diff options
Diffstat (limited to 'bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler')
309 files changed, 0 insertions, 85692 deletions
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. ".js") - * e.g. "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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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 Binary files differdeleted 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 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); - } - -} |