From f6829621e6d552e65409c5bdc2d32a738f37a373 Mon Sep 17 00:00:00 2001 From: khartlage Date: Mon, 27 Jan 2003 17:47:49 +0000 Subject: [PATCH 01/16] Config editor through XML file --- net.sourceforge.phpeclipse/plugin.xml | 168 +- .../internal/compiler/codegen/CodeStream.java |11268 ++++++++-------- .../phpdt/internal/compiler/parser/Parser.java |14671 ++++++++++---------- .../phpeclipse/IPreferenceConstants.java | 133 +- .../src/net/sourceforge/phpeclipse/PHPCore.java | 10 +- .../phpeclipse/PHPEclipseBasePreferencePage.java | 208 + .../phpeclipse/PHPEclipsePreferencePage.java | 115 - .../phpeclipse/PHPLanguagePreferencePage.java | 76 + .../phpeclipse/PHPOutlinePreferencePage.java | 56 + .../phpeclipse/PHPSyntaxEditorPreferencePage.java | 464 + .../phpeclipse/PHPSyntaxPreferencePage.java | 64 - .../sourceforge/phpeclipse/PHPeclipsePlugin.java | 87 +- .../newPHPPreferencesMessages_DE.properties | 65 + .../newPHPPreferencesMessages_FR.properties | 65 + .../newPHPPreferencesMessages_en_GB.properties | 64 + .../phpeclipse/phpeditor/PHPSyntaxRdr.java | 276 + .../phpeclipse/phpeditor/PHPTextHover.java | 37 +- .../phpeclipse/phpeditor/PresentationAction.java | 56 +- .../phpeclipse/phpeditor/SyntaxError.java | 64 - .../phpeclipse/phpeditor/php/PHPCodeScanner.java | 220 +- .../phpeclipse/phpeditor/php/PHPConstant.java | 16 + .../phpeclipse/phpeditor/php/PHPElement.java | 33 + .../phpeclipse/phpeditor/php/PHPFunction.java | 20 + .../phpeditor/php/PHPFunctionDescription.java | 2388 ---- .../phpeclipse/phpeditor/php/PHPKeyword.java | 29 + .../phpeclipse/phpeditor/php/PHPType.java | 15 + .../sourceforge/phpeclipse/phpeditor/phpsyntax.xml | 2416 ++++ .../phpeditor/util/HTMLColorProvider.java | 2 +- .../phpeditor/util/PHPColorProvider.java | 73 +- .../phpeclipse/preferences/ColorEditor.java | 116 + .../preferences/OverlayPreferenceStore.java | 443 + .../preferences/PHPPreferencesMessages.java | 62 +- .../preferences/PHPProjectLibraryPage.java | 237 +- .../preferences/PHPProjectPropertyPage.java | 144 +- 34 files changed, 18046 insertions(+), 16115 deletions(-) create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipseBasePreferencePage.java delete mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipsePreferencePage.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPOutlinePreferencePage.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java delete mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxPreferencePage.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_DE.properties create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_en_GB.properties create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java delete mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/SyntaxError.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java delete mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunctionDescription.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/phpsyntax.xml create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java diff --git a/net.sourceforge.phpeclipse/plugin.xml b/net.sourceforge.phpeclipse/plugin.xml index 7783dea..5725887 100644 --- a/net.sourceforge.phpeclipse/plugin.xml +++ b/net.sourceforge.phpeclipse/plugin.xml @@ -2,7 +2,7 @@ @@ -92,23 +92,42 @@ Create a new PHP project. + + + + Create a Xaraya module. + + + + + id="net.sourceforge.phpeclipse..ProjectNatureImagePHP"> - - - - + --> - + id="net.sourceforge.phpeclipse.phpeditor.comment"> + id="net.sourceforge.phpeclipse.phpeditor.uncomment"> + id="net.sourceforge.phpeclipse.phpeditor.comment"> + id="net.sourceforge.phpeclipse.phpeditor.uncomment"> - + --> - - - - - - - - - - - - - - - - - - - - - - - - - - - + class="net.sourceforge.phpeclipse.PHPSyntaxEditorPreferencePage" + id="net.sourceforge.phpeclipse.preference.PHPSyntaxEditorPreferencePage"> - + + + + + @@ -552,30 +516,6 @@ - - - - - - - - - - - - Tracking Max Stack. + // -> Tracking Max Stack. - public int stackMax; // Use Ints to keep from using extra bc when adding - public int stackDepth; // Use Ints to keep from using extra bc when adding - public int maxLocals; - public static final int max = 100; // Maximum size of the code array - public static final int growFactor = 400; - public static final int LABELS_INCREMENT = 5; - public byte[] bCodeStream; - public int pcToSourceMapSize; - public int[] pcToSourceMap = new int[24]; - public int lastEntryPC; // last entry recorded - public int[] lineSeparatorPositions; - public int position; // So when first set can be incremented - public int classFileOffset; - public int startingClassFileOffset; // I need to keep the starting point inside the byte array - public ConstantPool constantPool; // The constant pool used to generate bytecodes that need to store information into the constant pool - public ClassFile classFile; // The current classfile it is associated to. - // local variable attributes output - public static final int LOCALS_INCREMENT = 10; - public LocalVariableBinding[] locals = new LocalVariableBinding[LOCALS_INCREMENT]; - static LocalVariableBinding[] noLocals = new LocalVariableBinding[LOCALS_INCREMENT]; - public LocalVariableBinding[] visibleLocals = new LocalVariableBinding[LOCALS_INCREMENT]; - static LocalVariableBinding[] noVisibleLocals = new LocalVariableBinding[LOCALS_INCREMENT]; - int visibleLocalsCount; - public AbstractMethodDeclaration methodDeclaration; - public ExceptionLabel[] exceptionHandlers = new ExceptionLabel[LABELS_INCREMENT]; - static ExceptionLabel[] noExceptionHandlers = new ExceptionLabel[LABELS_INCREMENT]; - public int exceptionHandlersNumber; - public static FieldBinding[] ImplicitThis = new FieldBinding[] {}; - public boolean generateLineNumberAttributes; - public boolean generateLocalVariableTableAttributes; - public boolean preserveUnusedLocals; - // store all the labels placed at the current position to be able to optimize - // a jump to the next bytecode. - public Label[] labels = new Label[LABELS_INCREMENT]; - static Label[] noLabels = new Label[LABELS_INCREMENT]; - public int countLabels; - public int allLocalsCounter; - public int maxFieldCount; - // to handle goto_w - public boolean wideMode = false; - public static final CompilationResult RESTART_IN_WIDE_MODE = new CompilationResult((char[])null, 0, 0, 0); - -public CodeStream(ClassFile classFile) { - generateLineNumberAttributes = (classFile.produceDebugAttributes & CompilerOptions.Lines) != 0; - generateLocalVariableTableAttributes = (classFile.produceDebugAttributes & CompilerOptions.Vars) != 0; - if (generateLineNumberAttributes) { - lineSeparatorPositions = classFile.referenceBinding.scope.referenceCompilationUnit().compilationResult.lineSeparatorPositions; - } -} -final public void aaload() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_aaload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aaload); - } -} -final public void aastore() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_aastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aastore); - } -} -final public void aconst_null() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_aconst_null; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aconst_null); - } -} -public final void addDefinitelyAssignedVariables(Scope scope, int initStateIndex) { - // Required to fix 1PR0XVS: LFRE:WINNT - Compiler: variable table for method appears incorrect - if (!generateLocalVariableTableAttributes) - return; -/* if (initStateIndex == lastInitStateIndexWhenAddingInits) - return; - lastInitStateIndexWhenAddingInits = initStateIndex; - if (lastInitStateIndexWhenRemovingInits != initStateIndex){ - lastInitStateIndexWhenRemovingInits = -2; // reinitialize remove index - // remove(1)-add(1)-remove(1) -> ignore second remove - // remove(1)-add(2)-remove(1) -> perform second remove - } - -*/ for (int i = 0; i < visibleLocalsCount; i++) { - LocalVariableBinding localBinding = visibleLocals[i]; - if (localBinding != null) { - // Check if the local is definitely assigned - if ((initStateIndex != -1) && isDefinitelyAssigned(scope, initStateIndex, localBinding)) { - if ((localBinding.initializationCount == 0) || (localBinding.initializationPCs[((localBinding.initializationCount - 1) << 1) + 1] != -1)) { - /* There are two cases: - * 1) there is no initialization interval opened ==> add an opened interval - * 2) there is already some initialization intervals but the last one is closed ==> add an opened interval - * An opened interval means that the value at localBinding.initializationPCs[localBinding.initializationCount - 1][1] - * is equals to -1. - * initializationPCs is a collection of pairs of int: - * first value is the startPC and second value is the endPC. -1 one for the last value means that the interval - * is not closed yet. - */ - localBinding.recordInitializationStartPC(position); - } - } - } - } -} -public void addLabel(Label aLabel) { - if (countLabels == labels.length) - System.arraycopy(labels, 0, (labels = new Label[countLabels + LABELS_INCREMENT]), 0, countLabels); - labels[countLabels++] = aLabel; -} -public void addVisibleLocalVariable(LocalVariableBinding localBinding) { - if (!generateLocalVariableTableAttributes) - return; + public int stackMax; // Use Ints to keep from using extra bc when adding + public int stackDepth; // Use Ints to keep from using extra bc when adding + public int maxLocals; + public static final int max = 100; // Maximum size of the code array + public static final int growFactor = 400; + public static final int LABELS_INCREMENT = 5; + public byte[] bCodeStream; + public int pcToSourceMapSize; + public int[] pcToSourceMap = new int[24]; + public int lastEntryPC; // last entry recorded + public int[] lineSeparatorPositions; + public int position; // So when first set can be incremented + public int classFileOffset; + public int startingClassFileOffset; // I need to keep the starting point inside the byte array + public ConstantPool constantPool; + // The constant pool used to generate bytecodes that need to store information into the constant pool + public ClassFile classFile; // The current classfile it is associated to. + // local variable attributes output + public static final int LOCALS_INCREMENT = 10; + public LocalVariableBinding[] locals = new LocalVariableBinding[LOCALS_INCREMENT]; + static LocalVariableBinding[] noLocals = new LocalVariableBinding[LOCALS_INCREMENT]; + public LocalVariableBinding[] visibleLocals = new LocalVariableBinding[LOCALS_INCREMENT]; + static LocalVariableBinding[] noVisibleLocals = new LocalVariableBinding[LOCALS_INCREMENT]; + int visibleLocalsCount; + public AbstractMethodDeclaration methodDeclaration; + public ExceptionLabel[] exceptionHandlers = new ExceptionLabel[LABELS_INCREMENT]; + static ExceptionLabel[] noExceptionHandlers = new ExceptionLabel[LABELS_INCREMENT]; + public int exceptionHandlersNumber; + public static FieldBinding[] ImplicitThis = new FieldBinding[] { + }; + public boolean generateLineNumberAttributes; + public boolean generateLocalVariableTableAttributes; + public boolean preserveUnusedLocals; + // store all the labels placed at the current position to be able to optimize + // a jump to the next bytecode. + public Label[] labels = new Label[LABELS_INCREMENT]; + static Label[] noLabels = new Label[LABELS_INCREMENT]; + public int countLabels; + public int allLocalsCounter; + public int maxFieldCount; + // to handle goto_w + public boolean wideMode = false; + public static final CompilationResult RESTART_IN_WIDE_MODE = new CompilationResult((char[]) null, 0, 0, 0); - if (visibleLocalsCount >= visibleLocals.length) { - System.arraycopy(visibleLocals, 0, (visibleLocals = new LocalVariableBinding[visibleLocalsCount * 2]), 0, visibleLocalsCount); - } - visibleLocals[visibleLocalsCount++] = localBinding; -} -final public void aload(int iArg) { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals <= iArg) { - maxLocals = iArg + 1; - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_aload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aload); - } - writeUnsignedShort(iArg); - } else { - // Don't need to use the wide bytecode - try { - position++; - bCodeStream[classFileOffset++] = OPC_aload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aload); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) (iArg); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void aload_0() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals == 0) { - maxLocals = 1; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_aload_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aload_0); - } -} -final public void aload_1() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals <= 1) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_aload_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aload_1); - } -} -final public void aload_2() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals <= 2) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_aload_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aload_2); - } -} -final public void aload_3() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals <= 3) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_aload_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_aload_3); - } -} -public final void anewarray(TypeBinding typeBinding) { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_anewarray; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_anewarray); - } - writeUnsignedShort(constantPool.literalIndex(typeBinding)); -} -public void anewarrayJavaLangClass() { - // anewarray: java.lang.Class - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_anewarray; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_anewarray); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangClass()); -} -public void anewarrayJavaLangObject() { - // anewarray: java.lang.Object - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_anewarray; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_anewarray); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangObject()); -} -final public void areturn() { - countLabels = 0; - stackDepth--; - // the stackDepth should be equal to 0 - try { - position++; - bCodeStream[classFileOffset++] = OPC_areturn; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_areturn); - } -} -public void arrayAt(int typeBindingID) { - switch (typeBindingID) { - case T_int : - this.iaload(); - break; - case T_byte : - case T_boolean : - this.baload(); - break; - case T_short : - this.saload(); - break; - case T_char : - this.caload(); - break; - case T_long : - this.laload(); - break; - case T_float : - this.faload(); - break; - case T_double : - this.daload(); - break; - default : - this.aaload(); - } -} -public void arrayAtPut(int elementTypeID, boolean valueRequired) { - switch (elementTypeID) { - case T_int : - if (valueRequired) - dup_x2(); - iastore(); - break; - case T_byte : - case T_boolean : - if (valueRequired) - dup_x2(); - bastore(); - break; - case T_short : - if (valueRequired) - dup_x2(); - sastore(); - break; - case T_char : - if (valueRequired) - dup_x2(); - castore(); - break; - case T_long : - if (valueRequired) - dup2_x2(); - lastore(); - break; - case T_float : - if (valueRequired) - dup_x2(); - fastore(); - break; - case T_double : - if (valueRequired) - dup2_x2(); - dastore(); - break; - default : - if (valueRequired) - dup_x2(); - aastore(); - } -} -final public void arraylength() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_arraylength; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_arraylength); - } -} -final public void astore(int iArg) { - countLabels = 0; - stackDepth--; - if (maxLocals <= iArg) { - maxLocals = iArg + 1; - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_astore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_astore); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_astore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_astore); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void astore_0() { - countLabels = 0; - stackDepth--; - if (maxLocals == 0) { - maxLocals = 1; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_astore_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_astore_0); - } -} -final public void astore_1() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 1) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_astore_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_astore_1); - } -} -final public void astore_2() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 2) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_astore_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_astore_2); - } -} -final public void astore_3() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 3) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_astore_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_astore_3); - } -} -final public void athrow() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_athrow; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_athrow); - } -} -final public void baload() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_baload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_baload); - } -} -final public void bastore() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_bastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_bastore); - } -} -final public void bipush(byte b) { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_bipush; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_bipush); - } - writeSignedByte(b); -} -final public void caload() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_caload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_caload); - } -} -final public void castore() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_castore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_castore); - } -} -public final void checkcast(TypeBinding typeBinding) { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_checkcast; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_checkcast); - } - writeUnsignedShort(constantPool.literalIndex(typeBinding)); -} -public final void checkcastJavaLangError() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_checkcast; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_checkcast); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangError()); -} -final public void d2f() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_d2f; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_d2f); - } -} -final public void d2i() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_d2i; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_d2i); - } -} -final public void d2l() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_d2l; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_d2l); - } -} -final public void dadd() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dadd; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dadd); - } -} -final public void daload() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_daload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_daload); - } -} -final public void dastore() { - countLabels = 0; - stackDepth -= 4; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dastore); - } -} -final public void dcmpg() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dcmpg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dcmpg); - } -} -final public void dcmpl() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dcmpl; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dcmpl); - } -} -final public void dconst_0() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dconst_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dconst_0); - } -} -final public void dconst_1() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dconst_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dconst_1); - } -} -final public void ddiv() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ddiv; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ddiv); - } -} -public void decrStackSize(int offset) { - stackDepth -= offset; -} -final public void dload(int iArg) { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals < iArg + 2) { - maxLocals = iArg + 2; // + 2 because it is a double - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dload); - } - writeUnsignedShort(iArg); - } else { - // Don't need to use the wide bytecode - try { - position++; - bCodeStream[classFileOffset++] = OPC_dload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dload); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void dload_0() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals < 2) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dload_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dload_0); - } -} -final public void dload_1() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals < 3) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dload_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dload_1); - } -} -final public void dload_2() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals < 4) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dload_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dload_2); - } -} -final public void dload_3() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (maxLocals < 5) { - maxLocals = 5; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dload_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dload_3); - } -} -final public void dmul() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dmul; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dmul); - } -} -final public void dneg() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dneg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dneg); - } -} -final public void drem() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_drem; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_drem); - } -} -final public void dreturn() { - countLabels = 0; - stackDepth -= 2; - // the stackDepth should be equal to 0 - try { - position++; - bCodeStream[classFileOffset++] = OPC_dreturn; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dreturn); - } -} -final public void dstore(int iArg) { - countLabels = 0; - stackDepth -= 2; - if (maxLocals <= iArg + 1) { - maxLocals = iArg + 2; - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dstore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dstore); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_dstore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dstore); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void dstore_0() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 2) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dstore_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dstore_0); - } -} -final public void dstore_1() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 3) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dstore_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dstore_1); - } -} -final public void dstore_2() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 4) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dstore_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dstore_2); - } -} -final public void dstore_3() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 5) { - maxLocals = 5; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_dstore_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dstore_3); - } -} -final public void dsub() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dsub; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dsub); - } -} -final public void dup() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dup; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dup); - } -} -final public void dup_x1() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dup_x1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dup_x1); - } -} -final public void dup_x2() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dup_x2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dup_x2); - } -} -final public void dup2() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dup2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dup2); - } -} -final public void dup2_x1() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dup2_x1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dup2_x1); - } -} -final public void dup2_x2() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_dup2_x2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_dup2_x2); - } -} -public void exitUserScope(BlockScope blockScope) { - // mark all the scope's locals as loosing their definite assignment + public CodeStream(ClassFile classFile) { + generateLineNumberAttributes = (classFile.produceDebugAttributes & CompilerOptions.Lines) != 0; + generateLocalVariableTableAttributes = (classFile.produceDebugAttributes & CompilerOptions.Vars) != 0; + if (generateLineNumberAttributes) { + lineSeparatorPositions = classFile.referenceBinding.scope.referenceCompilationUnit().compilationResult.lineSeparatorPositions; + } + } + final public void aaload() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_aaload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aaload); + } + } + final public void aastore() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_aastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aastore); + } + } + final public void aconst_null() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_aconst_null; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aconst_null); + } + } + public final void addDefinitelyAssignedVariables(Scope scope, int initStateIndex) { + // Required to fix 1PR0XVS: LFRE:WINNT - Compiler: variable table for method appears incorrect + if (!generateLocalVariableTableAttributes) + return; + /* if (initStateIndex == lastInitStateIndexWhenAddingInits) + return; + lastInitStateIndexWhenAddingInits = initStateIndex; + if (lastInitStateIndexWhenRemovingInits != initStateIndex){ + lastInitStateIndexWhenRemovingInits = -2; // reinitialize remove index + // remove(1)-add(1)-remove(1) -> ignore second remove + // remove(1)-add(2)-remove(1) -> perform second remove + } + + */ + for (int i = 0; i < visibleLocalsCount; i++) { + LocalVariableBinding localBinding = visibleLocals[i]; + if (localBinding != null) { + // Check if the local is definitely assigned + if ((initStateIndex != -1) && isDefinitelyAssigned(scope, initStateIndex, localBinding)) { + if ((localBinding.initializationCount == 0) + || (localBinding.initializationPCs[((localBinding.initializationCount - 1) << 1) + 1] != -1)) { + /* There are two cases: + * 1) there is no initialization interval opened ==> add an opened interval + * 2) there is already some initialization intervals but the last one is closed ==> add an opened interval + * An opened interval means that the value at localBinding.initializationPCs[localBinding.initializationCount - 1][1] + * is equals to -1. + * initializationPCs is a collection of pairs of int: + * first value is the startPC and second value is the endPC. -1 one for the last value means that the interval + * is not closed yet. + */ + localBinding.recordInitializationStartPC(position); + } + } + } + } + } + public void addLabel(Label aLabel) { + if (countLabels == labels.length) + System.arraycopy(labels, 0, (labels = new Label[countLabels + LABELS_INCREMENT]), 0, countLabels); + labels[countLabels++] = aLabel; + } + public void addVisibleLocalVariable(LocalVariableBinding localBinding) { + if (!generateLocalVariableTableAttributes) + return; - if (!generateLocalVariableTableAttributes) - return; - for (int i = 0; i < visibleLocalsCount; i++) { - LocalVariableBinding visibleLocal = visibleLocals[i]; - if ((visibleLocal != null) && (visibleLocal.declaringScope == blockScope)) { - // there maybe some some preserved locals never initialized - if (visibleLocal.initializationCount > 0){ - visibleLocals[i].recordInitializationEndPC(position); - } - visibleLocals[i] = null; // this variable is no longer visible afterwards - } - } -} -final public void f2d() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_f2d; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_f2d); - } -} -final public void f2i() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_f2i; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_f2i); - } -} -final public void f2l() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_f2l; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_f2l); - } -} -final public void fadd() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fadd; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fadd); - } -} -final public void faload() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_faload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_faload); - } -} -final public void fastore() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fastore); - } -} -final public void fcmpg() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fcmpg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fcmpg); - } -} -final public void fcmpl() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fcmpl; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fcmpl); - } -} -final public void fconst_0() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fconst_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fconst_0); - } -} -final public void fconst_1() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fconst_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fconst_1); - } -} -final public void fconst_2() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fconst_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fconst_2); - } -} -final public void fdiv() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fdiv; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fdiv); - } -} -final public void fload(int iArg) { - countLabels = 0; - stackDepth++; - if (maxLocals <= iArg) { - maxLocals = iArg + 1; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_fload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fload); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_fload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fload); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void fload_0() { - countLabels = 0; - stackDepth++; - if (maxLocals == 0) { - maxLocals = 1; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fload_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fload_0); - } -} -final public void fload_1() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 1) { - maxLocals = 2; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fload_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fload_1); - } -} -final public void fload_2() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 2) { - maxLocals = 3; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fload_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fload_2); - } -} -final public void fload_3() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 3) { - maxLocals = 4; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fload_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fload_3); - } -} -final public void fmul() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fmul; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fmul); - } -} -final public void fneg() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fneg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fneg); - } -} -final public void frem() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_frem; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_frem); - } -} -final public void freturn() { - countLabels = 0; - stackDepth--; - // the stackDepth should be equal to 0 - try { - position++; - bCodeStream[classFileOffset++] = OPC_freturn; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_freturn); - } -} -final public void fstore(int iArg) { - countLabels = 0; - stackDepth--; - if (maxLocals <= iArg) { - maxLocals = iArg + 1; - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_fstore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fstore); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_fstore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fstore); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void fstore_0() { - countLabels = 0; - stackDepth--; - if (maxLocals == 0) { - maxLocals = 1; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_fstore_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fstore_0); - } -} -final public void fstore_1() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 1) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_fstore_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fstore_1); - } -} -final public void fstore_2() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 2) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_fstore_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fstore_2); - } -} -final public void fstore_3() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 3) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_fstore_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fstore_3); - } -} -final public void fsub() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_fsub; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_fsub); - } -} -/** - * Macro for building a class descriptor object - */ -public void generateClassLiteralAccessForType(TypeBinding accessedType, FieldBinding syntheticFieldBinding) { - Label endLabel; - ExceptionLabel anyExceptionHandler; - int saveStackSize; - if (accessedType.isBaseType() && accessedType != NullBinding) { - this.getTYPE(accessedType.id); - return; - } - endLabel = new Label(this); + if (visibleLocalsCount >= visibleLocals.length) { + System.arraycopy(visibleLocals, 0, (visibleLocals = new LocalVariableBinding[visibleLocalsCount * 2]), 0, visibleLocalsCount); + } + visibleLocals[visibleLocalsCount++] = localBinding; + } + final public void aload(int iArg) { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals <= iArg) { + maxLocals = iArg + 1; + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_aload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aload); + } + writeUnsignedShort(iArg); + } else { + // Don't need to use the wide bytecode + try { + position++; + bCodeStream[classFileOffset++] = OPC_aload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aload); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) (iArg); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void aload_0() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals == 0) { + maxLocals = 1; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_aload_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aload_0); + } + } + final public void aload_1() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals <= 1) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_aload_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aload_1); + } + } + final public void aload_2() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals <= 2) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_aload_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aload_2); + } + } + final public void aload_3() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals <= 3) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_aload_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_aload_3); + } + } + public final void anewarray(TypeBinding typeBinding) { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_anewarray; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_anewarray); + } + writeUnsignedShort(constantPool.literalIndex(typeBinding)); + } + public void anewarrayJavaLangClass() { + // anewarray: java.lang.Class + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_anewarray; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_anewarray); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangClass()); + } + public void anewarrayJavaLangObject() { + // anewarray: java.lang.Object + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_anewarray; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_anewarray); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangObject()); + } + final public void areturn() { + countLabels = 0; + stackDepth--; + // the stackDepth should be equal to 0 + try { + position++; + bCodeStream[classFileOffset++] = OPC_areturn; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_areturn); + } + } + public void arrayAt(int typeBindingID) { + switch (typeBindingID) { + case T_int : + this.iaload(); + break; + case T_byte : + case T_boolean : + this.baload(); + break; + case T_short : + this.saload(); + break; + case T_char : + this.caload(); + break; + case T_long : + this.laload(); + break; + case T_float : + this.faload(); + break; + case T_double : + this.daload(); + break; + default : + this.aaload(); + } + } + public void arrayAtPut(int elementTypeID, boolean valueRequired) { + switch (elementTypeID) { + case T_int : + if (valueRequired) + dup_x2(); + iastore(); + break; + case T_byte : + case T_boolean : + if (valueRequired) + dup_x2(); + bastore(); + break; + case T_short : + if (valueRequired) + dup_x2(); + sastore(); + break; + case T_char : + if (valueRequired) + dup_x2(); + castore(); + break; + case T_long : + if (valueRequired) + dup2_x2(); + lastore(); + break; + case T_float : + if (valueRequired) + dup_x2(); + fastore(); + break; + case T_double : + if (valueRequired) + dup2_x2(); + dastore(); + break; + default : + if (valueRequired) + dup_x2(); + aastore(); + } + } + final public void arraylength() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_arraylength; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_arraylength); + } + } + final public void astore(int iArg) { + countLabels = 0; + stackDepth--; + if (maxLocals <= iArg) { + maxLocals = iArg + 1; + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_astore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_astore); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_astore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_astore); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void astore_0() { + countLabels = 0; + stackDepth--; + if (maxLocals == 0) { + maxLocals = 1; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_astore_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_astore_0); + } + } + final public void astore_1() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 1) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_astore_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_astore_1); + } + } + final public void astore_2() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 2) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_astore_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_astore_2); + } + } + final public void astore_3() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 3) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_astore_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_astore_3); + } + } + final public void athrow() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_athrow; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_athrow); + } + } + final public void baload() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_baload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_baload); + } + } + final public void bastore() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_bastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_bastore); + } + } + final public void bipush(byte b) { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_bipush; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_bipush); + } + writeSignedByte(b); + } + final public void caload() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_caload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_caload); + } + } + final public void castore() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_castore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_castore); + } + } + public final void checkcast(TypeBinding typeBinding) { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_checkcast; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_checkcast); + } + writeUnsignedShort(constantPool.literalIndex(typeBinding)); + } + public final void checkcastJavaLangError() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_checkcast; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_checkcast); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangError()); + } + final public void d2f() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_d2f; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_d2f); + } + } + final public void d2i() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_d2i; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_d2i); + } + } + final public void d2l() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_d2l; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_d2l); + } + } + final public void dadd() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dadd; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dadd); + } + } + final public void daload() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_daload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_daload); + } + } + final public void dastore() { + countLabels = 0; + stackDepth -= 4; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dastore); + } + } + final public void dcmpg() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dcmpg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dcmpg); + } + } + final public void dcmpl() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dcmpl; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dcmpl); + } + } + final public void dconst_0() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dconst_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dconst_0); + } + } + final public void dconst_1() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dconst_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dconst_1); + } + } + final public void ddiv() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ddiv; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ddiv); + } + } + public void decrStackSize(int offset) { + stackDepth -= offset; + } + final public void dload(int iArg) { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals < iArg + 2) { + maxLocals = iArg + 2; // + 2 because it is a double + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dload); + } + writeUnsignedShort(iArg); + } else { + // Don't need to use the wide bytecode + try { + position++; + bCodeStream[classFileOffset++] = OPC_dload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dload); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void dload_0() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals < 2) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dload_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dload_0); + } + } + final public void dload_1() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals < 3) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dload_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dload_1); + } + } + final public void dload_2() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals < 4) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dload_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dload_2); + } + } + final public void dload_3() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (maxLocals < 5) { + maxLocals = 5; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dload_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dload_3); + } + } + final public void dmul() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dmul; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dmul); + } + } + final public void dneg() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dneg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dneg); + } + } + final public void drem() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_drem; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_drem); + } + } + final public void dreturn() { + countLabels = 0; + stackDepth -= 2; + // the stackDepth should be equal to 0 + try { + position++; + bCodeStream[classFileOffset++] = OPC_dreturn; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dreturn); + } + } + final public void dstore(int iArg) { + countLabels = 0; + stackDepth -= 2; + if (maxLocals <= iArg + 1) { + maxLocals = iArg + 2; + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dstore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dstore); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_dstore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dstore); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void dstore_0() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 2) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dstore_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dstore_0); + } + } + final public void dstore_1() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 3) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dstore_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dstore_1); + } + } + final public void dstore_2() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 4) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dstore_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dstore_2); + } + } + final public void dstore_3() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 5) { + maxLocals = 5; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_dstore_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dstore_3); + } + } + final public void dsub() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dsub; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dsub); + } + } + final public void dup() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dup; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dup); + } + } + final public void dup_x1() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dup_x1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dup_x1); + } + } + final public void dup_x2() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dup_x2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dup_x2); + } + } + final public void dup2() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dup2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dup2); + } + } + final public void dup2_x1() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dup2_x1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dup2_x1); + } + } + final public void dup2_x2() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_dup2_x2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_dup2_x2); + } + } + public void exitUserScope(BlockScope blockScope) { + // mark all the scope's locals as loosing their definite assignment - if (syntheticFieldBinding != null) { // non interface case - this.getstatic(syntheticFieldBinding); - this.dup(); - this.ifnonnull(endLabel); - this.pop(); - } + if (!generateLocalVariableTableAttributes) + return; + for (int i = 0; i < visibleLocalsCount; i++) { + LocalVariableBinding visibleLocal = visibleLocals[i]; + if ((visibleLocal != null) && (visibleLocal.declaringScope == blockScope)) { + // there maybe some some preserved locals never initialized + if (visibleLocal.initializationCount > 0) { + visibleLocals[i].recordInitializationEndPC(position); + } + visibleLocals[i] = null; // this variable is no longer visible afterwards + } + } + } + final public void f2d() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_f2d; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_f2d); + } + } + final public void f2i() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_f2i; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_f2i); + } + } + final public void f2l() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_f2l; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_f2l); + } + } + final public void fadd() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fadd; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fadd); + } + } + final public void faload() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_faload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_faload); + } + } + final public void fastore() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fastore); + } + } + final public void fcmpg() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fcmpg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fcmpg); + } + } + final public void fcmpl() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fcmpl; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fcmpl); + } + } + final public void fconst_0() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fconst_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fconst_0); + } + } + final public void fconst_1() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fconst_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fconst_1); + } + } + final public void fconst_2() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fconst_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fconst_2); + } + } + final public void fdiv() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fdiv; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fdiv); + } + } + final public void fload(int iArg) { + countLabels = 0; + stackDepth++; + if (maxLocals <= iArg) { + maxLocals = iArg + 1; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_fload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fload); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_fload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fload); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void fload_0() { + countLabels = 0; + stackDepth++; + if (maxLocals == 0) { + maxLocals = 1; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fload_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fload_0); + } + } + final public void fload_1() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 1) { + maxLocals = 2; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fload_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fload_1); + } + } + final public void fload_2() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 2) { + maxLocals = 3; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fload_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fload_2); + } + } + final public void fload_3() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 3) { + maxLocals = 4; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fload_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fload_3); + } + } + final public void fmul() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fmul; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fmul); + } + } + final public void fneg() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fneg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fneg); + } + } + final public void frem() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_frem; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_frem); + } + } + final public void freturn() { + countLabels = 0; + stackDepth--; + // the stackDepth should be equal to 0 + try { + position++; + bCodeStream[classFileOffset++] = OPC_freturn; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_freturn); + } + } + final public void fstore(int iArg) { + countLabels = 0; + stackDepth--; + if (maxLocals <= iArg) { + maxLocals = iArg + 1; + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_fstore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fstore); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_fstore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fstore); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void fstore_0() { + countLabels = 0; + stackDepth--; + if (maxLocals == 0) { + maxLocals = 1; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_fstore_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fstore_0); + } + } + final public void fstore_1() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 1) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_fstore_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fstore_1); + } + } + final public void fstore_2() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 2) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_fstore_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fstore_2); + } + } + final public void fstore_3() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 3) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_fstore_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fstore_3); + } + } + final public void fsub() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_fsub; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_fsub); + } + } + /** + * Macro for building a class descriptor object + */ + public void generateClassLiteralAccessForType(TypeBinding accessedType, FieldBinding syntheticFieldBinding) { + Label endLabel; + ExceptionLabel anyExceptionHandler; + int saveStackSize; + if (accessedType.isBaseType() && accessedType != NullBinding) { + this.getTYPE(accessedType.id); + return; + } + endLabel = new Label(this); - /* Macro for building a class descriptor object... using or not a field cache to store it into... - this sequence is responsible for building the actual class descriptor. - - If the fieldCache is set, then it is supposed to be the body of a synthetic access method - factoring the actual descriptor creation out of the invocation site (saving space). - If the fieldCache is nil, then we are dumping the bytecode on the invocation site, since - we have no way to get a hand on the field cache to do better. */ + if (syntheticFieldBinding != null) { // non interface case + this.getstatic(syntheticFieldBinding); + this.dup(); + this.ifnonnull(endLabel); + this.pop(); + } + /* Macro for building a class descriptor object... using or not a field cache to store it into... + this sequence is responsible for building the actual class descriptor. + + If the fieldCache is set, then it is supposed to be the body of a synthetic access method + factoring the actual descriptor creation out of the invocation site (saving space). + If the fieldCache is nil, then we are dumping the bytecode on the invocation site, since + we have no way to get a hand on the field cache to do better. */ - // Wrap the code in an exception handler to convert a ClassNotFoundException into a NoClassDefError + // Wrap the code in an exception handler to convert a ClassNotFoundException into a NoClassDefError - anyExceptionHandler = new ExceptionLabel(this, TypeBinding.NullBinding /* represents ClassNotFoundException*/); - this.ldc(accessedType == TypeBinding.NullBinding ? "java.lang.Object" : String.valueOf(accessedType.constantPoolName()).replace('/', '.')); //$NON-NLS-1$ - this.invokeClassForName(); + anyExceptionHandler = new ExceptionLabel(this, TypeBinding.NullBinding /* represents ClassNotFoundException*/ + ); + this.ldc(accessedType == TypeBinding.NullBinding ? "java.lang.Object" : String.valueOf(accessedType.constantPoolName()).replace('/', '.')); //$NON-NLS-1$ + this.invokeClassForName(); - /* We need to protect the runtime code from binary inconsistencies - in case the accessedType is missing, the ClassNotFoundException has to be converted - into a NoClassDefError(old ex message), we thus need to build an exception handler for this one. */ - anyExceptionHandler.placeEnd(); + /* We need to protect the runtime code from binary inconsistencies + in case the accessedType is missing, the ClassNotFoundException has to be converted + into a NoClassDefError(old ex message), we thus need to build an exception handler for this one. */ + anyExceptionHandler.placeEnd(); - if (syntheticFieldBinding != null) { // non interface case - this.dup(); - this.putstatic(syntheticFieldBinding); - } - this.goto_(endLabel); + if (syntheticFieldBinding != null) { // non interface case + this.dup(); + this.putstatic(syntheticFieldBinding); + } + this.goto_(endLabel); + // Generate the body of the exception handler + saveStackSize = stackDepth; + stackDepth = 1; + /* ClassNotFoundException on stack -- the class literal could be doing more things + on the stack, which means that the stack may not be empty at this point in the + above code gen. So we save its state and restart it from 1. */ - // Generate the body of the exception handler - saveStackSize = stackDepth; - stackDepth = 1; - /* ClassNotFoundException on stack -- the class literal could be doing more things - on the stack, which means that the stack may not be empty at this point in the - above code gen. So we save its state and restart it from 1. */ + anyExceptionHandler.place(); - anyExceptionHandler.place(); + // Transform the current exception, and repush and throw a + // NoClassDefFoundError(ClassNotFound.getMessage()) - // Transform the current exception, and repush and throw a - // NoClassDefFoundError(ClassNotFound.getMessage()) + this.newNoClassDefFoundError(); + this.dup_x1(); + this.swap(); - this.newNoClassDefFoundError(); - this.dup_x1(); - this.swap(); + // Retrieve the message from the old exception + this.invokeThrowableGetMessage(); - // Retrieve the message from the old exception - this.invokeThrowableGetMessage(); + // Send the constructor taking a message string as an argument + this.invokeNoClassDefFoundErrorStringConstructor(); + this.athrow(); + endLabel.place(); + stackDepth = saveStackSize; + } + /** + * This method returns the exception handler to be able to generate the exception handler + * attribute. + */ + final public int[] generateCodeAttributeForProblemMethod(String errorName, String problemMessage) { + /** + * Equivalent code: + * try { + * throw ((Error) (Class.forName(errorName).getConstructor(new Class[] {Class.forName("java.lang.String")})).newInstance(new Object[] {problemMessage})); + * } catch (Exception e) { + * throw (NullPointerException) null; + * } + */ + int endPC, handlerPC; + ldc(errorName); + invokeClassForName(); + iconst_1(); + anewarrayJavaLangClass(); + dup(); + iconst_0(); + ldc("java.lang.String"); //$NON-NLS-1$ + invokeClassForName(); + aastore(); + invokeConstructorGetConstructor(); + iconst_1(); + anewarrayJavaLangObject(); + dup(); + iconst_0(); + ldc(problemMessage); + aastore(); + invokeObjectNewInstance(); + checkcastJavaLangError(); + athrow(); + endPC = handlerPC = position; + pop(); + aconst_null(); + athrow(); + return_(); + return new int[] { 0, endPC, handlerPC }; + } + public void generateConstant(Constant constant, int implicitConversionCode) { + int targetTypeID = implicitConversionCode >> 4; + switch (targetTypeID) { + case T_boolean : + generateInlinedValue(constant.booleanValue()); + break; + case T_char : + generateInlinedValue(constant.charValue()); + break; + case T_byte : + generateInlinedValue(constant.byteValue()); + break; + case T_short : + generateInlinedValue(constant.shortValue()); + break; + case T_int : + generateInlinedValue(constant.intValue()); + break; + case T_long : + generateInlinedValue(constant.longValue()); + break; + case T_float : + generateInlinedValue(constant.floatValue()); + break; + case T_double : + generateInlinedValue(constant.doubleValue()); + break; + case T_String : + this.ldc(constant.stringValue()); + break; + default : //reference object (constant can be from T_null or T_String) + if (constant.typeID() == T_String) + ldc(constant.stringValue()); + else + aconst_null(); + } + } + /** + * @param implicitConversionCode int + */ + public void generateImplicitConversion(int implicitConversionCode) { + switch (implicitConversionCode) { + case Float2Char : + this.f2i(); + this.i2c(); + break; + case Double2Char : + this.d2i(); + this.i2c(); + break; + case Int2Char : + case Short2Char : + case Byte2Char : + this.i2c(); + break; + case Long2Char : + this.l2i(); + this.i2c(); + break; + case Char2Float : + case Short2Float : + case Int2Float : + case Byte2Float : + this.i2f(); + break; + case Double2Float : + this.d2f(); + break; + case Long2Float : + this.l2f(); + break; + case Float2Byte : + this.f2i(); + this.i2b(); + break; + case Double2Byte : + this.d2i(); + this.i2b(); + break; + case Int2Byte : + case Short2Byte : + case Char2Byte : + this.i2b(); + break; + case Long2Byte : + this.l2i(); + this.i2b(); + break; + case Byte2Double : + case Char2Double : + case Short2Double : + case Int2Double : + this.i2d(); + break; + case Float2Double : + this.f2d(); + break; + case Long2Double : + this.l2d(); + break; + case Byte2Short : + case Char2Short : + case Int2Short : + this.i2s(); + break; + case Double2Short : + this.d2i(); + this.i2s(); + break; + case Long2Short : + this.l2i(); + this.i2s(); + break; + case Float2Short : + this.f2i(); + this.i2s(); + break; + case Double2Int : + this.d2i(); + break; + case Float2Int : + this.f2i(); + break; + case Long2Int : + this.l2i(); + break; + case Int2Long : + case Char2Long : + case Byte2Long : + case Short2Long : + this.i2l(); + break; + case Double2Long : + this.d2l(); + break; + case Float2Long : + this.f2l(); + } + } + public void generateInlinedValue(byte inlinedValue) { + switch (inlinedValue) { + case -1 : + this.iconst_m1(); + break; + case 0 : + this.iconst_0(); + break; + case 1 : + this.iconst_1(); + break; + case 2 : + this.iconst_2(); + break; + case 3 : + this.iconst_3(); + break; + case 4 : + this.iconst_4(); + break; + case 5 : + this.iconst_5(); + break; + default : + if ((-128 <= inlinedValue) && (inlinedValue <= 127)) { + this.bipush((byte) inlinedValue); + return; + } + } + } + public void generateInlinedValue(char inlinedValue) { + switch (inlinedValue) { + case 0 : + this.iconst_0(); + break; + case 1 : + this.iconst_1(); + break; + case 2 : + this.iconst_2(); + break; + case 3 : + this.iconst_3(); + break; + case 4 : + this.iconst_4(); + break; + case 5 : + this.iconst_5(); + break; + default : + if ((6 <= inlinedValue) && (inlinedValue <= 127)) { + this.bipush((byte) inlinedValue); + return; + } + if ((128 <= inlinedValue) && (inlinedValue <= 32767)) { + this.sipush(inlinedValue); + return; + } + this.ldc(inlinedValue); + } + } + public void generateInlinedValue(double inlinedValue) { + if (inlinedValue == 0.0) { + if (Double.doubleToLongBits(inlinedValue) != 0L) + this.ldc2_w(inlinedValue); + else + this.dconst_0(); + return; + } + if (inlinedValue == 1.0) { + this.dconst_1(); + return; + } + this.ldc2_w(inlinedValue); + } + public void generateInlinedValue(float inlinedValue) { + if (inlinedValue == 0.0f) { + if (Float.floatToIntBits(inlinedValue) != 0) + this.ldc(inlinedValue); + else + this.fconst_0(); + return; + } + if (inlinedValue == 1.0f) { + this.fconst_1(); + return; + } + if (inlinedValue == 2.0f) { + this.fconst_2(); + return; + } + this.ldc(inlinedValue); + } + public void generateInlinedValue(int inlinedValue) { + switch (inlinedValue) { + case -1 : + this.iconst_m1(); + break; + case 0 : + this.iconst_0(); + break; + case 1 : + this.iconst_1(); + break; + case 2 : + this.iconst_2(); + break; + case 3 : + this.iconst_3(); + break; + case 4 : + this.iconst_4(); + break; + case 5 : + this.iconst_5(); + break; + default : + if ((-128 <= inlinedValue) && (inlinedValue <= 127)) { + this.bipush((byte) inlinedValue); + return; + } + if ((-32768 <= inlinedValue) && (inlinedValue <= 32767)) { + this.sipush(inlinedValue); + return; + } + this.ldc(inlinedValue); + } + } + public void generateInlinedValue(long inlinedValue) { + if (inlinedValue == 0) { + this.lconst_0(); + return; + } + if (inlinedValue == 1) { + this.lconst_1(); + return; + } + this.ldc2_w(inlinedValue); + } + public void generateInlinedValue(short inlinedValue) { + switch (inlinedValue) { + case -1 : + this.iconst_m1(); + break; + case 0 : + this.iconst_0(); + break; + case 1 : + this.iconst_1(); + break; + case 2 : + this.iconst_2(); + break; + case 3 : + this.iconst_3(); + break; + case 4 : + this.iconst_4(); + break; + case 5 : + this.iconst_5(); + break; + default : + if ((-128 <= inlinedValue) && (inlinedValue <= 127)) { + this.bipush((byte) inlinedValue); + return; + } + this.sipush(inlinedValue); + } + } + public void generateInlinedValue(boolean inlinedValue) { + if (inlinedValue) + this.iconst_1(); + else + this.iconst_0(); + } + public void generateOuterAccess(Object[] mappingSequence, AstNode invocationSite, Scope scope) { + if (mappingSequence == null) + return; + if (mappingSequence == BlockScope.EmulationPathToImplicitThis) { + if (scope.methodScope().isConstructorCall) { + scope.problemReporter().errorThisSuperInStatic(invocationSite); + } + this.aload_0(); + return; + } + if (mappingSequence[0] instanceof FieldBinding) { + FieldBinding fieldBinding = (FieldBinding) mappingSequence[0]; + if (scope.methodScope().isConstructorCall) { + scope.problemReporter().errorThisSuperInStatic(invocationSite); + } + this.aload_0(); + this.getfield(fieldBinding); + } else { + load((LocalVariableBinding) mappingSequence[0]); + } + for (int i = 1, length = mappingSequence.length; i < length; i++) { + if (mappingSequence[i] instanceof FieldBinding) { + FieldBinding fieldBinding = (FieldBinding) mappingSequence[i]; + this.getfield(fieldBinding); + } else { + this.invokestatic((MethodBinding) mappingSequence[i]); + } + } + } + /** + * The equivalent code performs a string conversion: + * + * @param oper1 org.eclipse.jdt.internal.compiler.lookup.BlockScope + * @param oper1 org.eclipse.jdt.internal.compiler.ast.Expression + * @param oper2 org.eclipse.jdt.internal.compiler.ast.Expression + */ + public void generateStringAppend(BlockScope blockScope, Expression oper1, Expression oper2) { + int pc; + if (oper1 == null) { + /* Operand is already on the stack, and maybe nil: + note type1 is always to java.lang.String here.*/ + this.newStringBuffer(); + this.dup_x1(); + this.swap(); + // If argument is reference type, need to transform it + // into a string (handles null case) + this.invokeStringValueOf(T_Object); + this.invokeStringBufferStringConstructor(); + } else { + pc = position; + oper1.generateOptimizedStringBufferCreation(blockScope, this, oper1.implicitConversion & 0xF); + this.recordPositionsFrom(pc, oper1.sourceStart); + } + pc = position; + oper2.generateOptimizedStringBuffer(blockScope, this, oper2.implicitConversion & 0xF); + this.recordPositionsFrom(pc, oper2.sourceStart); + this.invokeStringBufferToString(); + } + /** + * Code responsible to generate the suitable code to supply values for the synthetic arguments of + * a constructor invocation of a nested type. + */ + public void generateSyntheticArgumentValues( + BlockScope currentScope, + ReferenceBinding targetType, + Expression enclosingInstance, + AstNode invocationSite) { - // Send the constructor taking a message string as an argument - this.invokeNoClassDefFoundErrorStringConstructor(); - this.athrow(); - endLabel.place(); - stackDepth = saveStackSize; -} -/** - * This method returns the exception handler to be able to generate the exception handler - * attribute. - */ -final public int[] generateCodeAttributeForProblemMethod(String errorName, String problemMessage) { - /** - * Equivalent code: - * try { - * throw ((Error) (Class.forName(errorName).getConstructor(new Class[] {Class.forName("java.lang.String")})).newInstance(new Object[] {problemMessage})); - * } catch (Exception e) { - * throw (NullPointerException) null; - * } - */ - int endPC, handlerPC; - ldc(errorName); - invokeClassForName(); - iconst_1(); - anewarrayJavaLangClass(); - dup(); - iconst_0(); - ldc("java.lang.String"); //$NON-NLS-1$ - invokeClassForName(); - aastore(); - invokeConstructorGetConstructor(); - iconst_1(); - anewarrayJavaLangObject(); - dup(); - iconst_0(); - ldc(problemMessage); - aastore(); - invokeObjectNewInstance(); - checkcastJavaLangError(); - athrow(); - endPC = handlerPC = position; - pop(); - aconst_null(); - athrow(); - return_(); - return new int[] {0, endPC, handlerPC}; -} -public void generateConstant(Constant constant, int implicitConversionCode) { - int targetTypeID = implicitConversionCode >> 4; - switch (targetTypeID) { - case T_boolean : - generateInlinedValue(constant.booleanValue()); - break; - case T_char : - generateInlinedValue(constant.charValue()); - break; - case T_byte : - generateInlinedValue(constant.byteValue()); - break; - case T_short : - generateInlinedValue(constant.shortValue()); - break; - case T_int : - generateInlinedValue(constant.intValue()); - break; - case T_long : - generateInlinedValue(constant.longValue()); - break; - case T_float : - generateInlinedValue(constant.floatValue()); - break; - case T_double : - generateInlinedValue(constant.doubleValue()); - break; - case T_String : - this.ldc(constant.stringValue()); - break; - default : //reference object (constant can be from T_null or T_String) - if (constant.typeID() == T_String) - ldc(constant.stringValue()); - else - aconst_null(); - } -} -/** - * @param implicitConversionCode int - */ -public void generateImplicitConversion(int implicitConversionCode) { - switch (implicitConversionCode) { - case Float2Char : - this.f2i(); - this.i2c(); - break; - case Double2Char : - this.d2i(); - this.i2c(); - break; - case Int2Char : - case Short2Char : - case Byte2Char : - this.i2c(); - break; - case Long2Char : - this.l2i(); - this.i2c(); - break; - case Char2Float : - case Short2Float : - case Int2Float : - case Byte2Float : - this.i2f(); - break; - case Double2Float : - this.d2f(); - break; - case Long2Float : - this.l2f(); - break; - case Float2Byte : - this.f2i(); - this.i2b(); - break; - case Double2Byte : - this.d2i(); - this.i2b(); - break; - case Int2Byte : - case Short2Byte : - case Char2Byte : - this.i2b(); - break; - case Long2Byte : - this.l2i(); - this.i2b(); - break; - case Byte2Double : - case Char2Double : - case Short2Double : - case Int2Double : - this.i2d(); - break; - case Float2Double : - this.f2d(); - break; - case Long2Double : - this.l2d(); - break; - case Byte2Short : - case Char2Short : - case Int2Short : - this.i2s(); - break; - case Double2Short : - this.d2i(); - this.i2s(); - break; - case Long2Short : - this.l2i(); - this.i2s(); - break; - case Float2Short : - this.f2i(); - this.i2s(); - break; - case Double2Int : - this.d2i(); - break; - case Float2Int : - this.f2i(); - break; - case Long2Int : - this.l2i(); - break; - case Int2Long : - case Char2Long : - case Byte2Long : - case Short2Long : - this.i2l(); - break; - case Double2Long : - this.d2l(); - break; - case Float2Long : - this.f2l(); - } -} -public void generateInlinedValue(byte inlinedValue) { - switch (inlinedValue) { - case -1 : - this.iconst_m1(); - break; - case 0 : - this.iconst_0(); - break; - case 1 : - this.iconst_1(); - break; - case 2 : - this.iconst_2(); - break; - case 3 : - this.iconst_3(); - break; - case 4 : - this.iconst_4(); - break; - case 5 : - this.iconst_5(); - break; - default : - if ((-128 <= inlinedValue) && (inlinedValue <= 127)) { - this.bipush((byte) inlinedValue); - return; - } - } -} -public void generateInlinedValue(char inlinedValue) { - switch (inlinedValue) { - case 0 : - this.iconst_0(); - break; - case 1 : - this.iconst_1(); - break; - case 2 : - this.iconst_2(); - break; - case 3 : - this.iconst_3(); - break; - case 4 : - this.iconst_4(); - break; - case 5 : - this.iconst_5(); - break; - default : - if ((6 <= inlinedValue) && (inlinedValue <= 127)) { - this.bipush((byte) inlinedValue); - return; - } - if ((128 <= inlinedValue) && (inlinedValue <= 32767)) { - this.sipush(inlinedValue); - return; - } - this.ldc(inlinedValue); - } -} -public void generateInlinedValue(double inlinedValue) { - if (inlinedValue == 0.0) { - if (Double.doubleToLongBits(inlinedValue) != 0L) - this.ldc2_w(inlinedValue); - else - this.dconst_0(); - return; - } - if (inlinedValue == 1.0) { - this.dconst_1(); - return; - } - this.ldc2_w(inlinedValue); -} -public void generateInlinedValue(float inlinedValue) { - if (inlinedValue == 0.0f) { - if (Float.floatToIntBits(inlinedValue) != 0) - this.ldc(inlinedValue); - else - this.fconst_0(); - return; - } - if (inlinedValue == 1.0f) { - this.fconst_1(); - return; - } - if (inlinedValue == 2.0f) { - this.fconst_2(); - return; - } - this.ldc(inlinedValue); -} -public void generateInlinedValue(int inlinedValue) { - switch (inlinedValue) { - case -1 : - this.iconst_m1(); - break; - case 0 : - this.iconst_0(); - break; - case 1 : - this.iconst_1(); - break; - case 2 : - this.iconst_2(); - break; - case 3 : - this.iconst_3(); - break; - case 4 : - this.iconst_4(); - break; - case 5 : - this.iconst_5(); - break; - default : - if ((-128 <= inlinedValue) && (inlinedValue <= 127)) { - this.bipush((byte) inlinedValue); - return; - } - if ((-32768 <= inlinedValue) && (inlinedValue <= 32767)) { - this.sipush(inlinedValue); - return; - } - this.ldc(inlinedValue); - } -} -public void generateInlinedValue(long inlinedValue) { - if (inlinedValue == 0) { - this.lconst_0(); - return; - } - if (inlinedValue == 1) { - this.lconst_1(); - return; - } - this.ldc2_w(inlinedValue); -} -public void generateInlinedValue(short inlinedValue) { - switch (inlinedValue) { - case -1 : - this.iconst_m1(); - break; - case 0 : - this.iconst_0(); - break; - case 1 : - this.iconst_1(); - break; - case 2 : - this.iconst_2(); - break; - case 3 : - this.iconst_3(); - break; - case 4 : - this.iconst_4(); - break; - case 5 : - this.iconst_5(); - break; - default : - if ((-128 <= inlinedValue) && (inlinedValue <= 127)) { - this.bipush((byte) inlinedValue); - return; - } - this.sipush(inlinedValue); - } -} -public void generateInlinedValue(boolean inlinedValue) { - if (inlinedValue) - this.iconst_1(); - else - this.iconst_0(); -} -public void generateOuterAccess(Object[] mappingSequence, AstNode invocationSite, Scope scope) { - if (mappingSequence == null) - return; - if (mappingSequence == BlockScope.EmulationPathToImplicitThis) { - if (scope.methodScope().isConstructorCall){ - scope.problemReporter().errorThisSuperInStatic(invocationSite); - } - this.aload_0(); - return; - } - if (mappingSequence[0] instanceof FieldBinding) { - FieldBinding fieldBinding = (FieldBinding) mappingSequence[0]; - if (scope.methodScope().isConstructorCall){ - scope.problemReporter().errorThisSuperInStatic(invocationSite); - } - this.aload_0(); - this.getfield(fieldBinding); - } else { - load((LocalVariableBinding) mappingSequence[0]); - } - for (int i = 1, length = mappingSequence.length; i < length; i++) { - if (mappingSequence[i] instanceof FieldBinding) { - FieldBinding fieldBinding = (FieldBinding) mappingSequence[i]; - this.getfield(fieldBinding); - } else { - this.invokestatic((MethodBinding) mappingSequence[i]); - } - } -} -/** - * The equivalent code performs a string conversion: - * - * @param oper1 org.eclipse.jdt.internal.compiler.lookup.BlockScope - * @param oper1 org.eclipse.jdt.internal.compiler.ast.Expression - * @param oper2 org.eclipse.jdt.internal.compiler.ast.Expression - */ -public void generateStringAppend(BlockScope blockScope, Expression oper1, Expression oper2) { - int pc; - if (oper1 == null) { - /* Operand is already on the stack, and maybe nil: - note type1 is always to java.lang.String here.*/ - this.newStringBuffer(); - this.dup_x1(); - this.swap(); - // If argument is reference type, need to transform it - // into a string (handles null case) - this.invokeStringValueOf(T_Object); - this.invokeStringBufferStringConstructor(); - } else { - pc = position; - oper1.generateOptimizedStringBufferCreation(blockScope, this, oper1.implicitConversion & 0xF); - this.recordPositionsFrom(pc, oper1.sourceStart); - } - pc = position; - oper2.generateOptimizedStringBuffer(blockScope, this, oper2.implicitConversion & 0xF); - this.recordPositionsFrom(pc, oper2.sourceStart); - this.invokeStringBufferToString(); -} -/** - * Code responsible to generate the suitable code to supply values for the synthetic arguments of - * a constructor invocation of a nested type. - */ -public void generateSyntheticArgumentValues(BlockScope currentScope, ReferenceBinding targetType, Expression enclosingInstance, AstNode invocationSite) { + // perform some emulation work in case there is some and we are inside a local type only + ReferenceBinding[] syntheticArgumentTypes; - // perform some emulation work in case there is some and we are inside a local type only - ReferenceBinding[] syntheticArgumentTypes; + // generate the enclosing instance first + if ((syntheticArgumentTypes = targetType.syntheticEnclosingInstanceTypes()) != null) { - // generate the enclosing instance first - if ((syntheticArgumentTypes = targetType.syntheticEnclosingInstanceTypes()) != null) { + ReferenceBinding targetEnclosingType = + targetType.isAnonymousType() + ? targetType.superclass().enclosingType() // supplying enclosing instance for the anonymous type's superclass + : targetType.enclosingType(); - ReferenceBinding targetEnclosingType = targetType.isAnonymousType() ? - targetType.superclass().enclosingType() // supplying enclosing instance for the anonymous type's superclass - : targetType.enclosingType(); - - for (int i = 0, max = syntheticArgumentTypes.length; i < max; i++) { - ReferenceBinding syntheticArgType = syntheticArgumentTypes[i]; - if (enclosingInstance != null && i == 0) { - if (syntheticArgType != targetEnclosingType) { - currentScope.problemReporter().unnecessaryEnclosingInstanceSpecification(enclosingInstance, targetType); - } - //if (currentScope.environment().options.complianceLevel >= CompilerOptions.JDK1_4){ - enclosingInstance.generateCode(currentScope, this, true); - if (syntheticArgType == targetEnclosingType){ - this.dup(); - } - this.invokeObjectGetClass(); // causes null check for all explicit enclosing instances - this.pop(); - //} else { - // enclosingInstance.generateCode(currentScope, this, syntheticArgType == targetEnclosingType); - //} - } else { - Object[] emulationPath = currentScope.getCompatibleEmulationPath(syntheticArgType); - if (emulationPath == null) { - currentScope.problemReporter().missingEnclosingInstanceSpecification(syntheticArgType, invocationSite); - } else { - this.generateOuterAccess(emulationPath, invocationSite, currentScope); - } - } - } - } else { // we may still have an enclosing instance to consider - if (enclosingInstance != null) { - currentScope.problemReporter().unnecessaryEnclosingInstanceSpecification(enclosingInstance, targetType); - //if (currentScope.environment().options.complianceLevel >= CompilerOptions.JDK1_4){ - enclosingInstance.generateCode(currentScope, this, true); - this.invokeObjectGetClass(); // causes null check for all explicit enclosing instances - this.pop(); - //} else { - // enclosingInstance.generateCode(currentScope, this, false); // do not want the value - //} - } - } - // generate the synthetic outer arguments then - SyntheticArgumentBinding syntheticArguments[]; - if ((syntheticArguments = targetType.syntheticOuterLocalVariables()) != null) { - for (int i = 0, max = syntheticArguments.length; i < max; i++) { - VariableBinding[] emulationPath = currentScope.getEmulationPath(syntheticArguments[i].actualOuterLocalVariable); - if (emulationPath == null) { - // could not emulate a path to a given outer local variable (internal error) - currentScope.problemReporter().needImplementation(); - } else { - this.generateOuterAccess(emulationPath, invocationSite, currentScope); - } - } - } -} -/** - * @param parameters org.eclipse.jdt.internal.compiler.lookup.TypeBinding[] - * @param constructorBinding org.eclipse.jdt.internal.compiler.lookup.MethodBinding - */ -public void generateSyntheticBodyForConstructorAccess(SyntheticAccessMethodBinding accessBinding) { + for (int i = 0, max = syntheticArgumentTypes.length; i < max; i++) { + ReferenceBinding syntheticArgType = syntheticArgumentTypes[i]; + if (enclosingInstance != null && i == 0) { + if (syntheticArgType != targetEnclosingType) { + currentScope.problemReporter().unnecessaryEnclosingInstanceSpecification(enclosingInstance, targetType); + } + //if (currentScope.environment().options.complianceLevel >= CompilerOptions.JDK1_4){ + enclosingInstance.generateCode(currentScope, this, true); + if (syntheticArgType == targetEnclosingType) { + this.dup(); + } + this.invokeObjectGetClass(); // causes null check for all explicit enclosing instances + this.pop(); + //} else { + // enclosingInstance.generateCode(currentScope, this, syntheticArgType == targetEnclosingType); + //} + } else { + Object[] emulationPath = currentScope.getCompatibleEmulationPath(syntheticArgType); + if (emulationPath == null) { + currentScope.problemReporter().missingEnclosingInstanceSpecification(syntheticArgType, invocationSite); + } else { + this.generateOuterAccess(emulationPath, invocationSite, currentScope); + } + } + } + } else { // we may still have an enclosing instance to consider + if (enclosingInstance != null) { + currentScope.problemReporter().unnecessaryEnclosingInstanceSpecification(enclosingInstance, targetType); + //if (currentScope.environment().options.complianceLevel >= CompilerOptions.JDK1_4){ + enclosingInstance.generateCode(currentScope, this, true); + this.invokeObjectGetClass(); // causes null check for all explicit enclosing instances + this.pop(); + //} else { + // enclosingInstance.generateCode(currentScope, this, false); // do not want the value + //} + } + } + // generate the synthetic outer arguments then + SyntheticArgumentBinding syntheticArguments[]; + if ((syntheticArguments = targetType.syntheticOuterLocalVariables()) != null) { + for (int i = 0, max = syntheticArguments.length; i < max; i++) { + VariableBinding[] emulationPath = currentScope.getEmulationPath(syntheticArguments[i].actualOuterLocalVariable); + if (emulationPath == null) { + // could not emulate a path to a given outer local variable (internal error) + currentScope.problemReporter().needImplementation(); + } else { + this.generateOuterAccess(emulationPath, invocationSite, currentScope); + } + } + } + } + /** + * @param parameters org.eclipse.jdt.internal.compiler.lookup.TypeBinding[] + * @param constructorBinding org.eclipse.jdt.internal.compiler.lookup.MethodBinding + */ + public void generateSyntheticBodyForConstructorAccess(SyntheticAccessMethodBinding accessBinding) { - initializeMaxLocals(accessBinding); + initializeMaxLocals(accessBinding); - MethodBinding constructorBinding = accessBinding.targetMethod; - TypeBinding[] parameters = constructorBinding.parameters; - int length = parameters.length; - int resolvedPosition = 1; - this.aload_0(); - if (constructorBinding.declaringClass.isNestedType()) { - NestedTypeBinding nestedType = (NestedTypeBinding) constructorBinding.declaringClass; - SyntheticArgumentBinding[] syntheticArguments = nestedType.syntheticEnclosingInstances(); - for (int i = 0; i < (syntheticArguments == null ? 0 : syntheticArguments.length); i++) { - TypeBinding type; - load((type = syntheticArguments[i].type), resolvedPosition); - if ((type == DoubleBinding) || (type == LongBinding)) - resolvedPosition += 2; - else - resolvedPosition++; - } - syntheticArguments = nestedType.syntheticOuterLocalVariables(); - for (int i = 0; i < (syntheticArguments == null ? 0 : syntheticArguments.length); i++) { - TypeBinding type; - load((type = syntheticArguments[i].type), resolvedPosition); - if ((type == DoubleBinding) || (type == LongBinding)) - resolvedPosition += 2; - else - resolvedPosition++; - } - } - for (int i = 0; i < length; i++) { - load(parameters[i], resolvedPosition); - if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding)) - resolvedPosition += 2; - else - resolvedPosition++; - } - this.invokespecial(constructorBinding); - this.return_(); -} -public void generateSyntheticBodyForFieldReadAccess(SyntheticAccessMethodBinding accessBinding) { - initializeMaxLocals(accessBinding); - FieldBinding fieldBinding = accessBinding.targetReadField; - TypeBinding type; - if (fieldBinding.isStatic()) - this.getstatic(fieldBinding); - else { - this.aload_0(); - this.getfield(fieldBinding); - } - if ((type = fieldBinding.type).isBaseType()) { - if (type == IntBinding) - this.ireturn(); - else - if (type == FloatBinding) - this.freturn(); - else - if (type == LongBinding) - this.lreturn(); - else - if (type == DoubleBinding) - this.dreturn(); - else - this.ireturn(); - } else - this.areturn(); -} -public void generateSyntheticBodyForFieldWriteAccess(SyntheticAccessMethodBinding accessBinding) { - initializeMaxLocals(accessBinding); - FieldBinding fieldBinding = accessBinding.targetWriteField; - if (fieldBinding.isStatic()) { - load(fieldBinding.type, 0); - this.putstatic(fieldBinding); - } else { - this.aload_0(); - load(fieldBinding.type, 1); - this.putfield(fieldBinding); - } - this.return_(); -} -public void generateSyntheticBodyForMethodAccess(SyntheticAccessMethodBinding accessBinding) { + MethodBinding constructorBinding = accessBinding.targetMethod; + TypeBinding[] parameters = constructorBinding.parameters; + int length = parameters.length; + int resolvedPosition = 1; + this.aload_0(); + if (constructorBinding.declaringClass.isNestedType()) { + NestedTypeBinding nestedType = (NestedTypeBinding) constructorBinding.declaringClass; + SyntheticArgumentBinding[] syntheticArguments = nestedType.syntheticEnclosingInstances(); + for (int i = 0; i < (syntheticArguments == null ? 0 : syntheticArguments.length); i++) { + TypeBinding type; + load((type = syntheticArguments[i].type), resolvedPosition); + if ((type == DoubleBinding) || (type == LongBinding)) + resolvedPosition += 2; + else + resolvedPosition++; + } + syntheticArguments = nestedType.syntheticOuterLocalVariables(); + for (int i = 0; i < (syntheticArguments == null ? 0 : syntheticArguments.length); i++) { + TypeBinding type; + load((type = syntheticArguments[i].type), resolvedPosition); + if ((type == DoubleBinding) || (type == LongBinding)) + resolvedPosition += 2; + else + resolvedPosition++; + } + } + for (int i = 0; i < length; i++) { + load(parameters[i], resolvedPosition); + if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding)) + resolvedPosition += 2; + else + resolvedPosition++; + } + this.invokespecial(constructorBinding); + this.return_(); + } + public void generateSyntheticBodyForFieldReadAccess(SyntheticAccessMethodBinding accessBinding) { + initializeMaxLocals(accessBinding); + FieldBinding fieldBinding = accessBinding.targetReadField; + TypeBinding type; + if (fieldBinding.isStatic()) + this.getstatic(fieldBinding); + else { + this.aload_0(); + this.getfield(fieldBinding); + } + if ((type = fieldBinding.type).isBaseType()) { + if (type == IntBinding) + this.ireturn(); + else if (type == FloatBinding) + this.freturn(); + else if (type == LongBinding) + this.lreturn(); + else if (type == DoubleBinding) + this.dreturn(); + else + this.ireturn(); + } else + this.areturn(); + } + public void generateSyntheticBodyForFieldWriteAccess(SyntheticAccessMethodBinding accessBinding) { + initializeMaxLocals(accessBinding); + FieldBinding fieldBinding = accessBinding.targetWriteField; + if (fieldBinding.isStatic()) { + load(fieldBinding.type, 0); + this.putstatic(fieldBinding); + } else { + this.aload_0(); + load(fieldBinding.type, 1); + this.putfield(fieldBinding); + } + this.return_(); + } + public void generateSyntheticBodyForMethodAccess(SyntheticAccessMethodBinding accessBinding) { - initializeMaxLocals(accessBinding); - MethodBinding methodBinding = accessBinding.targetMethod; - TypeBinding[] parameters = methodBinding.parameters; - int length = parameters.length; - int resolvedPosition; - if (methodBinding.isStatic()) - resolvedPosition = 0; - else { - this.aload_0(); - resolvedPosition = 1; - } - for (int i = 0; i < length; i++) { - load(parameters[i], resolvedPosition); - if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding)) - resolvedPosition += 2; - else - resolvedPosition++; - } - TypeBinding type; - if (methodBinding.isStatic()) - this.invokestatic(methodBinding); - else { - if (methodBinding.isConstructor() - || methodBinding.isPrivate() - // qualified super "X.super.foo()" targets methods from superclass - || (methodBinding.declaringClass != methodDeclaration.binding.declaringClass)){ - this.invokespecial(methodBinding); - } else { - if (methodBinding.declaringClass.isInterface()){ - this.invokeinterface(methodBinding); - } else { - this.invokevirtual(methodBinding); - } - } - } - if ((type = methodBinding.returnType).isBaseType()) - if (type == VoidBinding) - this.return_(); - else - if (type == IntBinding) - this.ireturn(); - else - if (type == FloatBinding) - this.freturn(); - else - if (type == LongBinding) - this.lreturn(); - else - if (type == DoubleBinding) - this.dreturn(); - else - this.ireturn(); - else - this.areturn(); -} -final public byte[] getContents() { - byte[] contents; - System.arraycopy(bCodeStream, 0, contents = new byte[position], 0, position); - return contents; -} -final public void getfield(FieldBinding fieldBinding) { - countLabels = 0; - if ((fieldBinding.type.id == T_double) || (fieldBinding.type.id == T_long)) { - if (++stackDepth > stackMax) - stackMax = stackDepth; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_getfield; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_getfield); - } - writeUnsignedShort(constantPool.literalIndex(fieldBinding)); -} -final public void getstatic(FieldBinding fieldBinding) { - countLabels = 0; - if ((fieldBinding.type.id == T_double) || (fieldBinding.type.id == T_long)) - stackDepth += 2; - else - stackDepth += 1; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_getstatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_getstatic); - } - writeUnsignedShort(constantPool.literalIndex(fieldBinding)); -} -public void getSystemOut() { - countLabels = 0; - if (++stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_getstatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_getstatic); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangSystemOut()); -} -public void getTYPE(int baseTypeID) { - countLabels = 0; - if (++stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_getstatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_getstatic); - } - switch (baseTypeID) { - // getstatic: java.lang.Byte.TYPE - case T_byte : - writeUnsignedShort(constantPool.literalIndexForJavaLangByteTYPE()); - break; - // getstatic: java.lang.Short.TYPE - case T_short : - writeUnsignedShort(constantPool.literalIndexForJavaLangShortTYPE()); - break; - // getstatic: java.lang.Character.TYPE - case T_char : - writeUnsignedShort(constantPool.literalIndexForJavaLangCharacterTYPE()); - break; - // getstatic: java.lang.Integer.TYPE - case T_int : - writeUnsignedShort(constantPool.literalIndexForJavaLangIntegerTYPE()); - break; - // getstatic: java.lang.Long.TYPE - case T_long : - writeUnsignedShort(constantPool.literalIndexForJavaLangLongTYPE()); - break; - // getstatic: java.lang.Float.TYPE - case T_float : - writeUnsignedShort(constantPool.literalIndexForJavaLangFloatTYPE()); - break; - // getstatic: java.lang.Double.TYPE - case T_double : - writeUnsignedShort(constantPool.literalIndexForJavaLangDoubleTYPE()); - break; - // getstatic: java.lang.Boolean.TYPE - case T_boolean : - writeUnsignedShort(constantPool.literalIndexForJavaLangBooleanTYPE()); - break; - // getstatic: java.lang.Void.TYPE - case T_void : - writeUnsignedShort(constantPool.literalIndexForJavaLangVoidTYPE()); - break; - } -} -/** - * We didn't call it goto, because there is a conflit with the goto keyword - */ -final public void goto_(Label lbl) { - if (this.wideMode) { - this.goto_w(lbl); - return; - } - try { - lbl.inlineForwardReferencesFromLabelsTargeting(position); - /* - Possible optimization for code such as: - public Object foo() { - boolean b = true; - if (b) { - if (b) - return null; - } else { - if (b) { - return null; - } - } - return null; - } - The goto around the else block for the first if will - be unreachable, because the thenClause of the second if - returns. - See inlineForwardReferencesFromLabelsTargeting defined - on the Label class for the remaining part of this - optimization. - if (!lbl.isBranchTarget(position)) { - switch(bCodeStream[classFileOffset-1]) { - case OPC_return : - case OPC_areturn: - return; - } - }*/ - position++; - bCodeStream[classFileOffset++] = OPC_goto; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_goto); - } - lbl.branch(); -} + initializeMaxLocals(accessBinding); + MethodBinding methodBinding = accessBinding.targetMethod; + TypeBinding[] parameters = methodBinding.parameters; + int length = parameters.length; + int resolvedPosition; + if (methodBinding.isStatic()) + resolvedPosition = 0; + else { + this.aload_0(); + resolvedPosition = 1; + } + for (int i = 0; i < length; i++) { + load(parameters[i], resolvedPosition); + if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding)) + resolvedPosition += 2; + else + resolvedPosition++; + } + TypeBinding type; + if (methodBinding.isStatic()) + this.invokestatic(methodBinding); + else { + if (methodBinding.isConstructor() + || methodBinding.isPrivate() // qualified super "X.super.foo()" targets methods from superclass + || (methodBinding.declaringClass != methodDeclaration.binding.declaringClass)) { + this.invokespecial(methodBinding); + } else { + if (methodBinding.declaringClass.isInterface()) { + this.invokeinterface(methodBinding); + } else { + this.invokevirtual(methodBinding); + } + } + } + if ((type = methodBinding.returnType).isBaseType()) + if (type == VoidBinding) + this.return_(); + else if (type == IntBinding) + this.ireturn(); + else if (type == FloatBinding) + this.freturn(); + else if (type == LongBinding) + this.lreturn(); + else if (type == DoubleBinding) + this.dreturn(); + else + this.ireturn(); + else + this.areturn(); + } + final public byte[] getContents() { + byte[] contents; + System.arraycopy(bCodeStream, 0, contents = new byte[position], 0, position); + return contents; + } + final public void getfield(FieldBinding fieldBinding) { + countLabels = 0; + if ((fieldBinding.type.id == T_double) || (fieldBinding.type.id == T_long)) { + if (++stackDepth > stackMax) + stackMax = stackDepth; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_getfield; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_getfield); + } + writeUnsignedShort(constantPool.literalIndex(fieldBinding)); + } + final public void getstatic(FieldBinding fieldBinding) { + countLabels = 0; + if ((fieldBinding.type.id == T_double) || (fieldBinding.type.id == T_long)) + stackDepth += 2; + else + stackDepth += 1; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_getstatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_getstatic); + } + writeUnsignedShort(constantPool.literalIndex(fieldBinding)); + } + public void getSystemOut() { + countLabels = 0; + if (++stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_getstatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_getstatic); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangSystemOut()); + } + public void getTYPE(int baseTypeID) { + countLabels = 0; + if (++stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_getstatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_getstatic); + } + switch (baseTypeID) { + // getstatic: java.lang.Byte.TYPE + case T_byte : + writeUnsignedShort(constantPool.literalIndexForJavaLangByteTYPE()); + break; + // getstatic: java.lang.Short.TYPE + case T_short : + writeUnsignedShort(constantPool.literalIndexForJavaLangShortTYPE()); + break; + // getstatic: java.lang.Character.TYPE + case T_char : + writeUnsignedShort(constantPool.literalIndexForJavaLangCharacterTYPE()); + break; + // getstatic: java.lang.Integer.TYPE + case T_int : + writeUnsignedShort(constantPool.literalIndexForJavaLangIntegerTYPE()); + break; + // getstatic: java.lang.Long.TYPE + case T_long : + writeUnsignedShort(constantPool.literalIndexForJavaLangLongTYPE()); + break; + // getstatic: java.lang.Float.TYPE + case T_float : + writeUnsignedShort(constantPool.literalIndexForJavaLangFloatTYPE()); + break; + // getstatic: java.lang.Double.TYPE + case T_double : + writeUnsignedShort(constantPool.literalIndexForJavaLangDoubleTYPE()); + break; + // getstatic: java.lang.Boolean.TYPE + case T_boolean : + writeUnsignedShort(constantPool.literalIndexForJavaLangBooleanTYPE()); + break; + // getstatic: java.lang.Void.TYPE + case T_void : + writeUnsignedShort(constantPool.literalIndexForJavaLangVoidTYPE()); + break; + } + } + /** + * We didn't call it goto, because there is a conflit with the goto keyword + */ + final public void goto_(Label lbl) { + if (this.wideMode) { + this.goto_w(lbl); + return; + } + try { + lbl.inlineForwardReferencesFromLabelsTargeting(position); + /* + Possible optimization for code such as: + public Object foo() { + boolean b = true; + if (b) { + if (b) + return null; + } else { + if (b) { + return null; + } + } + return null; + } + The goto around the else block for the first if will + be unreachable, because the thenClause of the second if + returns. + See inlineForwardReferencesFromLabelsTargeting defined + on the Label class for the remaining part of this + optimization. + if (!lbl.isBranchTarget(position)) { + switch(bCodeStream[classFileOffset-1]) { + case OPC_return : + case OPC_areturn: + return; + } + }*/ + position++; + bCodeStream[classFileOffset++] = OPC_goto; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_goto); + } + lbl.branch(); + } -/** - * We didn't call it goto, because there is a conflit with the goto keyword - */ -final public void internal_goto_(Label lbl) { - try { - lbl.inlineForwardReferencesFromLabelsTargeting(position); - /* - Possible optimization for code such as: - public Object foo() { - boolean b = true; - if (b) { - if (b) - return null; - } else { - if (b) { - return null; - } - } - return null; - } - The goto around the else block for the first if will - be unreachable, because the thenClause of the second if - returns. - See inlineForwardReferencesFromLabelsTargeting defined - on the Label class for the remaining part of this - optimization. - if (!lbl.isBranchTarget(position)) { - switch(bCodeStream[classFileOffset-1]) { - case OPC_return : - case OPC_areturn: - return; - } - }*/ - position++; - bCodeStream[classFileOffset++] = OPC_goto; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_goto); - } - lbl.branch(); -} -final public void goto_w(Label lbl) { - try { - position++; - bCodeStream[classFileOffset++] = OPC_goto_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_goto_w); - } - lbl.branchWide(); -} -final public void i2b() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_i2b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_i2b); - } -} -final public void i2c() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_i2c; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_i2c); - } -} -final public void i2d() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_i2d; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_i2d); - } -} -final public void i2f() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_i2f; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_i2f); - } -} -final public void i2l() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_i2l; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_i2l); - } -} -final public void i2s() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_i2s; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_i2s); - } -} -final public void iadd() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iadd; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iadd); - } -} -final public void iaload() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iaload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iaload); - } -} -final public void iand() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iand; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iand); - } -} -final public void iastore() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iastore); - } -} -final public void iconst_0() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_0); - } -} -final public void iconst_1() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_1); - } -} -final public void iconst_2() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_2); - } -} -final public void iconst_3() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_3); - } -} -final public void iconst_4() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_4; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_4); - } -} -final public void iconst_5() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_5; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_5); - } -} -final public void iconst_m1() { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iconst_m1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iconst_m1); - } -} -final public void idiv() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_idiv; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_idiv); - } -} -final public void if_acmpeq(Label lbl) { - countLabels = 0; - stackDepth-=2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_acmpeq, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_acmpeq; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_acmpeq); - } - lbl.branch(); - } -} -final public void if_acmpne(Label lbl) { - countLabels = 0; - stackDepth-=2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_acmpne, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_acmpne; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_acmpne); - } - lbl.branch(); - } -} -final public void if_icmpeq(Label lbl) { - countLabels = 0; - stackDepth -= 2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_icmpeq, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_icmpeq; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_icmpeq); - } - lbl.branch(); - } -} -final public void if_icmpge(Label lbl) { - countLabels = 0; - stackDepth -= 2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_icmpge, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_icmpge; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_icmpge); - } - lbl.branch(); - } -} -final public void if_icmpgt(Label lbl) { - countLabels = 0; - stackDepth -= 2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_icmpgt, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_icmpgt; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_icmpgt); - } - lbl.branch(); - } -} -final public void if_icmple(Label lbl) { - countLabels = 0; - stackDepth -= 2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_icmple, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_icmple; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_icmple); - } - lbl.branch(); - } -} -final public void if_icmplt(Label lbl) { - countLabels = 0; - stackDepth -= 2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_icmplt, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_icmplt; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_icmplt); - } - lbl.branch(); - } -} -final public void if_icmpne(Label lbl) { - countLabels = 0; - stackDepth -= 2; - if (this.wideMode) { - generateWideConditionalBranch(OPC_if_icmpne, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_if_icmpne; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_if_icmpne); - } - lbl.branch(); - } -} -final public void ifeq(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifeq, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifeq; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifeq); - } - lbl.branch(); - } -} -final public void ifge(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifge, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifge; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifge); - } - lbl.branch(); - } -} -final public void ifgt(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifgt, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifgt; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifgt); - } - lbl.branch(); - } -} -final public void ifle(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifle, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifle; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifle); - } - lbl.branch(); - } -} -final public void iflt(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_iflt, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_iflt; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iflt); - } - lbl.branch(); - } -} -final public void ifne(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifne, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifne; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifne); - } - lbl.branch(); - } -} -final public void ifnonnull(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifnonnull, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifnonnull; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifnonnull); - } - lbl.branch(); - } -} -final public void ifnull(Label lbl) { - countLabels = 0; - stackDepth--; - if (this.wideMode) { - generateWideConditionalBranch(OPC_ifnull, lbl); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_ifnull; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ifnull); - } - lbl.branch(); - } -} -final public void iinc(int index, int value) { - countLabels = 0; - if ((index > 255) || (value < -128 || value > 127)) { // have to widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_iinc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iinc); - } - writeUnsignedShort(index); - writeSignedShort(value); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_iinc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iinc); - } - writeUnsignedByte(index); - writeSignedByte(value); - } -} -final public void iload(int iArg) { - countLabels = 0; - stackDepth++; - if (maxLocals <= iArg) { - maxLocals = iArg + 1; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_iload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iload); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_iload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iload); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void iload_0() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 0) { - maxLocals = 1; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iload_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iload_0); - } -} -final public void iload_1() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 1) { - maxLocals = 2; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iload_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iload_1); - } -} -final public void iload_2() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 2) { - maxLocals = 3; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iload_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iload_2); - } -} -final public void iload_3() { - countLabels = 0; - stackDepth++; - if (maxLocals <= 3) { - maxLocals = 4; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iload_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iload_3); - } -} -final public void imul() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_imul; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_imul); - } -} -public void incrementTemp(LocalVariableBinding localBinding, int value) { - if (value == (short) value) { - this.iinc(localBinding.resolvedPosition, value); - return; - } - load(localBinding); - this.ldc(value); - this.iadd(); - store(localBinding, false); -} -public void incrStackSize(int offset) { - if ((stackDepth += offset) > stackMax) - stackMax = stackDepth; -} -public int indexOfSameLineEntrySincePC(int pc, int line) { - for (int index = pc, max = pcToSourceMapSize; index < max; index+=2) { - if (pcToSourceMap[index+1] == line) - return index; - } - return -1; -} -final public void ineg() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ineg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ineg); - } -} -public void init(ClassFile classFile) { - this.classFile = classFile; - this.constantPool = classFile.constantPool; - this.bCodeStream = classFile.contents; - this.classFileOffset = classFile.contentsOffset; - this.startingClassFileOffset = this.classFileOffset; - pcToSourceMapSize = 0; - lastEntryPC = 0; - int length = visibleLocals.length; - if (noVisibleLocals.length < length) { - noVisibleLocals = new LocalVariableBinding[length]; - } - System.arraycopy(noVisibleLocals, 0, visibleLocals, 0, length); - visibleLocalsCount = 0; - - length = locals.length; - if (noLocals.length < length) { - noLocals = new LocalVariableBinding[length]; - } - System.arraycopy(noLocals, 0, locals, 0, length); - allLocalsCounter = 0; + /** + * We didn't call it goto, because there is a conflit with the goto keyword + */ + final public void internal_goto_(Label lbl) { + try { + lbl.inlineForwardReferencesFromLabelsTargeting(position); + /* + Possible optimization for code such as: + public Object foo() { + boolean b = true; + if (b) { + if (b) + return null; + } else { + if (b) { + return null; + } + } + return null; + } + The goto around the else block for the first if will + be unreachable, because the thenClause of the second if + returns. + See inlineForwardReferencesFromLabelsTargeting defined + on the Label class for the remaining part of this + optimization. + if (!lbl.isBranchTarget(position)) { + switch(bCodeStream[classFileOffset-1]) { + case OPC_return : + case OPC_areturn: + return; + } + }*/ + position++; + bCodeStream[classFileOffset++] = OPC_goto; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_goto); + } + lbl.branch(); + } + final public void goto_w(Label lbl) { + try { + position++; + bCodeStream[classFileOffset++] = OPC_goto_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_goto_w); + } + lbl.branchWide(); + } + final public void i2b() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_i2b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_i2b); + } + } + final public void i2c() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_i2c; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_i2c); + } + } + final public void i2d() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_i2d; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_i2d); + } + } + final public void i2f() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_i2f; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_i2f); + } + } + final public void i2l() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_i2l; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_i2l); + } + } + final public void i2s() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_i2s; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_i2s); + } + } + final public void iadd() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iadd; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iadd); + } + } + final public void iaload() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iaload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iaload); + } + } + final public void iand() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iand; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iand); + } + } + final public void iastore() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iastore); + } + } + final public void iconst_0() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_0); + } + } + final public void iconst_1() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_1); + } + } + final public void iconst_2() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_2); + } + } + final public void iconst_3() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_3); + } + } + final public void iconst_4() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_4; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_4); + } + } + final public void iconst_5() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_5; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_5); + } + } + final public void iconst_m1() { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iconst_m1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iconst_m1); + } + } + final public void idiv() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_idiv; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_idiv); + } + } + final public void if_acmpeq(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_acmpeq, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_acmpeq; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_acmpeq); + } + lbl.branch(); + } + } + final public void if_acmpne(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_acmpne, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_acmpne; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_acmpne); + } + lbl.branch(); + } + } + final public void if_icmpeq(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_icmpeq, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_icmpeq; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_icmpeq); + } + lbl.branch(); + } + } + final public void if_icmpge(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_icmpge, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_icmpge; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_icmpge); + } + lbl.branch(); + } + } + final public void if_icmpgt(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_icmpgt, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_icmpgt; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_icmpgt); + } + lbl.branch(); + } + } + final public void if_icmple(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_icmple, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_icmple; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_icmple); + } + lbl.branch(); + } + } + final public void if_icmplt(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_icmplt, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_icmplt; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_icmplt); + } + lbl.branch(); + } + } + final public void if_icmpne(Label lbl) { + countLabels = 0; + stackDepth -= 2; + if (this.wideMode) { + generateWideConditionalBranch(OPC_if_icmpne, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_if_icmpne; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_if_icmpne); + } + lbl.branch(); + } + } + final public void ifeq(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifeq, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifeq; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifeq); + } + lbl.branch(); + } + } + final public void ifge(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifge, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifge; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifge); + } + lbl.branch(); + } + } + final public void ifgt(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifgt, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifgt; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifgt); + } + lbl.branch(); + } + } + final public void ifle(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifle, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifle; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifle); + } + lbl.branch(); + } + } + final public void iflt(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_iflt, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_iflt; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iflt); + } + lbl.branch(); + } + } + final public void ifne(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifne, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifne; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifne); + } + lbl.branch(); + } + } + final public void ifnonnull(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifnonnull, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifnonnull; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifnonnull); + } + lbl.branch(); + } + } + final public void ifnull(Label lbl) { + countLabels = 0; + stackDepth--; + if (this.wideMode) { + generateWideConditionalBranch(OPC_ifnull, lbl); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_ifnull; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ifnull); + } + lbl.branch(); + } + } + final public void iinc(int index, int value) { + countLabels = 0; + if ((index > 255) || (value < -128 || value > 127)) { // have to widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_iinc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iinc); + } + writeUnsignedShort(index); + writeSignedShort(value); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_iinc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iinc); + } + writeUnsignedByte(index); + writeSignedByte(value); + } + } + final public void iload(int iArg) { + countLabels = 0; + stackDepth++; + if (maxLocals <= iArg) { + maxLocals = iArg + 1; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_iload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iload); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_iload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iload); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void iload_0() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 0) { + maxLocals = 1; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iload_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iload_0); + } + } + final public void iload_1() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 1) { + maxLocals = 2; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iload_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iload_1); + } + } + final public void iload_2() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 2) { + maxLocals = 3; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iload_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iload_2); + } + } + final public void iload_3() { + countLabels = 0; + stackDepth++; + if (maxLocals <= 3) { + maxLocals = 4; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iload_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iload_3); + } + } + final public void imul() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_imul; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_imul); + } + } + public void incrementTemp(LocalVariableBinding localBinding, int value) { + if (value == (short) value) { + this.iinc(localBinding.resolvedPosition, value); + return; + } + load(localBinding); + this.ldc(value); + this.iadd(); + store(localBinding, false); + } + public void incrStackSize(int offset) { + if ((stackDepth += offset) > stackMax) + stackMax = stackDepth; + } + public int indexOfSameLineEntrySincePC(int pc, int line) { + for (int index = pc, max = pcToSourceMapSize; index < max; index += 2) { + if (pcToSourceMap[index + 1] == line) + return index; + } + return -1; + } + final public void ineg() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ineg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ineg); + } + } + public void init(ClassFile classFile) { + this.classFile = classFile; + this.constantPool = classFile.constantPool; + this.bCodeStream = classFile.contents; + this.classFileOffset = classFile.contentsOffset; + this.startingClassFileOffset = this.classFileOffset; + pcToSourceMapSize = 0; + lastEntryPC = 0; + int length = visibleLocals.length; + if (noVisibleLocals.length < length) { + noVisibleLocals = new LocalVariableBinding[length]; + } + System.arraycopy(noVisibleLocals, 0, visibleLocals, 0, length); + visibleLocalsCount = 0; - length = exceptionHandlers.length; - if (noExceptionHandlers.length < length) { - noExceptionHandlers = new ExceptionLabel[length]; - } - System.arraycopy(noExceptionHandlers, 0, exceptionHandlers, 0, length); - exceptionHandlersNumber = 0; - - length = labels.length; - if (noLabels.length < length) { - noLabels = new Label[length]; - } - System.arraycopy(noLabels, 0, labels, 0, length); - countLabels = 0; + length = locals.length; + if (noLocals.length < length) { + noLocals = new LocalVariableBinding[length]; + } + System.arraycopy(noLocals, 0, locals, 0, length); + allLocalsCounter = 0; - stackMax = 0; - stackDepth = 0; - maxLocals = 0; - position = 0; -} -/** - * @param methodDeclaration org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration - * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile - */ -public void initializeMaxLocals(MethodBinding methodBinding) { + length = exceptionHandlers.length; + if (noExceptionHandlers.length < length) { + noExceptionHandlers = new ExceptionLabel[length]; + } + System.arraycopy(noExceptionHandlers, 0, exceptionHandlers, 0, length); + exceptionHandlersNumber = 0; - maxLocals = (methodBinding == null || methodBinding.isStatic()) ? 0 : 1; - // take into account the synthetic parameters - if (methodBinding != null) { - if (methodBinding.isConstructor() && methodBinding.declaringClass.isNestedType()) { - ReferenceBinding enclosingInstanceTypes[]; - if ((enclosingInstanceTypes = methodBinding.declaringClass.syntheticEnclosingInstanceTypes()) != null) { - for (int i = 0, max = enclosingInstanceTypes.length; i < max; i++) { - maxLocals++; // an enclosingInstanceType can only be a reference binding. It cannot be - // LongBinding or DoubleBinding - } - } - SyntheticArgumentBinding syntheticArguments[]; - if ((syntheticArguments = methodBinding.declaringClass.syntheticOuterLocalVariables()) != null) { - for (int i = 0, max = syntheticArguments.length; i < max; i++) { - TypeBinding argType; - if (((argType = syntheticArguments[i].type) == LongBinding) || (argType == DoubleBinding)) { - maxLocals += 2; - } else { - maxLocals++; - } - } - } - } - TypeBinding[] arguments; - if ((arguments = methodBinding.parameters) != null) { - for (int i = 0, max = arguments.length; i < max; i++) { - TypeBinding argType; - if (((argType = arguments[i]) == LongBinding) || (argType == DoubleBinding)) { - maxLocals += 2; - } else { - maxLocals++; - } - } - } - } -} -/** - * This methods searches for an existing entry inside the pcToSourceMap table with a pc equals to @pc. - * If there is an existing entry it returns -1 (no insertion required). - * Otherwise it returns the index where the entry for the pc has to be inserted. - * This is based on the fact that the pcToSourceMap table is sorted according to the pc. - * - * @param int pc - * @return int - */ -public static int insertionIndex(int[] pcToSourceMap, int length, int pc) { - int g = 0; - int d = length - 2; - int m = 0; - while (g <= d) { - m = (g + d) / 2; - // we search only on even indexes - if ((m % 2) != 0) - m--; - int currentPC = pcToSourceMap[m]; - if (pc < currentPC) { - d = m - 2; - } else - if (pc > currentPC) { - g = m + 2; - } else { - return -1; - } - } - if (pc < pcToSourceMap[m]) - return m; - return m + 2; -} -/** - * We didn't call it instanceof because there is a conflit with the - * instanceof keyword - */ -final public void instance_of(TypeBinding typeBinding) { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_instanceof; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_instanceof); - } - writeUnsignedShort(constantPool.literalIndex(typeBinding)); -} -public void invokeClassForName() { - // invokestatic: java.lang.Class.forName(Ljava.lang.String;)Ljava.lang.Class; - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokestatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokestatic); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangClassForName()); -} + length = labels.length; + if (noLabels.length < length) { + noLabels = new Label[length]; + } + System.arraycopy(noLabels, 0, labels, 0, length); + countLabels = 0; -public void invokeJavaLangClassDesiredAssertionStatus() { - // invokevirtual: java.lang.Class.desiredAssertionStatus()Z; - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangClassDesiredAssertionStatus()); -} + stackMax = 0; + stackDepth = 0; + maxLocals = 0; + position = 0; + } + /** + * @param methodDeclaration org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration + * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile + */ + public void initializeMaxLocals(MethodBinding methodBinding) { -public void invokeConstructorGetConstructor() { - // invokevirtual: java.lang.Class.getConstructor(java.lang.Class[])Ljava.lang.reflect.Constructor; - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangClassGetConstructor()); -} -final public void invokeinterface(MethodBinding methodBinding) { - // initialized to 1 to take into account this immediately - countLabels = 0; - int argCount = 1; - int id; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokeinterface; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokeinterface); - } - writeUnsignedShort(constantPool.literalIndex(methodBinding)); - for (int i = methodBinding.parameters.length - 1; i >= 0; i--) - if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) - argCount += 2; - else - argCount += 1; - writeUnsignedByte(argCount); - // Generate a 0 into the byte array. Like the array is already fill with 0, we just need to increment - // the number of bytes. - position++; - classFileOffset++; - if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) - stackDepth += (2 - argCount); - else - if (id == T_void) - stackDepth -= argCount; - else - stackDepth += (1 - argCount); - if (stackDepth > stackMax) - stackMax = stackDepth; -} -public void invokeJavaLangErrorConstructor() { - // invokespecial: java.lang.Error(Ljava.lang.String;)V - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - stackDepth -= 2; - writeUnsignedShort(constantPool.literalIndexForJavaLangErrorConstructor()); -} -public void invokeNoClassDefFoundErrorStringConstructor() { - // invokespecial: java.lang.NoClassDefFoundError.(Ljava.lang.String;)V - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangNoClassDefFoundErrorStringConstructor()); - stackDepth -= 2; -} -public void invokeObjectNewInstance() { - // invokevirtual: java.lang.reflect.Constructor.newInstance(java.lang.Object[])Ljava.lang.Object; - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangReflectConstructorNewInstance()); -} + maxLocals = (methodBinding == null || methodBinding.isStatic()) ? 0 : 1; + // take into account the synthetic parameters + if (methodBinding != null) { + if (methodBinding.isConstructor() && methodBinding.declaringClass.isNestedType()) { + ReferenceBinding enclosingInstanceTypes[]; + if ((enclosingInstanceTypes = methodBinding.declaringClass.syntheticEnclosingInstanceTypes()) != null) { + for (int i = 0, max = enclosingInstanceTypes.length; i < max; i++) { + maxLocals++; // an enclosingInstanceType can only be a reference binding. It cannot be + // LongBinding or DoubleBinding + } + } + SyntheticArgumentBinding syntheticArguments[]; + if ((syntheticArguments = methodBinding.declaringClass.syntheticOuterLocalVariables()) != null) { + for (int i = 0, max = syntheticArguments.length; i < max; i++) { + TypeBinding argType; + if (((argType = syntheticArguments[i].type) == LongBinding) || (argType == DoubleBinding)) { + maxLocals += 2; + } else { + maxLocals++; + } + } + } + } + TypeBinding[] arguments; + if ((arguments = methodBinding.parameters) != null) { + for (int i = 0, max = arguments.length; i < max; i++) { + TypeBinding argType; + if (((argType = arguments[i]) == LongBinding) || (argType == DoubleBinding)) { + maxLocals += 2; + } else { + maxLocals++; + } + } + } + } + } + /** + * This methods searches for an existing entry inside the pcToSourceMap table with a pc equals to @pc. + * If there is an existing entry it returns -1 (no insertion required). + * Otherwise it returns the index where the entry for the pc has to be inserted. + * This is based on the fact that the pcToSourceMap table is sorted according to the pc. + * + * @param int pc + * @return int + */ + public static int insertionIndex(int[] pcToSourceMap, int length, int pc) { + int g = 0; + int d = length - 2; + int m = 0; + while (g <= d) { + m = (g + d) / 2; + // we search only on even indexes + if ((m % 2) != 0) + m--; + int currentPC = pcToSourceMap[m]; + if (pc < currentPC) { + d = m - 2; + } else if (pc > currentPC) { + g = m + 2; + } else { + return -1; + } + } + if (pc < pcToSourceMap[m]) + return m; + return m + 2; + } + /** + * We didn't call it instanceof because there is a conflit with the + * instanceof keyword + */ + final public void instance_of(TypeBinding typeBinding) { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_instanceof; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_instanceof); + } + writeUnsignedShort(constantPool.literalIndex(typeBinding)); + } + public void invokeClassForName() { + // invokestatic: java.lang.Class.forName(Ljava.lang.String;)Ljava.lang.Class; + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokestatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokestatic); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangClassForName()); + } -public void invokeObjectGetClass() { - // invokevirtual: java.lang.Object.getClass()Ljava.lang.Class; - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangObjectGetClass()); -} + public void invokeJavaLangClassDesiredAssertionStatus() { + // invokevirtual: java.lang.Class.desiredAssertionStatus()Z; + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangClassDesiredAssertionStatus()); + } -final public void invokespecial(MethodBinding methodBinding) { - // initialized to 1 to take into account this immediately - countLabels = 0; - int argCount = 1; - int id; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - writeUnsignedShort(constantPool.literalIndex(methodBinding)); - if (methodBinding.isConstructor() && methodBinding.declaringClass.isNestedType()) { - // enclosing instances - TypeBinding[] syntheticArgumentTypes = methodBinding.declaringClass.syntheticEnclosingInstanceTypes(); - if (syntheticArgumentTypes != null) { - for (int i = 0, max = syntheticArgumentTypes.length; i < max; i++) { - if (((id = syntheticArgumentTypes[i].id) == T_double) || (id == T_long)) { - argCount += 2; - } else { - argCount++; - } - } - } - // outer local variables - SyntheticArgumentBinding[] syntheticArguments = methodBinding.declaringClass.syntheticOuterLocalVariables(); - if (syntheticArguments != null) { - for (int i = 0, max = syntheticArguments.length; i < max; i++) { - if (((id = syntheticArguments[i].type.id) == T_double) || (id == T_long)) { - argCount += 2; - } else { - argCount++; - } - } - } - } - for (int i = methodBinding.parameters.length - 1; i >= 0; i--) - if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) - argCount += 2; - else - argCount++; - if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) - stackDepth += (2 - argCount); - else - if (id == T_void) - stackDepth -= argCount; - else - stackDepth += (1 - argCount); - if (stackDepth > stackMax) - stackMax = stackDepth; -} -final public void invokestatic(MethodBinding methodBinding) { - // initialized to 0 to take into account that there is no this for - // a static method - countLabels = 0; - int argCount = 0; - int id; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokestatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokestatic); - } - writeUnsignedShort(constantPool.literalIndex(methodBinding)); - for (int i = methodBinding.parameters.length - 1; i >= 0; i--) - if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) - argCount += 2; - else - argCount += 1; - if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) - stackDepth += (2 - argCount); - else - if (id == T_void) - stackDepth -= argCount; - else - stackDepth += (1 - argCount); - if (stackDepth > stackMax) - stackMax = stackDepth; -} -/** - * The equivalent code performs a string conversion of the TOS - * @param typeID int - */ -public void invokeStringBufferAppendForType(int typeID) { - countLabels = 0; - int usedTypeID; - if (typeID == T_null) - usedTypeID = T_String; - else - usedTypeID = typeID; - // invokevirtual - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferAppend(typeID)); - if ((usedTypeID == T_long) || (usedTypeID == T_double)) - stackDepth -= 2; - else - stackDepth--; -} + public void invokeConstructorGetConstructor() { + // invokevirtual: java.lang.Class.getConstructor(java.lang.Class[])Ljava.lang.reflect.Constructor; + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangClassGetConstructor()); + } + final public void invokeinterface(MethodBinding methodBinding) { + // initialized to 1 to take into account this immediately + countLabels = 0; + int argCount = 1; + int id; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokeinterface; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokeinterface); + } + writeUnsignedShort(constantPool.literalIndex(methodBinding)); + for (int i = methodBinding.parameters.length - 1; i >= 0; i--) + if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) + argCount += 2; + else + argCount += 1; + writeUnsignedByte(argCount); + // Generate a 0 into the byte array. Like the array is already fill with 0, we just need to increment + // the number of bytes. + position++; + classFileOffset++; + if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) + stackDepth += (2 - argCount); + else if (id == T_void) + stackDepth -= argCount; + else + stackDepth += (1 - argCount); + if (stackDepth > stackMax) + stackMax = stackDepth; + } + public void invokeJavaLangErrorConstructor() { + // invokespecial: java.lang.Error(Ljava.lang.String;)V + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + stackDepth -= 2; + writeUnsignedShort(constantPool.literalIndexForJavaLangErrorConstructor()); + } + public void invokeNoClassDefFoundErrorStringConstructor() { + // invokespecial: java.lang.NoClassDefFoundError.(Ljava.lang.String;)V + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangNoClassDefFoundErrorStringConstructor()); + stackDepth -= 2; + } + public void invokeObjectNewInstance() { + // invokevirtual: java.lang.reflect.Constructor.newInstance(java.lang.Object[])Ljava.lang.Object; + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangReflectConstructorNewInstance()); + } -public void invokeJavaLangAssertionErrorConstructor(int typeBindingID) { - // invokespecial: java.lang.AssertionError.(typeBindingID)V - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionErrorConstructor(typeBindingID)); - stackDepth -= 2; -} + public void invokeObjectGetClass() { + // invokevirtual: java.lang.Object.getClass()Ljava.lang.Class; + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangObjectGetClass()); + } -public void invokeJavaLangAssertionErrorDefaultConstructor() { - // invokespecial: java.lang.AssertionError.()V - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionErrorDefaultConstructor()); - stackDepth --; -} + final public void invokespecial(MethodBinding methodBinding) { + // initialized to 1 to take into account this immediately + countLabels = 0; + int argCount = 1; + int id; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + writeUnsignedShort(constantPool.literalIndex(methodBinding)); + if (methodBinding.isConstructor() && methodBinding.declaringClass.isNestedType()) { + // enclosing instances + TypeBinding[] syntheticArgumentTypes = methodBinding.declaringClass.syntheticEnclosingInstanceTypes(); + if (syntheticArgumentTypes != null) { + for (int i = 0, max = syntheticArgumentTypes.length; i < max; i++) { + if (((id = syntheticArgumentTypes[i].id) == T_double) || (id == T_long)) { + argCount += 2; + } else { + argCount++; + } + } + } + // outer local variables + SyntheticArgumentBinding[] syntheticArguments = methodBinding.declaringClass.syntheticOuterLocalVariables(); + if (syntheticArguments != null) { + for (int i = 0, max = syntheticArguments.length; i < max; i++) { + if (((id = syntheticArguments[i].type.id) == T_double) || (id == T_long)) { + argCount += 2; + } else { + argCount++; + } + } + } + } + for (int i = methodBinding.parameters.length - 1; i >= 0; i--) + if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) + argCount += 2; + else + argCount++; + if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) + stackDepth += (2 - argCount); + else if (id == T_void) + stackDepth -= argCount; + else + stackDepth += (1 - argCount); + if (stackDepth > stackMax) + stackMax = stackDepth; + } + final public void invokestatic(MethodBinding methodBinding) { + // initialized to 0 to take into account that there is no this for + // a static method + countLabels = 0; + int argCount = 0; + int id; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokestatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokestatic); + } + writeUnsignedShort(constantPool.literalIndex(methodBinding)); + for (int i = methodBinding.parameters.length - 1; i >= 0; i--) + if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) + argCount += 2; + else + argCount += 1; + if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) + stackDepth += (2 - argCount); + else if (id == T_void) + stackDepth -= argCount; + else + stackDepth += (1 - argCount); + if (stackDepth > stackMax) + stackMax = stackDepth; + } + /** + * The equivalent code performs a string conversion of the TOS + * @param typeID int + */ + public void invokeStringBufferAppendForType(int typeID) { + countLabels = 0; + int usedTypeID; + if (typeID == T_null) + usedTypeID = T_String; + else + usedTypeID = typeID; + // invokevirtual + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferAppend(typeID)); + if ((usedTypeID == T_long) || (usedTypeID == T_double)) + stackDepth -= 2; + else + stackDepth--; + } -public void invokeStringBufferDefaultConstructor() { - // invokespecial: java.lang.StringBuffer.()V - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferDefaultConstructor()); - stackDepth--; -} -public void invokeStringBufferStringConstructor() { - // invokespecial: java.lang.StringBuffer.(Ljava.lang.String;)V - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokespecial; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokespecial); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferConstructor()); - stackDepth -= 2; -} + public void invokeJavaLangAssertionErrorConstructor(int typeBindingID) { + // invokespecial: java.lang.AssertionError.(typeBindingID)V + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionErrorConstructor(typeBindingID)); + stackDepth -= 2; + } -public void invokeStringBufferToString() { - // invokevirtual: StringBuffer.toString()Ljava.lang.String; - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferToString()); -} -public void invokeStringIntern() { - // invokevirtual: java.lang.String.intern() - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringIntern()); -} -public void invokeStringValueOf(int typeID) { - // invokestatic: java.lang.String.valueOf(argumentType) - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokestatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokestatic); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringValueOf(typeID)); -} -public void invokeSystemExit() { - // invokestatic: java.lang.System.exit(I) - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokestatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokestatic); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangSystemExitInt()); - stackDepth--; // int argument -} -public void invokeThrowableGetMessage() { - // invokevirtual: java.lang.Throwable.getMessage()Ljava.lang.String; - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangThrowableGetMessage()); -} -final public void invokevirtual(MethodBinding methodBinding) { - // initialized to 1 to take into account this immediately - countLabels = 0; - int argCount = 1; - int id; - try { - position++; - bCodeStream[classFileOffset++] = OPC_invokevirtual; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_invokevirtual); - } - writeUnsignedShort(constantPool.literalIndex(methodBinding)); - for (int i = methodBinding.parameters.length - 1; i >= 0; i--) - if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) - argCount += 2; - else - argCount++; - if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) - stackDepth += (2 - argCount); - else - if (id == T_void) - stackDepth -= argCount; - else - stackDepth += (1 - argCount); - if (stackDepth > stackMax) - stackMax = stackDepth; -} -final public void ior() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ior; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ior); - } -} -final public void irem() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_irem; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_irem); - } -} -final public void ireturn() { - countLabels = 0; - stackDepth--; - // the stackDepth should be equal to 0 - try { - position++; - bCodeStream[classFileOffset++] = OPC_ireturn; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ireturn); - } -} -public boolean isDefinitelyAssigned(Scope scope, int initStateIndex, LocalVariableBinding local) { - // Dependant of UnconditionalFlowInfo.isDefinitelyAssigned(..) - if (initStateIndex == -1) - return false; - if (local.isArgument) { - return true; - } - int position = local.id + maxFieldCount; - MethodScope methodScope = scope.methodScope(); - // id is zero-based - if (position < UnconditionalFlowInfo.BitCacheSize) { - return (methodScope.definiteInits[initStateIndex] & (1L << position)) != 0; // use bits - } - // use extra vector - long[] extraInits = methodScope.extraDefiniteInits[initStateIndex]; - if (extraInits == null) - return false; // if vector not yet allocated, then not initialized - int vectorIndex; - if ((vectorIndex = (position / UnconditionalFlowInfo.BitCacheSize) - 1) >= extraInits.length) - return false; // if not enough room in vector, then not initialized - return ((extraInits[vectorIndex]) & (1L << (position % UnconditionalFlowInfo.BitCacheSize))) != 0; -} -final public void ishl() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ishl; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ishl); - } -} -final public void ishr() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ishr; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ishr); - } -} -final public void istore(int iArg) { - countLabels = 0; - stackDepth--; - if (maxLocals <= iArg) { - maxLocals = iArg + 1; - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_istore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_istore); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_istore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_istore); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void istore_0() { - countLabels = 0; - stackDepth--; - if (maxLocals == 0) { - maxLocals = 1; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_istore_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_istore_0); - } -} -final public void istore_1() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 1) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_istore_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_istore_1); - } -} -final public void istore_2() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 2) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_istore_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_istore_2); - } -} -final public void istore_3() { - countLabels = 0; - stackDepth--; - if (maxLocals <= 3) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_istore_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_istore_3); - } -} -final public void isub() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_isub; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_isub); - } -} -final public void iushr() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_iushr; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_iushr); - } -} -final public void ixor() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ixor; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ixor); - } -} -final public void jsr(Label lbl) { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_jsr; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_jsr); - } - lbl.branch(); -} -final public void jsr_w(Label lbl) { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_jsr_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_jsr_w); - } - lbl.branchWide(); -} -final public void l2d() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_l2d; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_l2d); - } -} -final public void l2f() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_l2f; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_l2f); - } -} -final public void l2i() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_l2i; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_l2i); - } -} -final public void ladd() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ladd; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ladd); - } -} -final public void laload() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_laload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_laload); - } -} -final public void land() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_land; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_land); - } -} -final public void lastore() { - countLabels = 0; - stackDepth -= 4; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lastore); - } -} -final public void lcmp() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lcmp; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lcmp); - } -} -final public void lconst_0() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lconst_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lconst_0); - } -} -final public void lconst_1() { - countLabels = 0; - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lconst_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lconst_1); - } -} -final public void ldc(float constant) { - countLabels = 0; - int index = constantPool.literalIndex(constant); - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (index > 255) { - // Generate a ldc_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc_w); - } - writeUnsignedShort(index); - } else { - // Generate a ldc - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc); - } - writeUnsignedByte(index); - } -} -final public void ldc(int constant) { - countLabels = 0; - int index = constantPool.literalIndex(constant); - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (index > 255) { - // Generate a ldc_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc_w); - } - writeUnsignedShort(index); - } else { - // Generate a ldc - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc); - } - writeUnsignedByte(index); - } -} -final public void ldc(String constant) { - countLabels = 0; - int currentConstantPoolIndex = constantPool.currentIndex; - int currentConstantPoolOffset = constantPool.currentOffset; - int currentCodeStreamPosition = position; - int index = constantPool.literalIndexForLdc(constant.toCharArray()); - if (index > 0) { - // the string already exists inside the constant pool - // we reuse the same index - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (index > 255) { - // Generate a ldc_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc_w); - } - writeUnsignedShort(index); - } else { - // Generate a ldc - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc); - } - writeUnsignedByte(index); - } - } else { - // the string is too big to be utf8-encoded in one pass. - // we have to split it into different pieces. - // first we clean all side-effects due to the code above - // this case is very rare, so we can afford to lose time to handle it - char[] constantChars = constant.toCharArray(); - position = currentCodeStreamPosition; - constantPool.currentIndex = currentConstantPoolIndex; - constantPool.currentOffset = currentConstantPoolOffset; - constantPool.stringCache.remove(constantChars); - constantPool.UTF8Cache.remove(constantChars); - int i = 0; - int length = 0; - int constantLength = constant.length(); - byte[] utf8encoding = new byte[Math.min(constantLength + 100, 65535)]; - int utf8encodingLength = 0; - while ((length < 65532) && (i < constantLength)) { - char current = constantChars[i]; - // we resize the byte array immediately if necessary - if (length + 3 > (utf8encodingLength = utf8encoding.length)) { - System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[Math.min(utf8encodingLength + 100, 65535)]), 0, length); - } - if ((current >= 0x0001) && (current <= 0x007F)) { - // we only need one byte: ASCII table - utf8encoding[length++] = (byte) current; - } else { - if (current > 0x07FF) { - // we need 3 bytes - utf8encoding[length++] = (byte) (0xE0 | ((current >> 12) & 0x0F)); // 0xE0 = 1110 0000 - utf8encoding[length++] = (byte) (0x80 | ((current >> 6) & 0x3F)); // 0x80 = 1000 0000 - utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 - } else { - // we can be 0 or between 0x0080 and 0x07FF - // In that case we only need 2 bytes - utf8encoding[length++] = (byte) (0xC0 | ((current >> 6) & 0x1F)); // 0xC0 = 1100 0000 - utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 - } - } - i++; - } - // check if all the string is encoded (PR 1PR2DWJ) - // the string is too big to be encoded in one pass - newStringBuffer(); - dup(); - // write the first part - char[] subChars = new char[i]; - System.arraycopy(constantChars, 0, subChars, 0, i); - System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[length]), 0, length); - index = constantPool.literalIndex(subChars, utf8encoding); - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (index > 255) { - // Generate a ldc_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc_w); - } - writeUnsignedShort(index); - } else { - // Generate a ldc - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc); - } - writeUnsignedByte(index); - } - // write the remaining part - invokeStringBufferStringConstructor(); - while (i < constantLength) { - length = 0; - utf8encoding = new byte[Math.min(constantLength - i + 100, 65535)]; - int startIndex = i; - while ((length < 65532) && (i < constantLength)) { - char current = constantChars[i]; - // we resize the byte array immediately if necessary - if (constantLength + 2 > (utf8encodingLength = utf8encoding.length)) { - System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[Math.min(utf8encodingLength + 100, 65535)]), 0, length); - } - if ((current >= 0x0001) && (current <= 0x007F)) { - // we only need one byte: ASCII table - utf8encoding[length++] = (byte) current; - } else { - if (current > 0x07FF) { - // we need 3 bytes - utf8encoding[length++] = (byte) (0xE0 | ((current >> 12) & 0x0F)); // 0xE0 = 1110 0000 - utf8encoding[length++] = (byte) (0x80 | ((current >> 6) & 0x3F)); // 0x80 = 1000 0000 - utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 - } else { - // we can be 0 or between 0x0080 and 0x07FF - // In that case we only need 2 bytes - utf8encoding[length++] = (byte) (0xC0 | ((current >> 6) & 0x1F)); // 0xC0 = 1100 0000 - utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 - } - } - i++; - } - // the next part is done - subChars = new char[i - startIndex]; - System.arraycopy(constantChars, startIndex, subChars, 0, i - startIndex); - System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[length]), 0, length); - index = constantPool.literalIndex(subChars, utf8encoding); - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - if (index > 255) { - // Generate a ldc_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc_w); - } - writeUnsignedShort(index); - } else { - // Generate a ldc - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc); - } - writeUnsignedByte(index); - } - // now on the stack it should be a StringBuffer and a string. - invokeStringBufferAppendForType(T_String); - } - invokeStringBufferToString(); - invokeStringIntern(); - } -} -final public void ldc2_w(double constant) { - countLabels = 0; - int index = constantPool.literalIndex(constant); - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - // Generate a ldc2_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc2_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc2_w); - } - writeUnsignedShort(index); -} -final public void ldc2_w(long constant) { - countLabels = 0; - int index = constantPool.literalIndex(constant); - stackDepth += 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - // Generate a ldc2_w - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldc2_w; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldc2_w); - } - writeUnsignedShort(index); -} -final public void ldiv() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_ldiv; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ldiv); - } -} -final public void lload(int iArg) { - countLabels = 0; - stackDepth += 2; - if (maxLocals <= iArg + 1) { - maxLocals = iArg + 2; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lload); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_lload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lload); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void lload_0() { - countLabels = 0; - stackDepth += 2; - if (maxLocals < 2) { - maxLocals = 2; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lload_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lload_0); - } -} -final public void lload_1() { - countLabels = 0; - stackDepth += 2; - if (maxLocals < 3) { - maxLocals = 3; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lload_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lload_1); - } -} -final public void lload_2() { - countLabels = 0; - stackDepth += 2; - if (maxLocals < 4) { - maxLocals = 4; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lload_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lload_2); - } -} -final public void lload_3() { - countLabels = 0; - stackDepth += 2; - if (maxLocals < 5) { - maxLocals = 5; - } - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lload_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lload_3); - } -} -final public void lmul() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lmul; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lmul); - } -} -final public void lneg() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lneg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lneg); - } -} -public final void load(LocalVariableBinding localBinding) { - countLabels = 0; - TypeBinding typeBinding = localBinding.type; - int resolvedPosition = localBinding.resolvedPosition; - // Using dedicated int bytecode - if (typeBinding == IntBinding) { - switch (resolvedPosition) { - case 0 : - this.iload_0(); - break; - case 1 : - this.iload_1(); - break; - case 2 : - this.iload_2(); - break; - case 3 : - this.iload_3(); - break; - default : - this.iload(resolvedPosition); - } - return; - } - // Using dedicated float bytecode - if (typeBinding == FloatBinding) { - switch (resolvedPosition) { - case 0 : - this.fload_0(); - break; - case 1 : - this.fload_1(); - break; - case 2 : - this.fload_2(); - break; - case 3 : - this.fload_3(); - break; - default : - this.fload(resolvedPosition); - } - return; - } - // Using dedicated long bytecode - if (typeBinding == LongBinding) { - switch (resolvedPosition) { - case 0 : - this.lload_0(); - break; - case 1 : - this.lload_1(); - break; - case 2 : - this.lload_2(); - break; - case 3 : - this.lload_3(); - break; - default : - this.lload(resolvedPosition); - } - return; - } - // Using dedicated double bytecode - if (typeBinding == DoubleBinding) { - switch (resolvedPosition) { - case 0 : - this.dload_0(); - break; - case 1 : - this.dload_1(); - break; - case 2 : - this.dload_2(); - break; - case 3 : - this.dload_3(); - break; - default : - this.dload(resolvedPosition); - } - return; - } - // boolean, byte, char and short are handled as int - if ((typeBinding == ByteBinding) || (typeBinding == CharBinding) || (typeBinding == BooleanBinding) || (typeBinding == ShortBinding)) { - switch (resolvedPosition) { - case 0 : - this.iload_0(); - break; - case 1 : - this.iload_1(); - break; - case 2 : - this.iload_2(); - break; - case 3 : - this.iload_3(); - break; - default : - this.iload(resolvedPosition); - } - return; - } + public void invokeJavaLangAssertionErrorDefaultConstructor() { + // invokespecial: java.lang.AssertionError.()V + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionErrorDefaultConstructor()); + stackDepth--; + } - // Reference object - switch (resolvedPosition) { - case 0 : - this.aload_0(); - break; - case 1 : - this.aload_1(); - break; - case 2 : - this.aload_2(); - break; - case 3 : - this.aload_3(); - break; - default : - this.aload(resolvedPosition); - } -} -public final void load(TypeBinding typeBinding, int resolvedPosition) { - countLabels = 0; - // Using dedicated int bytecode - if (typeBinding == IntBinding) { - switch (resolvedPosition) { - case 0 : - this.iload_0(); - break; - case 1 : - this.iload_1(); - break; - case 2 : - this.iload_2(); - break; - case 3 : - this.iload_3(); - break; - default : - this.iload(resolvedPosition); - } - return; - } - // Using dedicated float bytecode - if (typeBinding == FloatBinding) { - switch (resolvedPosition) { - case 0 : - this.fload_0(); - break; - case 1 : - this.fload_1(); - break; - case 2 : - this.fload_2(); - break; - case 3 : - this.fload_3(); - break; - default : - this.fload(resolvedPosition); - } - return; - } - // Using dedicated long bytecode - if (typeBinding == LongBinding) { - switch (resolvedPosition) { - case 0 : - this.lload_0(); - break; - case 1 : - this.lload_1(); - break; - case 2 : - this.lload_2(); - break; - case 3 : - this.lload_3(); - break; - default : - this.lload(resolvedPosition); - } - return; - } - // Using dedicated double bytecode - if (typeBinding == DoubleBinding) { - switch (resolvedPosition) { - case 0 : - this.dload_0(); - break; - case 1 : - this.dload_1(); - break; - case 2 : - this.dload_2(); - break; - case 3 : - this.dload_3(); - break; - default : - this.dload(resolvedPosition); - } - return; - } - // boolean, byte, char and short are handled as int - if ((typeBinding == ByteBinding) || (typeBinding == CharBinding) || (typeBinding == BooleanBinding) || (typeBinding == ShortBinding)) { - switch (resolvedPosition) { - case 0 : - this.iload_0(); - break; - case 1 : - this.iload_1(); - break; - case 2 : - this.iload_2(); - break; - case 3 : - this.iload_3(); - break; - default : - this.iload(resolvedPosition); - } - return; - } + public void invokeStringBufferDefaultConstructor() { + // invokespecial: java.lang.StringBuffer.()V + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferDefaultConstructor()); + stackDepth--; + } + public void invokeStringBufferStringConstructor() { + // invokespecial: java.lang.StringBuffer.(Ljava.lang.String;)V + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokespecial; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokespecial); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferConstructor()); + stackDepth -= 2; + } - // Reference object - switch (resolvedPosition) { - case 0 : - this.aload_0(); - break; - case 1 : - this.aload_1(); - break; - case 2 : - this.aload_2(); - break; - case 3 : - this.aload_3(); - break; - default : - this.aload(resolvedPosition); - } -} -public final void loadInt(int resolvedPosition) { - // Using dedicated int bytecode - switch (resolvedPosition) { - case 0 : - this.iload_0(); - break; - case 1 : - this.iload_1(); - break; - case 2 : - this.iload_2(); - break; - case 3 : - this.iload_3(); - break; - default : - this.iload(resolvedPosition); - } -} -public final void loadObject(int resolvedPosition) { - switch (resolvedPosition) { - case 0 : - this.aload_0(); - break; - case 1 : - this.aload_1(); - break; - case 2 : - this.aload_2(); - break; - case 3 : - this.aload_3(); - break; - default : - this.aload(resolvedPosition); - } -} -final public void lookupswitch(CaseLabel defaultLabel, int[] keys, int[] sortedIndexes, CaseLabel[] casesLabel) { - countLabels = 0; - stackDepth--; - int length = keys.length; - int pos = position; - defaultLabel.placeInstruction(); - for (int i = 0; i < length; i++) { - casesLabel[i].placeInstruction(); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lookupswitch; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lookupswitch); - } - for (int i = (3 - (pos % 4)); i > 0; i--) { - position++; // Padding - classFileOffset++; - } - defaultLabel.branch(); - writeSignedWord(length); - for (int i = 0; i < length; i++) { - writeSignedWord(keys[sortedIndexes[i]]); - casesLabel[sortedIndexes[i]].branch(); - } -} -final public void lor() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lor; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lor); - } -} -final public void lrem() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lrem; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lrem); - } -} -final public void lreturn() { - countLabels = 0; - stackDepth -= 2; - // the stackDepth should be equal to 0 - try { - position++; - bCodeStream[classFileOffset++] = OPC_lreturn; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lreturn); - } -} -final public void lshl() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lshl; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lshl); - } -} -final public void lshr() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lshr; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lshr); - } -} -final public void lstore(int iArg) { - countLabels = 0; - stackDepth -= 2; - if (maxLocals <= iArg + 1) { - maxLocals = iArg + 2; - } - if (iArg > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lstore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lstore); - } - writeUnsignedShort(iArg); - } else { - try { - position++; - bCodeStream[classFileOffset++] = OPC_lstore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lstore); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) iArg; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) iArg); - } - } -} -final public void lstore_0() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 2) { - maxLocals = 2; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lstore_0; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lstore_0); - } -} -final public void lstore_1() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 3) { - maxLocals = 3; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lstore_1; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lstore_1); - } -} -final public void lstore_2() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 4) { - maxLocals = 4; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lstore_2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lstore_2); - } -} -final public void lstore_3() { - countLabels = 0; - stackDepth -= 2; - if (maxLocals < 5) { - maxLocals = 5; - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_lstore_3; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lstore_3); - } -} -final public void lsub() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lsub; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lsub); - } -} -final public void lushr() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lushr; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lushr); - } -} -final public void lxor() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_lxor; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_lxor); - } -} -final public void monitorenter() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_monitorenter; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_monitorenter); - } -} -final public void monitorexit() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_monitorexit; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_monitorexit); - } -} -final public void multianewarray(TypeBinding typeBinding, int dimensions) { - countLabels = 0; - stackDepth += (1 - dimensions); - try { - position++; - bCodeStream[classFileOffset++] = OPC_multianewarray; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_multianewarray); - } - writeUnsignedShort(constantPool.literalIndex(typeBinding)); - writeUnsignedByte(dimensions); -} -public static void needImplementation() { -} -/** - * We didn't call it new, because there is a conflit with the new keyword - */ -final public void new_(TypeBinding typeBinding) { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_new; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_new); - } - writeUnsignedShort(constantPool.literalIndex(typeBinding)); -} -final public void newarray(int array_Type) { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_newarray; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_newarray); - } - writeUnsignedByte(array_Type); -} -public void newArray(Scope scope, ArrayBinding arrayBinding) { - TypeBinding component = arrayBinding.elementsType(scope); - switch (component.id) { - case T_int : - this.newarray(10); - break; - case T_byte : - this.newarray(8); - break; - case T_boolean : - this.newarray(4); - break; - case T_short : - this.newarray(9); - break; - case T_char : - this.newarray(5); - break; - case T_long : - this.newarray(11); - break; - case T_float : - this.newarray(6); - break; - case T_double : - this.newarray(7); - break; - default : - this.anewarray(component); - } -} -public void newJavaLangError() { - // new: java.lang.Error - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_new; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_new); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangError()); -} + public void invokeStringBufferToString() { + // invokevirtual: StringBuffer.toString()Ljava.lang.String; + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringBufferToString()); + } + public void invokeStringIntern() { + // invokevirtual: java.lang.String.intern() + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringIntern()); + } + public void invokeStringValueOf(int typeID) { + // invokestatic: java.lang.String.valueOf(argumentType) + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokestatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokestatic); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringValueOf(typeID)); + } + public void invokeSystemExit() { + // invokestatic: java.lang.System.exit(I) + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokestatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokestatic); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangSystemExitInt()); + stackDepth--; // int argument + } + public void invokeThrowableGetMessage() { + // invokevirtual: java.lang.Throwable.getMessage()Ljava.lang.String; + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangThrowableGetMessage()); + } + final public void invokevirtual(MethodBinding methodBinding) { + // initialized to 1 to take into account this immediately + countLabels = 0; + int argCount = 1; + int id; + try { + position++; + bCodeStream[classFileOffset++] = OPC_invokevirtual; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_invokevirtual); + } + writeUnsignedShort(constantPool.literalIndex(methodBinding)); + for (int i = methodBinding.parameters.length - 1; i >= 0; i--) + if (((id = methodBinding.parameters[i].id) == T_double) || (id == T_long)) + argCount += 2; + else + argCount++; + if (((id = methodBinding.returnType.id) == T_double) || (id == T_long)) + stackDepth += (2 - argCount); + else if (id == T_void) + stackDepth -= argCount; + else + stackDepth += (1 - argCount); + if (stackDepth > stackMax) + stackMax = stackDepth; + } + final public void ior() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ior; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ior); + } + } + final public void irem() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_irem; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_irem); + } + } + final public void ireturn() { + countLabels = 0; + stackDepth--; + // the stackDepth should be equal to 0 + try { + position++; + bCodeStream[classFileOffset++] = OPC_ireturn; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ireturn); + } + } + public boolean isDefinitelyAssigned(Scope scope, int initStateIndex, LocalVariableBinding local) { + // Dependant of UnconditionalFlowInfo.isDefinitelyAssigned(..) + if (initStateIndex == -1) + return false; + if (local.isArgument) { + return true; + } + int position = local.id + maxFieldCount; + MethodScope methodScope = scope.methodScope(); + // id is zero-based + if (position < UnconditionalFlowInfo.BitCacheSize) { + return (methodScope.definiteInits[initStateIndex] & (1L << position)) != 0; // use bits + } + // use extra vector + long[] extraInits = methodScope.extraDefiniteInits[initStateIndex]; + if (extraInits == null) + return false; // if vector not yet allocated, then not initialized + int vectorIndex; + if ((vectorIndex = (position / UnconditionalFlowInfo.BitCacheSize) - 1) >= extraInits.length) + return false; // if not enough room in vector, then not initialized + return ((extraInits[vectorIndex]) & (1L << (position % UnconditionalFlowInfo.BitCacheSize))) != 0; + } + final public void ishl() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ishl; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ishl); + } + } + final public void ishr() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ishr; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ishr); + } + } + final public void istore(int iArg) { + countLabels = 0; + stackDepth--; + if (maxLocals <= iArg) { + maxLocals = iArg + 1; + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_istore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_istore); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_istore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_istore); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void istore_0() { + countLabels = 0; + stackDepth--; + if (maxLocals == 0) { + maxLocals = 1; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_istore_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_istore_0); + } + } + final public void istore_1() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 1) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_istore_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_istore_1); + } + } + final public void istore_2() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 2) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_istore_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_istore_2); + } + } + final public void istore_3() { + countLabels = 0; + stackDepth--; + if (maxLocals <= 3) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_istore_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_istore_3); + } + } + final public void isub() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_isub; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_isub); + } + } + final public void iushr() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_iushr; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_iushr); + } + } + final public void ixor() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ixor; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ixor); + } + } + final public void jsr(Label lbl) { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_jsr; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_jsr); + } + lbl.branch(); + } + final public void jsr_w(Label lbl) { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_jsr_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_jsr_w); + } + lbl.branchWide(); + } + final public void l2d() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_l2d; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_l2d); + } + } + final public void l2f() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_l2f; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_l2f); + } + } + final public void l2i() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_l2i; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_l2i); + } + } + final public void ladd() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ladd; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ladd); + } + } + final public void laload() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_laload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_laload); + } + } + final public void land() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_land; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_land); + } + } + final public void lastore() { + countLabels = 0; + stackDepth -= 4; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lastore); + } + } + final public void lcmp() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lcmp; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lcmp); + } + } + final public void lconst_0() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lconst_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lconst_0); + } + } + final public void lconst_1() { + countLabels = 0; + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lconst_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lconst_1); + } + } + final public void ldc(float constant) { + countLabels = 0; + int index = constantPool.literalIndex(constant); + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (index > 255) { + // Generate a ldc_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc_w); + } + writeUnsignedShort(index); + } else { + // Generate a ldc + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc); + } + writeUnsignedByte(index); + } + } + final public void ldc(int constant) { + countLabels = 0; + int index = constantPool.literalIndex(constant); + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (index > 255) { + // Generate a ldc_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc_w); + } + writeUnsignedShort(index); + } else { + // Generate a ldc + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc); + } + writeUnsignedByte(index); + } + } + final public void ldc(String constant) { + countLabels = 0; + int currentConstantPoolIndex = constantPool.currentIndex; + int currentConstantPoolOffset = constantPool.currentOffset; + int currentCodeStreamPosition = position; + int index = constantPool.literalIndexForLdc(constant.toCharArray()); + if (index > 0) { + // the string already exists inside the constant pool + // we reuse the same index + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (index > 255) { + // Generate a ldc_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc_w); + } + writeUnsignedShort(index); + } else { + // Generate a ldc + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc); + } + writeUnsignedByte(index); + } + } else { + // the string is too big to be utf8-encoded in one pass. + // we have to split it into different pieces. + // first we clean all side-effects due to the code above + // this case is very rare, so we can afford to lose time to handle it + char[] constantChars = constant.toCharArray(); + position = currentCodeStreamPosition; + constantPool.currentIndex = currentConstantPoolIndex; + constantPool.currentOffset = currentConstantPoolOffset; + constantPool.stringCache.remove(constantChars); + constantPool.UTF8Cache.remove(constantChars); + int i = 0; + int length = 0; + int constantLength = constant.length(); + byte[] utf8encoding = new byte[Math.min(constantLength + 100, 65535)]; + int utf8encodingLength = 0; + while ((length < 65532) && (i < constantLength)) { + char current = constantChars[i]; + // we resize the byte array immediately if necessary + if (length + 3 > (utf8encodingLength = utf8encoding.length)) { + System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[Math.min(utf8encodingLength + 100, 65535)]), 0, length); + } + if ((current >= 0x0001) && (current <= 0x007F)) { + // we only need one byte: ASCII table + utf8encoding[length++] = (byte) current; + } else { + if (current > 0x07FF) { + // we need 3 bytes + utf8encoding[length++] = (byte) (0xE0 | ((current >> 12) & 0x0F)); // 0xE0 = 1110 0000 + utf8encoding[length++] = (byte) (0x80 | ((current >> 6) & 0x3F)); // 0x80 = 1000 0000 + utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 + } else { + // we can be 0 or between 0x0080 and 0x07FF + // In that case we only need 2 bytes + utf8encoding[length++] = (byte) (0xC0 | ((current >> 6) & 0x1F)); // 0xC0 = 1100 0000 + utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 + } + } + i++; + } + // check if all the string is encoded (PR 1PR2DWJ) + // the string is too big to be encoded in one pass + newStringBuffer(); + dup(); + // write the first part + char[] subChars = new char[i]; + System.arraycopy(constantChars, 0, subChars, 0, i); + System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[length]), 0, length); + index = constantPool.literalIndex(subChars, utf8encoding); + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (index > 255) { + // Generate a ldc_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc_w); + } + writeUnsignedShort(index); + } else { + // Generate a ldc + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc); + } + writeUnsignedByte(index); + } + // write the remaining part + invokeStringBufferStringConstructor(); + while (i < constantLength) { + length = 0; + utf8encoding = new byte[Math.min(constantLength - i + 100, 65535)]; + int startIndex = i; + while ((length < 65532) && (i < constantLength)) { + char current = constantChars[i]; + // we resize the byte array immediately if necessary + if (constantLength + 2 > (utf8encodingLength = utf8encoding.length)) { + System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[Math.min(utf8encodingLength + 100, 65535)]), 0, length); + } + if ((current >= 0x0001) && (current <= 0x007F)) { + // we only need one byte: ASCII table + utf8encoding[length++] = (byte) current; + } else { + if (current > 0x07FF) { + // we need 3 bytes + utf8encoding[length++] = (byte) (0xE0 | ((current >> 12) & 0x0F)); // 0xE0 = 1110 0000 + utf8encoding[length++] = (byte) (0x80 | ((current >> 6) & 0x3F)); // 0x80 = 1000 0000 + utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 + } else { + // we can be 0 or between 0x0080 and 0x07FF + // In that case we only need 2 bytes + utf8encoding[length++] = (byte) (0xC0 | ((current >> 6) & 0x1F)); // 0xC0 = 1100 0000 + utf8encoding[length++] = (byte) (0x80 | (current & 0x3F)); // 0x80 = 1000 0000 + } + } + i++; + } + // the next part is done + subChars = new char[i - startIndex]; + System.arraycopy(constantChars, startIndex, subChars, 0, i - startIndex); + System.arraycopy(utf8encoding, 0, (utf8encoding = new byte[length]), 0, length); + index = constantPool.literalIndex(subChars, utf8encoding); + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + if (index > 255) { + // Generate a ldc_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc_w); + } + writeUnsignedShort(index); + } else { + // Generate a ldc + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc); + } + writeUnsignedByte(index); + } + // now on the stack it should be a StringBuffer and a string. + invokeStringBufferAppendForType(T_String); + } + invokeStringBufferToString(); + invokeStringIntern(); + } + } + final public void ldc2_w(double constant) { + countLabels = 0; + int index = constantPool.literalIndex(constant); + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + // Generate a ldc2_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc2_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc2_w); + } + writeUnsignedShort(index); + } + final public void ldc2_w(long constant) { + countLabels = 0; + int index = constantPool.literalIndex(constant); + stackDepth += 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + // Generate a ldc2_w + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldc2_w; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldc2_w); + } + writeUnsignedShort(index); + } + final public void ldiv() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_ldiv; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ldiv); + } + } + final public void lload(int iArg) { + countLabels = 0; + stackDepth += 2; + if (maxLocals <= iArg + 1) { + maxLocals = iArg + 2; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lload); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_lload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lload); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void lload_0() { + countLabels = 0; + stackDepth += 2; + if (maxLocals < 2) { + maxLocals = 2; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lload_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lload_0); + } + } + final public void lload_1() { + countLabels = 0; + stackDepth += 2; + if (maxLocals < 3) { + maxLocals = 3; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lload_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lload_1); + } + } + final public void lload_2() { + countLabels = 0; + stackDepth += 2; + if (maxLocals < 4) { + maxLocals = 4; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lload_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lload_2); + } + } + final public void lload_3() { + countLabels = 0; + stackDepth += 2; + if (maxLocals < 5) { + maxLocals = 5; + } + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lload_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lload_3); + } + } + final public void lmul() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lmul; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lmul); + } + } + final public void lneg() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lneg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lneg); + } + } + public final void load(LocalVariableBinding localBinding) { + countLabels = 0; + TypeBinding typeBinding = localBinding.type; + int resolvedPosition = localBinding.resolvedPosition; + // Using dedicated int bytecode + if (typeBinding == IntBinding) { + switch (resolvedPosition) { + case 0 : + this.iload_0(); + break; + case 1 : + this.iload_1(); + break; + case 2 : + this.iload_2(); + break; + case 3 : + this.iload_3(); + break; + default : + this.iload(resolvedPosition); + } + return; + } + // Using dedicated float bytecode + if (typeBinding == FloatBinding) { + switch (resolvedPosition) { + case 0 : + this.fload_0(); + break; + case 1 : + this.fload_1(); + break; + case 2 : + this.fload_2(); + break; + case 3 : + this.fload_3(); + break; + default : + this.fload(resolvedPosition); + } + return; + } + // Using dedicated long bytecode + if (typeBinding == LongBinding) { + switch (resolvedPosition) { + case 0 : + this.lload_0(); + break; + case 1 : + this.lload_1(); + break; + case 2 : + this.lload_2(); + break; + case 3 : + this.lload_3(); + break; + default : + this.lload(resolvedPosition); + } + return; + } + // Using dedicated double bytecode + if (typeBinding == DoubleBinding) { + switch (resolvedPosition) { + case 0 : + this.dload_0(); + break; + case 1 : + this.dload_1(); + break; + case 2 : + this.dload_2(); + break; + case 3 : + this.dload_3(); + break; + default : + this.dload(resolvedPosition); + } + return; + } + // boolean, byte, char and short are handled as int + if ((typeBinding == ByteBinding) + || (typeBinding == CharBinding) + || (typeBinding == BooleanBinding) + || (typeBinding == ShortBinding)) { + switch (resolvedPosition) { + case 0 : + this.iload_0(); + break; + case 1 : + this.iload_1(); + break; + case 2 : + this.iload_2(); + break; + case 3 : + this.iload_3(); + break; + default : + this.iload(resolvedPosition); + } + return; + } -public void newJavaLangAssertionError() { - // new: java.lang.AssertionError - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_new; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_new); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionError()); -} + // Reference object + switch (resolvedPosition) { + case 0 : + this.aload_0(); + break; + case 1 : + this.aload_1(); + break; + case 2 : + this.aload_2(); + break; + case 3 : + this.aload_3(); + break; + default : + this.aload(resolvedPosition); + } + } + public final void load(TypeBinding typeBinding, int resolvedPosition) { + countLabels = 0; + // Using dedicated int bytecode + if (typeBinding == IntBinding) { + switch (resolvedPosition) { + case 0 : + this.iload_0(); + break; + case 1 : + this.iload_1(); + break; + case 2 : + this.iload_2(); + break; + case 3 : + this.iload_3(); + break; + default : + this.iload(resolvedPosition); + } + return; + } + // Using dedicated float bytecode + if (typeBinding == FloatBinding) { + switch (resolvedPosition) { + case 0 : + this.fload_0(); + break; + case 1 : + this.fload_1(); + break; + case 2 : + this.fload_2(); + break; + case 3 : + this.fload_3(); + break; + default : + this.fload(resolvedPosition); + } + return; + } + // Using dedicated long bytecode + if (typeBinding == LongBinding) { + switch (resolvedPosition) { + case 0 : + this.lload_0(); + break; + case 1 : + this.lload_1(); + break; + case 2 : + this.lload_2(); + break; + case 3 : + this.lload_3(); + break; + default : + this.lload(resolvedPosition); + } + return; + } + // Using dedicated double bytecode + if (typeBinding == DoubleBinding) { + switch (resolvedPosition) { + case 0 : + this.dload_0(); + break; + case 1 : + this.dload_1(); + break; + case 2 : + this.dload_2(); + break; + case 3 : + this.dload_3(); + break; + default : + this.dload(resolvedPosition); + } + return; + } + // boolean, byte, char and short are handled as int + if ((typeBinding == ByteBinding) + || (typeBinding == CharBinding) + || (typeBinding == BooleanBinding) + || (typeBinding == ShortBinding)) { + switch (resolvedPosition) { + case 0 : + this.iload_0(); + break; + case 1 : + this.iload_1(); + break; + case 2 : + this.iload_2(); + break; + case 3 : + this.iload_3(); + break; + default : + this.iload(resolvedPosition); + } + return; + } -public void newNoClassDefFoundError() { // new: java.lang.NoClassDefFoundError - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_new; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_new); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangNoClassDefFoundError()); -} -public void newStringBuffer() { // new: java.lang.StringBuffer - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_new; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_new); - } - writeUnsignedShort(constantPool.literalIndexForJavaLangStringBuffer()); -} -public void newWrapperFor(int typeID) { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_new; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_new); - } - switch (typeID) { - case T_int : // new: java.lang.Integer - writeUnsignedShort(constantPool.literalIndexForJavaLangInteger()); - break; - case T_boolean : // new: java.lang.Boolean - writeUnsignedShort(constantPool.literalIndexForJavaLangBoolean()); - break; - case T_byte : // new: java.lang.Byte - writeUnsignedShort(constantPool.literalIndexForJavaLangByte()); - break; - case T_char : // new: java.lang.Character - writeUnsignedShort(constantPool.literalIndexForJavaLangCharacter()); - break; - case T_float : // new: java.lang.Float - writeUnsignedShort(constantPool.literalIndexForJavaLangFloat()); - break; - case T_double : // new: java.lang.Double - writeUnsignedShort(constantPool.literalIndexForJavaLangDouble()); - break; - case T_short : // new: java.lang.Short - writeUnsignedShort(constantPool.literalIndexForJavaLangShort()); - break; - case T_long : // new: java.lang.Long - writeUnsignedShort(constantPool.literalIndexForJavaLangLong()); - break; - case T_void : // new: java.lang.Void - writeUnsignedShort(constantPool.literalIndexForJavaLangVoid()); - } -} -final public void nop() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_nop; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_nop); - } -} -final public void pop() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_pop; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_pop); - } -} -final public void pop2() { - countLabels = 0; - stackDepth -= 2; - try { - position++; - bCodeStream[classFileOffset++] = OPC_pop2; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_pop2); - } -} -final public void putfield(FieldBinding fieldBinding) { - countLabels = 0; - int id; - if (((id = fieldBinding.type.id) == T_double) || (id == T_long)) - stackDepth -= 3; - else - stackDepth -= 2; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_putfield; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_putfield); - } - writeUnsignedShort(constantPool.literalIndex(fieldBinding)); -} -final public void putstatic(FieldBinding fieldBinding) { - countLabels = 0; - int id; - if (((id = fieldBinding.type.id) == T_double) || (id == T_long)) - stackDepth -= 2; - else - stackDepth -= 1; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_putstatic; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_putstatic); - } - writeUnsignedShort(constantPool.literalIndex(fieldBinding)); -} -public void record(LocalVariableBinding local) { - if (!generateLocalVariableTableAttributes) - return; - if (allLocalsCounter == locals.length) { - // resize the collection - System.arraycopy(locals, 0, (locals = new LocalVariableBinding[allLocalsCounter + LOCALS_INCREMENT]), 0, allLocalsCounter); - } - locals[allLocalsCounter++] = local; - local.initializationPCs = new int[4]; - local.initializationCount = 0; -} -public void recordPositionsFrom(int startPC, int sourcePos) { + // Reference object + switch (resolvedPosition) { + case 0 : + this.aload_0(); + break; + case 1 : + this.aload_1(); + break; + case 2 : + this.aload_2(); + break; + case 3 : + this.aload_3(); + break; + default : + this.aload(resolvedPosition); + } + } + public final void loadInt(int resolvedPosition) { + // Using dedicated int bytecode + switch (resolvedPosition) { + case 0 : + this.iload_0(); + break; + case 1 : + this.iload_1(); + break; + case 2 : + this.iload_2(); + break; + case 3 : + this.iload_3(); + break; + default : + this.iload(resolvedPosition); + } + } + public final void loadObject(int resolvedPosition) { + switch (resolvedPosition) { + case 0 : + this.aload_0(); + break; + case 1 : + this.aload_1(); + break; + case 2 : + this.aload_2(); + break; + case 3 : + this.aload_3(); + break; + default : + this.aload(resolvedPosition); + } + } + final public void lookupswitch(CaseLabel defaultLabel, int[] keys, int[] sortedIndexes, CaseLabel[] casesLabel) { + countLabels = 0; + stackDepth--; + int length = keys.length; + int pos = position; + defaultLabel.placeInstruction(); + for (int i = 0; i < length; i++) { + casesLabel[i].placeInstruction(); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lookupswitch; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lookupswitch); + } + for (int i = (3 - (pos % 4)); i > 0; i--) { + position++; // Padding + classFileOffset++; + } + defaultLabel.branch(); + writeSignedWord(length); + for (int i = 0; i < length; i++) { + writeSignedWord(keys[sortedIndexes[i]]); + casesLabel[sortedIndexes[i]].branch(); + } + } + final public void lor() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lor; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lor); + } + } + final public void lrem() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lrem; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lrem); + } + } + final public void lreturn() { + countLabels = 0; + stackDepth -= 2; + // the stackDepth should be equal to 0 + try { + position++; + bCodeStream[classFileOffset++] = OPC_lreturn; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lreturn); + } + } + final public void lshl() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lshl; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lshl); + } + } + final public void lshr() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lshr; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lshr); + } + } + final public void lstore(int iArg) { + countLabels = 0; + stackDepth -= 2; + if (maxLocals <= iArg + 1) { + maxLocals = iArg + 2; + } + if (iArg > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lstore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lstore); + } + writeUnsignedShort(iArg); + } else { + try { + position++; + bCodeStream[classFileOffset++] = OPC_lstore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lstore); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) iArg; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) iArg); + } + } + } + final public void lstore_0() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 2) { + maxLocals = 2; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lstore_0; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lstore_0); + } + } + final public void lstore_1() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 3) { + maxLocals = 3; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lstore_1; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lstore_1); + } + } + final public void lstore_2() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 4) { + maxLocals = 4; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lstore_2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lstore_2); + } + } + final public void lstore_3() { + countLabels = 0; + stackDepth -= 2; + if (maxLocals < 5) { + maxLocals = 5; + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_lstore_3; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lstore_3); + } + } + final public void lsub() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lsub; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lsub); + } + } + final public void lushr() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lushr; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lushr); + } + } + final public void lxor() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_lxor; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_lxor); + } + } + final public void monitorenter() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_monitorenter; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_monitorenter); + } + } + final public void monitorexit() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_monitorexit; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_monitorexit); + } + } + final public void multianewarray(TypeBinding typeBinding, int dimensions) { + countLabels = 0; + stackDepth += (1 - dimensions); + try { + position++; + bCodeStream[classFileOffset++] = OPC_multianewarray; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_multianewarray); + } + writeUnsignedShort(constantPool.literalIndex(typeBinding)); + writeUnsignedByte(dimensions); + } + public static void needImplementation() { + } + /** + * We didn't call it new, because there is a conflit with the new keyword + */ + final public void new_(TypeBinding typeBinding) { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_new; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_new); + } + writeUnsignedShort(constantPool.literalIndex(typeBinding)); + } + final public void newarray(int array_Type) { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_newarray; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_newarray); + } + writeUnsignedByte(array_Type); + } + public void newArray(Scope scope, ArrayBinding arrayBinding) { + TypeBinding component = arrayBinding.elementsType(scope); + switch (component.id) { + case T_int : + this.newarray(10); + break; + case T_byte : + this.newarray(8); + break; + case T_boolean : + this.newarray(4); + break; + case T_short : + this.newarray(9); + break; + case T_char : + this.newarray(5); + break; + case T_long : + this.newarray(11); + break; + case T_float : + this.newarray(6); + break; + case T_double : + this.newarray(7); + break; + default : + this.anewarray(component); + } + } + public void newJavaLangError() { + // new: java.lang.Error + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_new; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_new); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangError()); + } - /* Record positions in the table, only if nothing has - * already been recorded. Since we output them on the way - * up (children first for more specific info) - * The pcToSourceMap table is always sorted. - */ + public void newJavaLangAssertionError() { + // new: java.lang.AssertionError + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_new; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_new); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangAssertionError()); + } - if (!generateLineNumberAttributes) - return; - if (sourcePos == 0) - return; + public void newNoClassDefFoundError() { // new: java.lang.NoClassDefFoundError + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_new; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_new); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangNoClassDefFoundError()); + } + public void newStringBuffer() { // new: java.lang.StringBuffer + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_new; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_new); + } + writeUnsignedShort(constantPool.literalIndexForJavaLangStringBuffer()); + } + public void newWrapperFor(int typeID) { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_new; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_new); + } + switch (typeID) { + case T_int : // new: java.lang.Integer + writeUnsignedShort(constantPool.literalIndexForJavaLangInteger()); + break; + case T_boolean : // new: java.lang.Boolean + writeUnsignedShort(constantPool.literalIndexForJavaLangBoolean()); + break; + case T_byte : // new: java.lang.Byte + writeUnsignedShort(constantPool.literalIndexForJavaLangByte()); + break; + case T_char : // new: java.lang.Character + writeUnsignedShort(constantPool.literalIndexForJavaLangCharacter()); + break; + case T_float : // new: java.lang.Float + writeUnsignedShort(constantPool.literalIndexForJavaLangFloat()); + break; + case T_double : // new: java.lang.Double + writeUnsignedShort(constantPool.literalIndexForJavaLangDouble()); + break; + case T_short : // new: java.lang.Short + writeUnsignedShort(constantPool.literalIndexForJavaLangShort()); + break; + case T_long : // new: java.lang.Long + writeUnsignedShort(constantPool.literalIndexForJavaLangLong()); + break; + case T_void : // new: java.lang.Void + writeUnsignedShort(constantPool.literalIndexForJavaLangVoid()); + } + } + final public void nop() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_nop; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_nop); + } + } + final public void pop() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_pop; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_pop); + } + } + final public void pop2() { + countLabels = 0; + stackDepth -= 2; + try { + position++; + bCodeStream[classFileOffset++] = OPC_pop2; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_pop2); + } + } + final public void putfield(FieldBinding fieldBinding) { + countLabels = 0; + int id; + if (((id = fieldBinding.type.id) == T_double) || (id == T_long)) + stackDepth -= 3; + else + stackDepth -= 2; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_putfield; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_putfield); + } + writeUnsignedShort(constantPool.literalIndex(fieldBinding)); + } + final public void putstatic(FieldBinding fieldBinding) { + countLabels = 0; + int id; + if (((id = fieldBinding.type.id) == T_double) || (id == T_long)) + stackDepth -= 2; + else + stackDepth -= 1; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_putstatic; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_putstatic); + } + writeUnsignedShort(constantPool.literalIndex(fieldBinding)); + } + public void record(LocalVariableBinding local) { + if (!generateLocalVariableTableAttributes) + return; + if (allLocalsCounter == locals.length) { + // resize the collection + System.arraycopy(locals, 0, (locals = new LocalVariableBinding[allLocalsCounter + LOCALS_INCREMENT]), 0, allLocalsCounter); + } + locals[allLocalsCounter++] = local; + local.initializationPCs = new int[4]; + local.initializationCount = 0; + } + public void recordPositionsFrom(int startPC, int sourcePos) { - // no code generated for this node. e.g. field without any initialization - if (position == startPC) - return; + /* Record positions in the table, only if nothing has + * already been recorded. Since we output them on the way + * up (children first for more specific info) + * The pcToSourceMap table is always sorted. + */ - // Widening an existing entry that already has the same source positions - if (pcToSourceMapSize + 4 > pcToSourceMap.length) { - // resize the array pcToSourceMap - System.arraycopy(pcToSourceMap, 0, (pcToSourceMap = new int[pcToSourceMapSize << 1]), 0, pcToSourceMapSize); - } - int newLine = ClassFile.searchLineNumber(lineSeparatorPositions, sourcePos); - // lastEntryPC represents the endPC of the lastEntry. - if (pcToSourceMapSize > 0) { - // in this case there is already an entry in the table - if (pcToSourceMap[pcToSourceMapSize - 1] != newLine) { - if (startPC < lastEntryPC) { - // we forgot to add an entry. - // search if an existing entry exists for startPC - int insertionIndex = insertionIndex(pcToSourceMap, pcToSourceMapSize, startPC); - if (insertionIndex != -1) { - // there is no existing entry starting with startPC. - int existingEntryIndex = indexOfSameLineEntrySincePC(startPC, newLine); // index for PC - /* the existingEntryIndex corresponds to en entry with the same line and a PC >= startPC. - in this case it is relevant to widen this entry instead of creating a new one. - line1: this(a, - b, - c); - with this code we generate each argument. We generate a aload0 to invoke the constructor. There is no entry for this - aload0 bytecode. The first entry is the one for the argument a. - But we want the constructor call to start at the aload0 pc and not just at the pc of the first argument. - So we widen the existing entry (if there is one) or we create a new entry with the startPC. - */ - if (existingEntryIndex != -1) { - // widen existing entry - pcToSourceMap[existingEntryIndex] = startPC; - } else { - // we have to add an entry that won't be sorted. So we sort the pcToSourceMap. - System.arraycopy(pcToSourceMap, insertionIndex, pcToSourceMap, insertionIndex + 2, pcToSourceMapSize - insertionIndex); - pcToSourceMap[insertionIndex++] = startPC; - pcToSourceMap[insertionIndex] = newLine; - pcToSourceMapSize += 2; - } - } - if (position != lastEntryPC) { // no bytecode since last entry pc - pcToSourceMap[pcToSourceMapSize++] = lastEntryPC; - pcToSourceMap[pcToSourceMapSize++] = newLine; - } - } else { - // we can safely add the new entry. The endPC of the previous entry is not in conflit with the startPC of the new entry. - pcToSourceMap[pcToSourceMapSize++] = startPC; - pcToSourceMap[pcToSourceMapSize++] = newLine; - } - } else { - /* the last recorded entry is on the same line. But it could be relevant to widen this entry. - we want to extend this entry forward in case we generated some bytecode before the last entry that are not related to any statement - */ - if (startPC < pcToSourceMap[pcToSourceMapSize - 2]) { - int insertionIndex = insertionIndex(pcToSourceMap, pcToSourceMapSize, startPC); - if (insertionIndex != -1) { - // widen the existing entry - // we have to figure out if we need to move the last entry at another location to keep a sorted table - if ((pcToSourceMapSize > 4) && (pcToSourceMap[pcToSourceMapSize - 4] > startPC)) { - System.arraycopy(pcToSourceMap, insertionIndex, pcToSourceMap, insertionIndex + 2, pcToSourceMapSize - 2 - insertionIndex); - pcToSourceMap[insertionIndex++] = startPC; - pcToSourceMap[insertionIndex] = newLine; - } else { - pcToSourceMap[pcToSourceMapSize - 2] = startPC; - } - } - } - } - lastEntryPC = position; - } else { - // record the first entry - pcToSourceMap[pcToSourceMapSize++] = startPC; - pcToSourceMap[pcToSourceMapSize++] = newLine; - lastEntryPC = position; - } -} -/** - * @param anExceptionLabel org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel - */ -public void registerExceptionHandler(ExceptionLabel anExceptionLabel) { - int length; - if (exceptionHandlersNumber >= (length = exceptionHandlers.length)) { - // resize the exception handlers table - System.arraycopy(exceptionHandlers, 0, exceptionHandlers = new ExceptionLabel[length + LABELS_INCREMENT], 0, length); - } - // no need to resize. So just add the new exception label - exceptionHandlers[exceptionHandlersNumber++] = anExceptionLabel; -} -public final void removeNotDefinitelyAssignedVariables(Scope scope, int initStateIndex) { - // given some flow info, make sure we did not loose some variables initialization - // if this happens, then we must update their pc entries to reflect it in debug attributes - if (!generateLocalVariableTableAttributes) - return; -/* if (initStateIndex == lastInitStateIndexWhenRemovingInits) - return; - - lastInitStateIndexWhenRemovingInits = initStateIndex; - if (lastInitStateIndexWhenAddingInits != initStateIndex){ - lastInitStateIndexWhenAddingInits = -2;// reinitialize add index - // add(1)-remove(1)-add(1) -> ignore second add - // add(1)-remove(2)-add(1) -> perform second add - }*/ - for (int i = 0; i < visibleLocalsCount; i++) { - LocalVariableBinding localBinding = visibleLocals[i]; - if (localBinding != null) { - if (initStateIndex == -1 || !isDefinitelyAssigned(scope, initStateIndex, localBinding)) { - if (localBinding.initializationCount > 0) { - localBinding.recordInitializationEndPC(position); - } - } - } - } -} -/** - * @param methodDeclaration org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration - * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile - */ -public void reset(AbstractMethodDeclaration methodDeclaration, ClassFile classFile) { - init(classFile); - this.methodDeclaration = methodDeclaration; - preserveUnusedLocals = methodDeclaration.scope.problemReporter().options.preserveAllLocalVariables; - initializeMaxLocals(methodDeclaration.binding); -} -/** - * @param methodDeclaration org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration - * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile - */ -public void resetForProblemClinit(ClassFile classFile) { - init(classFile); - maxLocals = 0; -} -protected final void resizeByteArray() { - int actualLength = bCodeStream.length; - int requiredSize = actualLength + growFactor; - if (classFileOffset > requiredSize) { - requiredSize = classFileOffset + growFactor; - } - System.arraycopy(bCodeStream, 0, (bCodeStream = new byte[requiredSize]), 0, actualLength); -} -/** - * This method is used to resize the internal byte array in - * case of a ArrayOutOfBoundsException when adding the value b. - * Resize and add the new byte b inside the array. - * @param b byte - */ -protected final void resizeByteArray(byte b) { - resizeByteArray(); - bCodeStream[classFileOffset - 1] = b; -} -final public void ret(int index) { - countLabels = 0; - if (index > 255) { // Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } - try { - position++; - bCodeStream[classFileOffset++] = OPC_ret; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ret); - } - writeUnsignedShort(index); - } else { // Don't Widen - try { - position++; - bCodeStream[classFileOffset++] = OPC_ret; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_ret); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) index; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) index); - } - } -} -final public void return_() { - countLabels = 0; - // the stackDepth should be equal to 0 - try { - position++; - bCodeStream[classFileOffset++] = OPC_return; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_return); - } -} -final public void saload() { - countLabels = 0; - stackDepth--; - try { - position++; - bCodeStream[classFileOffset++] = OPC_saload; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_saload); - } -} -final public void sastore() { - countLabels = 0; - stackDepth -= 3; - try { - position++; - bCodeStream[classFileOffset++] = OPC_sastore; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_sastore); - } -} -/** - * @param operatorConstant int - * @param type_ID int - */ -public void sendOperator(int operatorConstant, int type_ID) { - switch (type_ID) { - case T_int : - case T_boolean : - case T_char : - case T_byte : - case T_short : - switch (operatorConstant) { - case PLUS : - this.iadd(); - break; - case MINUS : - this.isub(); - break; - case MULTIPLY : - this.imul(); - break; - case DIVIDE : - this.idiv(); - break; - case REMAINDER : - this.irem(); - break; - case LEFT_SHIFT : - this.ishl(); - break; - case RIGHT_SHIFT : - this.ishr(); - break; - case UNSIGNED_RIGHT_SHIFT : - this.iushr(); - break; - case AND : - this.iand(); - break; - case OR : - this.ior(); - break; - case XOR : - this.ixor(); - break; - } - break; - case T_long : - switch (operatorConstant) { - case PLUS : - this.ladd(); - break; - case MINUS : - this.lsub(); - break; - case MULTIPLY : - this.lmul(); - break; - case DIVIDE : - this.ldiv(); - break; - case REMAINDER : - this.lrem(); - break; - case LEFT_SHIFT : - this.lshl(); - break; - case RIGHT_SHIFT : - this.lshr(); - break; - case UNSIGNED_RIGHT_SHIFT : - this.lushr(); - break; - case AND : - this.land(); - break; - case OR : - this.lor(); - break; - case XOR : - this.lxor(); - break; - } - break; - case T_float : - switch (operatorConstant) { - case PLUS : - this.fadd(); - break; - case MINUS : - this.fsub(); - break; - case MULTIPLY : - this.fmul(); - break; - case DIVIDE : - this.fdiv(); - break; - case REMAINDER : - this.frem(); - } - break; - case T_double : - switch (operatorConstant) { - case PLUS : - this.dadd(); - break; - case MINUS : - this.dsub(); - break; - case MULTIPLY : - this.dmul(); - break; - case DIVIDE : - this.ddiv(); - break; - case REMAINDER : - this.drem(); - } - } -} -final public void sipush(int s) { - countLabels = 0; - stackDepth++; - if (stackDepth > stackMax) - stackMax = stackDepth; - try { - position++; - bCodeStream[classFileOffset++] = OPC_sipush; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_sipush); - } - writeSignedShort(s); -} -public static final void sort(int[] tab, int lo0, int hi0, int[] result) { - int lo = lo0; - int hi = hi0; - int mid; - if (hi0 > lo0) { - /* Arbitrarily establishing partition element as the midpoint of - * the array. - */ - mid = tab[ (lo0 + hi0) / 2]; - // loop through the array until indices cross - while (lo <= hi) { - /* find the first element that is greater than or equal to - * the partition element starting from the left Index. - */ - while ((lo < hi0) && (tab[lo] < mid)) - ++lo; - /* find an element that is smaller than or equal to - * the partition element starting from the right Index. - */ - while ((hi > lo0) && (tab[hi] > mid)) - --hi; - // if the indexes have not crossed, swap - if (lo <= hi) { - swap(tab, lo, hi, result); - ++lo; - --hi; - } - } - /* If the right index has not reached the left side of array - * must now sort the left partition. - */ - if (lo0 < hi) - sort(tab, lo0, hi, result); - /* If the left index has not reached the right side of array - * must now sort the right partition. - */ - if (lo < hi0) - sort(tab, lo, hi0, result); - } -} -public final void store(LocalVariableBinding localBinding, boolean valueRequired) { - TypeBinding type = localBinding.type; - int position = localBinding.resolvedPosition; - // Using dedicated int bytecode - if ((type == IntBinding) || (type == CharBinding) || (type == ByteBinding) || (type == ShortBinding) || (type == BooleanBinding)) { - if (valueRequired) - this.dup(); - switch (position) { - case 0 : - this.istore_0(); - break; - case 1 : - this.istore_1(); - break; - case 2 : - this.istore_2(); - break; - case 3 : - this.istore_3(); - break; - default : - this.istore(position); - } - return; - } - // Using dedicated float bytecode - if (type == FloatBinding) { - if (valueRequired) - this.dup(); - switch (position) { - case 0 : - this.fstore_0(); - break; - case 1 : - this.fstore_1(); - break; - case 2 : - this.fstore_2(); - break; - case 3 : - this.fstore_3(); - break; - default : - this.fstore(position); - } - return; - } - // Using dedicated long bytecode - if (type == LongBinding) { - if (valueRequired) - this.dup2(); - switch (position) { - case 0 : - this.lstore_0(); - break; - case 1 : - this.lstore_1(); - break; - case 2 : - this.lstore_2(); - break; - case 3 : - this.lstore_3(); - break; - default : - this.lstore(position); - } - return; - } - // Using dedicated double bytecode - if (type == DoubleBinding) { - if (valueRequired) - this.dup2(); - switch (position) { - case 0 : - this.dstore_0(); - break; - case 1 : - this.dstore_1(); - break; - case 2 : - this.dstore_2(); - break; - case 3 : - this.dstore_3(); - break; - default : - this.dstore(position); - } - return; - } - // Reference object - if (valueRequired) - this.dup(); - switch (position) { - case 0 : - this.astore_0(); - break; - case 1 : - this.astore_1(); - break; - case 2 : - this.astore_2(); - break; - case 3 : - this.astore_3(); - break; - default : - this.astore(position); - } -} -public final void store(TypeBinding type, int position) { - // Using dedicated int bytecode - if ((type == IntBinding) || (type == CharBinding) || (type == ByteBinding) || (type == ShortBinding) || (type == BooleanBinding)) { - switch (position) { - case 0 : - this.istore_0(); - break; - case 1 : - this.istore_1(); - break; - case 2 : - this.istore_2(); - break; - case 3 : - this.istore_3(); - break; - default : - this.istore(position); - } - return; - } - // Using dedicated float bytecode - if (type == FloatBinding) { - switch (position) { - case 0 : - this.fstore_0(); - break; - case 1 : - this.fstore_1(); - break; - case 2 : - this.fstore_2(); - break; - case 3 : - this.fstore_3(); - break; - default : - this.fstore(position); - } - return; - } - // Using dedicated long bytecode - if (type == LongBinding) { - switch (position) { - case 0 : - this.lstore_0(); - break; - case 1 : - this.lstore_1(); - break; - case 2 : - this.lstore_2(); - break; - case 3 : - this.lstore_3(); - break; - default : - this.lstore(position); - } - return; - } - // Using dedicated double bytecode - if (type == DoubleBinding) { - switch (position) { - case 0 : - this.dstore_0(); - break; - case 1 : - this.dstore_1(); - break; - case 2 : - this.dstore_2(); - break; - case 3 : - this.dstore_3(); - break; - default : - this.dstore(position); - } - return; - } - // Reference object - switch (position) { - case 0 : - this.astore_0(); - break; - case 1 : - this.astore_1(); - break; - case 2 : - this.astore_2(); - break; - case 3 : - this.astore_3(); - break; - default : - this.astore(position); - } -} -public final void storeInt(int position) { - switch (position) { - case 0 : - this.istore_0(); - break; - case 1 : - this.istore_1(); - break; - case 2 : - this.istore_2(); - break; - case 3 : - this.istore_3(); - break; - default : - this.istore(position); - } -} -public final void storeObject(int position) { - switch (position) { - case 0 : - this.astore_0(); - break; - case 1 : - this.astore_1(); - break; - case 2 : - this.astore_2(); - break; - case 3 : - this.astore_3(); - break; - default : - this.astore(position); - } -} -final public void swap() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_swap; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_swap); - } -} -private static final void swap(int a[], int i, int j, int result[]) { - int T; - T = a[i]; - a[i] = a[j]; - a[j] = T; - T = result[j]; - result[j] = result[i]; - result[i] = T; -} -final public void tableswitch(CaseLabel defaultLabel, int low, int high, int[] keys, int[] sortedIndexes, CaseLabel[] casesLabel) { - countLabels = 0; - stackDepth--; - int length = casesLabel.length; - int pos = position; - defaultLabel.placeInstruction(); - for (int i = 0; i < length; i++) - casesLabel[i].placeInstruction(); - try { - position++; - bCodeStream[classFileOffset++] = OPC_tableswitch; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_tableswitch); - } - for (int i = (3 - (pos % 4)); i > 0; i--) { - position++; // Padding - classFileOffset++; - } - defaultLabel.branch(); - writeSignedWord(low); - writeSignedWord(high); - int i = low, j = low; - // the index j is used to know if the index i is one of the missing entries in case of an - // optimized tableswitch - while (true) { - int index; - int key = keys[index = sortedIndexes[j - low]]; - if (key == i) { - casesLabel[index].branch(); - j++; - if (i == high) break; // if high is maxint, then avoids wrapping to minint. - } else { - defaultLabel.branch(); - } - i++; - } -} -public String toString() { - StringBuffer buffer = new StringBuffer("( position:"); //$NON-NLS-1$ - buffer.append(position); - buffer.append(",\nstackDepth:"); //$NON-NLS-1$ - buffer.append(stackDepth); - buffer.append(",\nmaxStack:"); //$NON-NLS-1$ - buffer.append(stackMax); - buffer.append(",\nmaxLocals:"); //$NON-NLS-1$ - buffer.append(maxLocals); - buffer.append(")"); //$NON-NLS-1$ - return buffer.toString(); -} -public void updateLastRecordedEndPC(int pos) { + if (!generateLineNumberAttributes) + return; + if (sourcePos == 0) + return; - /* Tune positions in the table, this is due to some - * extra bytecodes being - * added to some user code (jumps). */ - /** OLD CODE - if (!generateLineNumberAttributes) - return; - pcToSourceMap[pcToSourceMapSize - 1][1] = position; - // need to update the initialization endPC in case of generation of local variable attributes. - updateLocalVariablesAttribute(pos); - */ + // no code generated for this node. e.g. field without any initialization + if (position == startPC) + return; - if (!generateLineNumberAttributes) - return; - // need to update the initialization endPC in case of generation of local variable attributes. - updateLocalVariablesAttribute(pos); -} -public void updateLocalVariablesAttribute(int pos) { - // need to update the initialization endPC in case of generation of local variable attributes. - if (generateLocalVariableTableAttributes) { - for (int i = 0, max = locals.length; i < max; i++) { - LocalVariableBinding local = locals[i]; - if ((local != null) && (local.initializationCount > 0)) { - if (local.initializationPCs[((local.initializationCount - 1) << 1) + 1] == pos) { - local.initializationPCs[((local.initializationCount - 1) << 1) + 1] = position; - } - } - } - } -} -final public void wide() { - countLabels = 0; - try { - position++; - bCodeStream[classFileOffset++] = OPC_wide; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(OPC_wide); - } -} -public final void writeByte(byte b) { - try { - position++; - bCodeStream[classFileOffset++] = b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(b); - } -} -public final void writeByteAtPos(int pos, byte b) { - try { - bCodeStream[pos] = b; - } catch (IndexOutOfBoundsException ex) { - resizeByteArray(); - bCodeStream[pos] = b; - } -} -/** - * Write a unsigned 8 bits value into the byte array - * @param b the signed byte - */ -public final void writeSignedByte(int b) { - try { - position++; - bCodeStream[classFileOffset++] = (byte) b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) b); - } -} -/** - * Write a signed 16 bits value into the byte array - * @param b the signed short - */ -public final void writeSignedShort(int b) { - try { - position++; - bCodeStream[classFileOffset++] = (byte) (b >> 8); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) (b >> 8)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) b); - } -} -public final void writeSignedShort(int pos, int b) { - int currentOffset = startingClassFileOffset + pos; - try { - bCodeStream[currentOffset] = (byte) (b >> 8); - } catch (IndexOutOfBoundsException e) { - resizeByteArray(); - bCodeStream[currentOffset] = (byte) (b >> 8); - } - try { - bCodeStream[currentOffset + 1] = (byte) b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(); - bCodeStream[currentOffset + 1] = (byte) b; - } -} -public final void writeSignedWord(int value) { - try { - position++; - bCodeStream[classFileOffset++] = (byte) ((value & 0xFF000000) >> 24); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) ((value & 0xFF000000) >> 24)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) ((value & 0xFF0000) >> 16); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) ((value & 0xFF0000) >> 16)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) ((value & 0xFF00) >> 8); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) ((value & 0xFF00) >> 8)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) (value & 0xFF); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) (value & 0xFF)); - } -} -public final void writeSignedWord(int pos, int value) { - int currentOffset = startingClassFileOffset + pos; - try { - bCodeStream[currentOffset++] = (byte) ((value & 0xFF000000) >> 24); - } catch (IndexOutOfBoundsException e) { - resizeByteArray(); - bCodeStream[currentOffset-1] = (byte) ((value & 0xFF000000) >> 24); - } - try { - bCodeStream[currentOffset++] = (byte) ((value & 0xFF0000) >> 16); - } catch (IndexOutOfBoundsException e) { - resizeByteArray(); - bCodeStream[currentOffset-1] = (byte) ((value & 0xFF0000) >> 16); - } - try { - bCodeStream[currentOffset++] = (byte) ((value & 0xFF00) >> 8); - } catch (IndexOutOfBoundsException e) { - resizeByteArray(); - bCodeStream[currentOffset-1] = (byte) ((value & 0xFF00) >> 8); - } - try { - bCodeStream[currentOffset++] = (byte) (value & 0xFF); - } catch (IndexOutOfBoundsException e) { - resizeByteArray(); - bCodeStream[currentOffset-1] = (byte) (value & 0xFF); - } -} -/** - * Write a unsigned 8 bits value into the byte array - * @param b the unsigned byte - */ -public final void writeUnsignedByte(int b) { - try { - position++; - bCodeStream[classFileOffset++] = (byte) b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) b); - } -} -/** - * Write a unsigned 16 bits value into the byte array - * @param b the unsigned short - */ -public final void writeUnsignedShort(int b) { - try { - position++; - bCodeStream[classFileOffset++] = (byte) (b >>> 8); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) (b >>> 8)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) b; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) b); - } -} -/** - * Write a unsigned 32 bits value into the byte array - * @param value the unsigned word - */ -public final void writeUnsignedWord(int value) { - try { - position++; - bCodeStream[classFileOffset++] = (byte) (value >>> 24); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) (value >>> 24)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) (value >>> 16); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) (value >>> 16)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) (value >>> 8); - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) (value >>> 8)); - } - try { - position++; - bCodeStream[classFileOffset++] = (byte) value; - } catch (IndexOutOfBoundsException e) { - resizeByteArray((byte) value); - } -} + // Widening an existing entry that already has the same source positions + if (pcToSourceMapSize + 4 > pcToSourceMap.length) { + // resize the array pcToSourceMap + System.arraycopy(pcToSourceMap, 0, (pcToSourceMap = new int[pcToSourceMapSize << 1]), 0, pcToSourceMapSize); + } + int newLine = ClassFile.searchLineNumber(lineSeparatorPositions, sourcePos); + // lastEntryPC represents the endPC of the lastEntry. + if (pcToSourceMapSize > 0) { + // in this case there is already an entry in the table + if (pcToSourceMap[pcToSourceMapSize - 1] != newLine) { + if (startPC < lastEntryPC) { + // we forgot to add an entry. + // search if an existing entry exists for startPC + int insertionIndex = insertionIndex(pcToSourceMap, pcToSourceMapSize, startPC); + if (insertionIndex != -1) { + // there is no existing entry starting with startPC. + int existingEntryIndex = indexOfSameLineEntrySincePC(startPC, newLine); // index for PC + /* the existingEntryIndex corresponds to en entry with the same line and a PC >= startPC. + in this case it is relevant to widen this entry instead of creating a new one. + line1: this(a, + b, + c); + with this code we generate each argument. We generate a aload0 to invoke the constructor. There is no entry for this + aload0 bytecode. The first entry is the one for the argument a. + But we want the constructor call to start at the aload0 pc and not just at the pc of the first argument. + So we widen the existing entry (if there is one) or we create a new entry with the startPC. + */ + if (existingEntryIndex != -1) { + // widen existing entry + pcToSourceMap[existingEntryIndex] = startPC; + } else { + // we have to add an entry that won't be sorted. So we sort the pcToSourceMap. + System.arraycopy( + pcToSourceMap, + insertionIndex, + pcToSourceMap, + insertionIndex + 2, + pcToSourceMapSize - insertionIndex); + pcToSourceMap[insertionIndex++] = startPC; + pcToSourceMap[insertionIndex] = newLine; + pcToSourceMapSize += 2; + } + } + if (position != lastEntryPC) { // no bytecode since last entry pc + pcToSourceMap[pcToSourceMapSize++] = lastEntryPC; + pcToSourceMap[pcToSourceMapSize++] = newLine; + } + } else { + // we can safely add the new entry. The endPC of the previous entry is not in conflit with the startPC of the new entry. + pcToSourceMap[pcToSourceMapSize++] = startPC; + pcToSourceMap[pcToSourceMapSize++] = newLine; + } + } else { + /* the last recorded entry is on the same line. But it could be relevant to widen this entry. + we want to extend this entry forward in case we generated some bytecode before the last entry that are not related to any statement + */ + if (startPC < pcToSourceMap[pcToSourceMapSize - 2]) { + int insertionIndex = insertionIndex(pcToSourceMap, pcToSourceMapSize, startPC); + if (insertionIndex != -1) { + // widen the existing entry + // we have to figure out if we need to move the last entry at another location to keep a sorted table + if ((pcToSourceMapSize > 4) && (pcToSourceMap[pcToSourceMapSize - 4] > startPC)) { + System.arraycopy( + pcToSourceMap, + insertionIndex, + pcToSourceMap, + insertionIndex + 2, + pcToSourceMapSize - 2 - insertionIndex); + pcToSourceMap[insertionIndex++] = startPC; + pcToSourceMap[insertionIndex] = newLine; + } else { + pcToSourceMap[pcToSourceMapSize - 2] = startPC; + } + } + } + } + lastEntryPC = position; + } else { + // record the first entry + pcToSourceMap[pcToSourceMapSize++] = startPC; + pcToSourceMap[pcToSourceMapSize++] = newLine; + lastEntryPC = position; + } + } + /** + * @param anExceptionLabel org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel + */ + public void registerExceptionHandler(ExceptionLabel anExceptionLabel) { + int length; + if (exceptionHandlersNumber >= (length = exceptionHandlers.length)) { + // resize the exception handlers table + System.arraycopy(exceptionHandlers, 0, exceptionHandlers = new ExceptionLabel[length + LABELS_INCREMENT], 0, length); + } + // no need to resize. So just add the new exception label + exceptionHandlers[exceptionHandlersNumber++] = anExceptionLabel; + } + public final void removeNotDefinitelyAssignedVariables(Scope scope, int initStateIndex) { + // given some flow info, make sure we did not loose some variables initialization + // if this happens, then we must update their pc entries to reflect it in debug attributes + if (!generateLocalVariableTableAttributes) + return; + /* if (initStateIndex == lastInitStateIndexWhenRemovingInits) + return; + + lastInitStateIndexWhenRemovingInits = initStateIndex; + if (lastInitStateIndexWhenAddingInits != initStateIndex){ + lastInitStateIndexWhenAddingInits = -2;// reinitialize add index + // add(1)-remove(1)-add(1) -> ignore second add + // add(1)-remove(2)-add(1) -> perform second add + }*/ + for (int i = 0; i < visibleLocalsCount; i++) { + LocalVariableBinding localBinding = visibleLocals[i]; + if (localBinding != null) { + if (initStateIndex == -1 || !isDefinitelyAssigned(scope, initStateIndex, localBinding)) { + if (localBinding.initializationCount > 0) { + localBinding.recordInitializationEndPC(position); + } + } + } + } + } + /** + * @param methodDeclaration org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration + * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile + */ + public void reset(AbstractMethodDeclaration methodDeclaration, ClassFile classFile) { + init(classFile); + this.methodDeclaration = methodDeclaration; + preserveUnusedLocals = methodDeclaration.scope.problemReporter().options.preserveAllLocalVariables; + initializeMaxLocals(methodDeclaration.binding); + } + /** + * @param methodDeclaration org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration + * @param classFile org.eclipse.jdt.internal.compiler.codegen.ClassFile + */ + public void resetForProblemClinit(ClassFile classFile) { + init(classFile); + maxLocals = 0; + } + protected final void resizeByteArray() { + int actualLength = bCodeStream.length; + int requiredSize = actualLength + growFactor; + if (classFileOffset > requiredSize) { + requiredSize = classFileOffset + growFactor; + } + System.arraycopy(bCodeStream, 0, (bCodeStream = new byte[requiredSize]), 0, actualLength); + } + /** + * This method is used to resize the internal byte array in + * case of a ArrayOutOfBoundsException when adding the value b. + * Resize and add the new byte b inside the array. + * @param b byte + */ + protected final void resizeByteArray(byte b) { + resizeByteArray(); + bCodeStream[classFileOffset - 1] = b; + } + final public void ret(int index) { + countLabels = 0; + if (index > 255) { // Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + try { + position++; + bCodeStream[classFileOffset++] = OPC_ret; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ret); + } + writeUnsignedShort(index); + } else { // Don't Widen + try { + position++; + bCodeStream[classFileOffset++] = OPC_ret; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_ret); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) index; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) index); + } + } + } + final public void return_() { + countLabels = 0; + // the stackDepth should be equal to 0 + try { + position++; + bCodeStream[classFileOffset++] = OPC_return; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_return); + } + } + final public void saload() { + countLabels = 0; + stackDepth--; + try { + position++; + bCodeStream[classFileOffset++] = OPC_saload; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_saload); + } + } + final public void sastore() { + countLabels = 0; + stackDepth -= 3; + try { + position++; + bCodeStream[classFileOffset++] = OPC_sastore; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_sastore); + } + } + /** + * @param operatorConstant int + * @param type_ID int + */ + public void sendOperator(int operatorConstant, int type_ID) { + switch (type_ID) { + case T_int : + case T_boolean : + case T_char : + case T_byte : + case T_short : + switch (operatorConstant) { + case PLUS : + this.iadd(); + break; + case MINUS : + this.isub(); + break; + case MULTIPLY : + this.imul(); + break; + case DIVIDE : + this.idiv(); + break; + case REMAINDER : + this.irem(); + break; + case LEFT_SHIFT : + this.ishl(); + break; + case RIGHT_SHIFT : + this.ishr(); + break; + case UNSIGNED_RIGHT_SHIFT : + this.iushr(); + break; + case AND : + this.iand(); + break; + case OR : + this.ior(); + break; + case XOR : + this.ixor(); + break; + } + break; + case T_long : + switch (operatorConstant) { + case PLUS : + this.ladd(); + break; + case MINUS : + this.lsub(); + break; + case MULTIPLY : + this.lmul(); + break; + case DIVIDE : + this.ldiv(); + break; + case REMAINDER : + this.lrem(); + break; + case LEFT_SHIFT : + this.lshl(); + break; + case RIGHT_SHIFT : + this.lshr(); + break; + case UNSIGNED_RIGHT_SHIFT : + this.lushr(); + break; + case AND : + this.land(); + break; + case OR : + this.lor(); + break; + case XOR : + this.lxor(); + break; + } + break; + case T_float : + switch (operatorConstant) { + case PLUS : + this.fadd(); + break; + case MINUS : + this.fsub(); + break; + case MULTIPLY : + this.fmul(); + break; + case DIVIDE : + this.fdiv(); + break; + case REMAINDER : + this.frem(); + } + break; + case T_double : + switch (operatorConstant) { + case PLUS : + this.dadd(); + break; + case MINUS : + this.dsub(); + break; + case MULTIPLY : + this.dmul(); + break; + case DIVIDE : + this.ddiv(); + break; + case REMAINDER : + this.drem(); + } + } + } + final public void sipush(int s) { + countLabels = 0; + stackDepth++; + if (stackDepth > stackMax) + stackMax = stackDepth; + try { + position++; + bCodeStream[classFileOffset++] = OPC_sipush; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_sipush); + } + writeSignedShort(s); + } + public static final void sort(int[] tab, int lo0, int hi0, int[] result) { + int lo = lo0; + int hi = hi0; + int mid; + if (hi0 > lo0) { + /* Arbitrarily establishing partition element as the midpoint of + * the array. + */ + mid = tab[(lo0 + hi0) / 2]; + // loop through the array until indices cross + while (lo <= hi) { + /* find the first element that is greater than or equal to + * the partition element starting from the left Index. + */ + while ((lo < hi0) && (tab[lo] < mid)) + ++lo; + /* find an element that is smaller than or equal to + * the partition element starting from the right Index. + */ + while ((hi > lo0) && (tab[hi] > mid)) + --hi; + // if the indexes have not crossed, swap + if (lo <= hi) { + swap(tab, lo, hi, result); + ++lo; + --hi; + } + } + /* If the right index has not reached the left side of array + * must now sort the left partition. + */ + if (lo0 < hi) + sort(tab, lo0, hi, result); + /* If the left index has not reached the right side of array + * must now sort the right partition. + */ + if (lo < hi0) + sort(tab, lo, hi0, result); + } + } + public final void store(LocalVariableBinding localBinding, boolean valueRequired) { + TypeBinding type = localBinding.type; + int position = localBinding.resolvedPosition; + // Using dedicated int bytecode + if ((type == IntBinding) + || (type == CharBinding) + || (type == ByteBinding) + || (type == ShortBinding) + || (type == BooleanBinding)) { + if (valueRequired) + this.dup(); + switch (position) { + case 0 : + this.istore_0(); + break; + case 1 : + this.istore_1(); + break; + case 2 : + this.istore_2(); + break; + case 3 : + this.istore_3(); + break; + default : + this.istore(position); + } + return; + } + // Using dedicated float bytecode + if (type == FloatBinding) { + if (valueRequired) + this.dup(); + switch (position) { + case 0 : + this.fstore_0(); + break; + case 1 : + this.fstore_1(); + break; + case 2 : + this.fstore_2(); + break; + case 3 : + this.fstore_3(); + break; + default : + this.fstore(position); + } + return; + } + // Using dedicated long bytecode + if (type == LongBinding) { + if (valueRequired) + this.dup2(); + switch (position) { + case 0 : + this.lstore_0(); + break; + case 1 : + this.lstore_1(); + break; + case 2 : + this.lstore_2(); + break; + case 3 : + this.lstore_3(); + break; + default : + this.lstore(position); + } + return; + } + // Using dedicated double bytecode + if (type == DoubleBinding) { + if (valueRequired) + this.dup2(); + switch (position) { + case 0 : + this.dstore_0(); + break; + case 1 : + this.dstore_1(); + break; + case 2 : + this.dstore_2(); + break; + case 3 : + this.dstore_3(); + break; + default : + this.dstore(position); + } + return; + } + // Reference object + if (valueRequired) + this.dup(); + switch (position) { + case 0 : + this.astore_0(); + break; + case 1 : + this.astore_1(); + break; + case 2 : + this.astore_2(); + break; + case 3 : + this.astore_3(); + break; + default : + this.astore(position); + } + } + public final void store(TypeBinding type, int position) { + // Using dedicated int bytecode + if ((type == IntBinding) + || (type == CharBinding) + || (type == ByteBinding) + || (type == ShortBinding) + || (type == BooleanBinding)) { + switch (position) { + case 0 : + this.istore_0(); + break; + case 1 : + this.istore_1(); + break; + case 2 : + this.istore_2(); + break; + case 3 : + this.istore_3(); + break; + default : + this.istore(position); + } + return; + } + // Using dedicated float bytecode + if (type == FloatBinding) { + switch (position) { + case 0 : + this.fstore_0(); + break; + case 1 : + this.fstore_1(); + break; + case 2 : + this.fstore_2(); + break; + case 3 : + this.fstore_3(); + break; + default : + this.fstore(position); + } + return; + } + // Using dedicated long bytecode + if (type == LongBinding) { + switch (position) { + case 0 : + this.lstore_0(); + break; + case 1 : + this.lstore_1(); + break; + case 2 : + this.lstore_2(); + break; + case 3 : + this.lstore_3(); + break; + default : + this.lstore(position); + } + return; + } + // Using dedicated double bytecode + if (type == DoubleBinding) { + switch (position) { + case 0 : + this.dstore_0(); + break; + case 1 : + this.dstore_1(); + break; + case 2 : + this.dstore_2(); + break; + case 3 : + this.dstore_3(); + break; + default : + this.dstore(position); + } + return; + } + // Reference object + switch (position) { + case 0 : + this.astore_0(); + break; + case 1 : + this.astore_1(); + break; + case 2 : + this.astore_2(); + break; + case 3 : + this.astore_3(); + break; + default : + this.astore(position); + } + } + public final void storeInt(int position) { + switch (position) { + case 0 : + this.istore_0(); + break; + case 1 : + this.istore_1(); + break; + case 2 : + this.istore_2(); + break; + case 3 : + this.istore_3(); + break; + default : + this.istore(position); + } + } + public final void storeObject(int position) { + switch (position) { + case 0 : + this.astore_0(); + break; + case 1 : + this.astore_1(); + break; + case 2 : + this.astore_2(); + break; + case 3 : + this.astore_3(); + break; + default : + this.astore(position); + } + } + final public void swap() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_swap; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_swap); + } + } + private static final void swap(int a[], int i, int j, int result[]) { + int T; + T = a[i]; + a[i] = a[j]; + a[j] = T; + T = result[j]; + result[j] = result[i]; + result[i] = T; + } + final public void tableswitch( + CaseLabel defaultLabel, + int low, + int high, + int[] keys, + int[] sortedIndexes, + CaseLabel[] casesLabel) { + countLabels = 0; + stackDepth--; + int length = casesLabel.length; + int pos = position; + defaultLabel.placeInstruction(); + for (int i = 0; i < length; i++) + casesLabel[i].placeInstruction(); + try { + position++; + bCodeStream[classFileOffset++] = OPC_tableswitch; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_tableswitch); + } + for (int i = (3 - (pos % 4)); i > 0; i--) { + position++; // Padding + classFileOffset++; + } + defaultLabel.branch(); + writeSignedWord(low); + writeSignedWord(high); + int i = low, j = low; + // the index j is used to know if the index i is one of the missing entries in case of an + // optimized tableswitch + while (true) { + int index; + int key = keys[index = sortedIndexes[j - low]]; + if (key == i) { + casesLabel[index].branch(); + j++; + if (i == high) + break; // if high is maxint, then avoids wrapping to minint. + } else { + defaultLabel.branch(); + } + i++; + } + } + public String toString() { + StringBuffer buffer = new StringBuffer("( position:"); //$NON-NLS-1$ + buffer.append(position); + buffer.append(",\nstackDepth:"); //$NON-NLS-1$ + buffer.append(stackDepth); + buffer.append(",\nmaxStack:"); //$NON-NLS-1$ + buffer.append(stackMax); + buffer.append(",\nmaxLocals:"); //$NON-NLS-1$ + buffer.append(maxLocals); + buffer.append(")"); //$NON-NLS-1$ + return buffer.toString(); + } + public void updateLastRecordedEndPC(int pos) { -public void generateWideConditionalBranch(byte opcode, Label lbl) { - /* we handle the goto_w problem inside an if.... with some macro expansion - * at the bytecode level - * instead of: - * if_...... lbl - * we have: - * ifne - * goto - * l1 gotow // l3 is a wide target - * l2 .... - */ - Label l1 = new Label(this); - try { - position++; - bCodeStream[classFileOffset++] = opcode; - } catch (IndexOutOfBoundsException e) { - resizeByteArray(opcode); - } - l1.branch(); - Label l2 = new Label(this); - this.internal_goto_(l2); - l1.place(); - this.goto_w(lbl); - l2.place(); -} + /* Tune positions in the table, this is due to some + * extra bytecodes being + * added to some user code (jumps). */ + /** OLD CODE + if (!generateLineNumberAttributes) + return; + pcToSourceMap[pcToSourceMapSize - 1][1] = position; + // need to update the initialization endPC in case of generation of local variable attributes. + updateLocalVariablesAttribute(pos); + */ + + if (!generateLineNumberAttributes) + return; + // need to update the initialization endPC in case of generation of local variable attributes. + updateLocalVariablesAttribute(pos); + } + public void updateLocalVariablesAttribute(int pos) { + // need to update the initialization endPC in case of generation of local variable attributes. + if (generateLocalVariableTableAttributes) { + for (int i = 0, max = locals.length; i < max; i++) { + LocalVariableBinding local = locals[i]; + if ((local != null) && (local.initializationCount > 0)) { + if (local.initializationPCs[((local.initializationCount - 1) << 1) + 1] == pos) { + local.initializationPCs[((local.initializationCount - 1) << 1) + 1] = position; + } + } + } + } + } + final public void wide() { + countLabels = 0; + try { + position++; + bCodeStream[classFileOffset++] = OPC_wide; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(OPC_wide); + } + } + public final void writeByte(byte b) { + try { + position++; + bCodeStream[classFileOffset++] = b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(b); + } + } + public final void writeByteAtPos(int pos, byte b) { + try { + bCodeStream[pos] = b; + } catch (IndexOutOfBoundsException ex) { + resizeByteArray(); + bCodeStream[pos] = b; + } + } + /** + * Write a unsigned 8 bits value into the byte array + * @param b the signed byte + */ + public final void writeSignedByte(int b) { + try { + position++; + bCodeStream[classFileOffset++] = (byte) b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) b); + } + } + /** + * Write a signed 16 bits value into the byte array + * @param b the signed short + */ + public final void writeSignedShort(int b) { + try { + position++; + bCodeStream[classFileOffset++] = (byte) (b >> 8); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) (b >> 8)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) b); + } + } + public final void writeSignedShort(int pos, int b) { + int currentOffset = startingClassFileOffset + pos; + try { + bCodeStream[currentOffset] = (byte) (b >> 8); + } catch (IndexOutOfBoundsException e) { + resizeByteArray(); + bCodeStream[currentOffset] = (byte) (b >> 8); + } + try { + bCodeStream[currentOffset + 1] = (byte) b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(); + bCodeStream[currentOffset + 1] = (byte) b; + } + } + public final void writeSignedWord(int value) { + try { + position++; + bCodeStream[classFileOffset++] = (byte) ((value & 0xFF000000) >> 24); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) ((value & 0xFF000000) >> 24)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) ((value & 0xFF0000) >> 16); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) ((value & 0xFF0000) >> 16)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) ((value & 0xFF00) >> 8); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) ((value & 0xFF00) >> 8)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) (value & 0xFF); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) (value & 0xFF)); + } + } + public final void writeSignedWord(int pos, int value) { + int currentOffset = startingClassFileOffset + pos; + try { + bCodeStream[currentOffset++] = (byte) ((value & 0xFF000000) >> 24); + } catch (IndexOutOfBoundsException e) { + resizeByteArray(); + bCodeStream[currentOffset - 1] = (byte) ((value & 0xFF000000) >> 24); + } + try { + bCodeStream[currentOffset++] = (byte) ((value & 0xFF0000) >> 16); + } catch (IndexOutOfBoundsException e) { + resizeByteArray(); + bCodeStream[currentOffset - 1] = (byte) ((value & 0xFF0000) >> 16); + } + try { + bCodeStream[currentOffset++] = (byte) ((value & 0xFF00) >> 8); + } catch (IndexOutOfBoundsException e) { + resizeByteArray(); + bCodeStream[currentOffset - 1] = (byte) ((value & 0xFF00) >> 8); + } + try { + bCodeStream[currentOffset++] = (byte) (value & 0xFF); + } catch (IndexOutOfBoundsException e) { + resizeByteArray(); + bCodeStream[currentOffset - 1] = (byte) (value & 0xFF); + } + } + /** + * Write a unsigned 8 bits value into the byte array + * @param b the unsigned byte + */ + public final void writeUnsignedByte(int b) { + try { + position++; + bCodeStream[classFileOffset++] = (byte) b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) b); + } + } + /** + * Write a unsigned 16 bits value into the byte array + * @param b the unsigned short + */ + public final void writeUnsignedShort(int b) { + try { + position++; + bCodeStream[classFileOffset++] = (byte) (b >>> 8); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) (b >>> 8)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) b; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) b); + } + } + /** + * Write a unsigned 32 bits value into the byte array + * @param value the unsigned word + */ + public final void writeUnsignedWord(int value) { + try { + position++; + bCodeStream[classFileOffset++] = (byte) (value >>> 24); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) (value >>> 24)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) (value >>> 16); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) (value >>> 16)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) (value >>> 8); + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) (value >>> 8)); + } + try { + position++; + bCodeStream[classFileOffset++] = (byte) value; + } catch (IndexOutOfBoundsException e) { + resizeByteArray((byte) value); + } + } + + public void generateWideConditionalBranch(byte opcode, Label lbl) { + /* we handle the goto_w problem inside an if.... with some macro expansion + * at the bytecode level + * instead of: + * if_...... lbl + * we have: + * ifne + * goto + * l1 gotow // l3 is a wide target + * l2 .... + */ + Label l1 = new Label(this); + try { + position++; + bCodeStream[classFileOffset++] = opcode; + } catch (IndexOutOfBoundsException e) { + resizeByteArray(opcode); + } + l1.branch(); + Label l2 = new Label(this); + this.internal_goto_(l2); + l1.place(); + this.goto_w(lbl); + l2.place(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java index d46b0a2..299d267 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/parser/Parser.java @@ -13,9 +13,9 @@ package net.sourceforge.phpdt.internal.compiler.parser; import net.sourceforge.phpdt.core.compiler.*; import net.sourceforge.phpdt.core.compiler.InvalidInputException; import net.sourceforge.phpdt.internal.compiler.*; -import net.sourceforge.phpdt.internal.compiler.env.*; +import net.sourceforge.phpdt.internal.compiler.env.*; import net.sourceforge.phpdt.internal.compiler.impl.*; -import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.ast.*; import net.sourceforge.phpdt.internal.compiler.lookup.*; import net.sourceforge.phpdt.internal.compiler.problem.*; import net.sourceforge.phpdt.internal.compiler.util.*; @@ -24,7430 +24,7531 @@ import java.io.*; import java.util.ArrayList; public class Parser implements BindingIds, ParserBasicInformation, ITerminalSymbols, CompilerModifiers, OperatorIds, TypeIds { - protected ProblemReporter problemReporter; - public int firstToken ; // handle for multiple parsing goals - public int lastAct ; //handle for multiple parsing goals - protected ReferenceContext referenceContext; - public int currentToken; - private int synchronizedBlockSourceStart; - - //error recovery management - protected int lastCheckPoint; - protected RecoveredElement currentElement; - public static boolean VERBOSE_RECOVERY = false; - protected boolean restartRecovery; - protected int listLength; // for recovering some incomplete list (interfaces, throws or parameters) - protected boolean hasReportedError; - protected int recoveredStaticInitializerStart; - protected int lastIgnoredToken, nextIgnoredToken; - protected int lastErrorEndPosition; - - // 1.4 feature - protected boolean assertMode = false; - - //internal data for the automat - protected final static int StackIncrement = 255; - protected int stateStackTop; - protected int[] stack = new int[StackIncrement]; - //scanner token - public Scanner scanner; - //ast stack - final static int AstStackIncrement = 100; - protected int astPtr; - protected AstNode[] astStack = new AstNode[AstStackIncrement]; - protected int astLengthPtr; - protected int[] astLengthStack; - public CompilationUnitDeclaration compilationUnit; /*the result from parse()*/ - AstNode [] noAstNodes = new AstNode[AstStackIncrement]; - //expression stack - final static int ExpressionStackIncrement = 100; - protected int expressionPtr; - protected Expression[] expressionStack = new Expression[ExpressionStackIncrement]; - protected int expressionLengthPtr; - protected int[] expressionLengthStack; - Expression [] noExpressions = new Expression[ExpressionStackIncrement]; - //identifiers stacks - protected int identifierPtr; - protected char[][] identifierStack; - protected int identifierLengthPtr; - protected int[] identifierLengthStack; - protected long[] identifierPositionStack; - //positions , dimensions , .... (what ever is int) ..... stack - protected int intPtr; - protected int[] intStack; - 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 lParenPos,rParenPos; //accurate only when used ! - //modifiers dimensions nestedType etc....... - protected boolean optimizeStringLiterals =true; - protected int modifiers; - protected int modifiersSourceStart; - protected int nestedType, dimensions; - protected int[] nestedMethod; //the ptr is nestedType - protected int[] realBlockStack; - protected int realBlockPtr; - 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[] variablesCounter; - //===DATA===DATA===DATA===DATA===DATA===DATA===// - public final static byte rhs[] = {0, - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, - 2,2,2,1,1,1,1,1,1,1,1,1,1,1,1, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 2,2,1,1,1,1,3,4,0,1,2,1,1,1,1, - 1,1,1,1,1,5,1,2,1,2,2,2,1,1,2, - 2,2,4,1,1,1,1,2,1,1,1,1,1,1,1, - 1,1,1,1,2,3,3,2,2,1,3,1,3,1,2, - 1,1,1,3,0,3,1,1,1,1,1,1,1,4,1, - 3,3,7,0,0,0,0,0,2,1,1,1,2,2,4, - 4,5,4,4,2,1,2,3,3,1,3,3,1,3,1, - 4,0,2,1,2,2,4,1,1,2,5,5,7,7,7, - 7,2,2,3,2,2,3,1,2,1,2,1,1,2,2, - 1,1,1,1,1,3,3,4,1,3,4,0,1,2,1, - 1,1,1,2,3,4,0,1,1,1,1,1,1,1,1, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 1,3,3,2,1,1,1,1,1,1,1,5,7,7,6, - 2,3,3,4,1,2,2,1,2,3,2,5,5,7,9, - 9,1,1,1,1,3,3,5,2,3,2,3,3,3,5, - 1,3,4,1,2,5,2,1,1,1,1,1,1,3,1, - 1,3,3,3,3,3,1,1,5,6,8,7,2,0,2, - 0,1,3,4,4,1,2,3,2,1,1,2,2,3,3, - 4,6,6,4,4,1,1,1,1,2,2,0,1,1,3, - 3,1,3,3,1,3,3,1,5,5,4,1,3,3,3, - 1,3,3,1,3,3,3,1,3,3,3,3,3,1,3, - 3,1,3,1,3,1,3,1,3,1,3,1,5,1,1, - 3,3,1,1,1,1,1,1,1,1,1,1,1,1,1, - 1,1,1,1,1,0,1,0,1,0,1,0,1,0,1, - 0,1,0,2,0,1,0,1,0,1,0,1,0,1,0, - 1,0,1,0,2,0,0,1,0,1,0,1,0,1,0, - 1 + protected ProblemReporter problemReporter; + public int firstToken; // handle for multiple parsing goals + public int lastAct; //handle for multiple parsing goals + protected ReferenceContext referenceContext; + public int currentToken; + private int synchronizedBlockSourceStart; + + //error recovery management + protected int lastCheckPoint; + protected RecoveredElement currentElement; + public static boolean VERBOSE_RECOVERY = false; + protected boolean restartRecovery; + protected int listLength; // for recovering some incomplete list (interfaces, throws or parameters) + protected boolean hasReportedError; + protected int recoveredStaticInitializerStart; + protected int lastIgnoredToken, nextIgnoredToken; + protected int lastErrorEndPosition; + + // 1.4 feature + protected boolean assertMode = false; + + //internal data for the automat + protected final static int StackIncrement = 255; + protected int stateStackTop; + protected int[] stack = new int[StackIncrement]; + //scanner token + public Scanner scanner; + //ast stack + final static int AstStackIncrement = 100; + protected int astPtr; + protected AstNode[] astStack = new AstNode[AstStackIncrement]; + protected int astLengthPtr; + protected int[] astLengthStack; + public CompilationUnitDeclaration compilationUnit; /*the result from parse()*/ + AstNode[] noAstNodes = new AstNode[AstStackIncrement]; + //expression stack + final static int ExpressionStackIncrement = 100; + protected int expressionPtr; + protected Expression[] expressionStack = new Expression[ExpressionStackIncrement]; + protected int expressionLengthPtr; + protected int[] expressionLengthStack; + Expression[] noExpressions = new Expression[ExpressionStackIncrement]; + //identifiers stacks + protected int identifierPtr; + protected char[][] identifierStack; + protected int identifierLengthPtr; + protected int[] identifierLengthStack; + protected long[] identifierPositionStack; + //positions , dimensions , .... (what ever is int) ..... stack + protected int intPtr; + protected int[] intStack; + 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 lParenPos, rParenPos; //accurate only when used ! + //modifiers dimensions nestedType etc....... + protected boolean optimizeStringLiterals = true; + protected int modifiers; + protected int modifiersSourceStart; + protected int nestedType, dimensions; + protected int[] nestedMethod; //the ptr is nestedType + protected int[] realBlockStack; + protected int realBlockPtr; + 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[] variablesCounter; + //===DATA===DATA===DATA===DATA===DATA===DATA===// + public final static byte rhs[] = + { + 0, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 2, + 1, + 1, + 1, + 1, + 3, + 4, + 0, + 1, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 5, + 1, + 2, + 1, + 2, + 2, + 2, + 1, + 1, + 2, + 2, + 2, + 4, + 1, + 1, + 1, + 1, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 3, + 3, + 2, + 2, + 1, + 3, + 1, + 3, + 1, + 2, + 1, + 1, + 1, + 3, + 0, + 3, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 4, + 1, + 3, + 3, + 7, + 0, + 0, + 0, + 0, + 0, + 2, + 1, + 1, + 1, + 2, + 2, + 4, + 4, + 5, + 4, + 4, + 2, + 1, + 2, + 3, + 3, + 1, + 3, + 3, + 1, + 3, + 1, + 4, + 0, + 2, + 1, + 2, + 2, + 4, + 1, + 1, + 2, + 5, + 5, + 7, + 7, + 7, + 7, + 2, + 2, + 3, + 2, + 2, + 3, + 1, + 2, + 1, + 2, + 1, + 1, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 3, + 3, + 4, + 1, + 3, + 4, + 0, + 1, + 2, + 1, + 1, + 1, + 1, + 2, + 3, + 4, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 3, + 3, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 5, + 7, + 7, + 6, + 2, + 3, + 3, + 4, + 1, + 2, + 2, + 1, + 2, + 3, + 2, + 5, + 5, + 7, + 9, + 9, + 1, + 1, + 1, + 1, + 3, + 3, + 5, + 2, + 3, + 2, + 3, + 3, + 3, + 5, + 1, + 3, + 4, + 1, + 2, + 5, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 3, + 1, + 1, + 3, + 3, + 3, + 3, + 3, + 1, + 1, + 5, + 6, + 8, + 7, + 2, + 0, + 2, + 0, + 1, + 3, + 4, + 4, + 1, + 2, + 3, + 2, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 6, + 6, + 4, + 4, + 1, + 1, + 1, + 1, + 2, + 2, + 0, + 1, + 1, + 3, + 3, + 1, + 3, + 3, + 1, + 3, + 3, + 1, + 5, + 5, + 4, + 1, + 3, + 3, + 3, + 1, + 3, + 3, + 1, + 3, + 3, + 3, + 1, + 3, + 3, + 3, + 3, + 3, + 1, + 3, + 3, + 1, + 3, + 1, + 3, + 1, + 3, + 1, + 3, + 1, + 3, + 1, + 5, + 1, + 1, + 3, + 3, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 2, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 2, + 0, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1 }; + + public static char asb[] = null; + public static char asr[] = null; + public static char symbol_index[] = null; + private static final String UNEXPECTED_EOF = "Unexpected End Of File"; //$NON-NLS-1$ + + public final static String name[] = { null, "++", + //$NON-NLS-1$ + "--", //$NON-NLS-1$ + "==", //$NON-NLS-1$ + "<=", //$NON-NLS-1$ + ">=", //$NON-NLS-1$ + "!=", //$NON-NLS-1$ + "<<", //$NON-NLS-1$ + ">>", //$NON-NLS-1$ + ">>>", //$NON-NLS-1$ + "+=", //$NON-NLS-1$ + "-=", //$NON-NLS-1$ + "*=", //$NON-NLS-1$ + "/=", //$NON-NLS-1$ + "&=", //$NON-NLS-1$ + "|=", //$NON-NLS-1$ + "^=", //$NON-NLS-1$ + "%=", //$NON-NLS-1$ + "<<=", //$NON-NLS-1$ + ">>=", //$NON-NLS-1$ + ">>>=", //$NON-NLS-1$ + "||", //$NON-NLS-1$ + "&&", //$NON-NLS-1$ + "+", //$NON-NLS-1$ + "-", //$NON-NLS-1$ + "!", //$NON-NLS-1$ + "%", //$NON-NLS-1$ + "^", //$NON-NLS-1$ + "&", //$NON-NLS-1$ + "*", //$NON-NLS-1$ + "|", //$NON-NLS-1$ + "~", //$NON-NLS-1$ + "/", //$NON-NLS-1$ + ">", //$NON-NLS-1$ + "<", //$NON-NLS-1$ + "(", //$NON-NLS-1$ + ")", //$NON-NLS-1$ + "{", //$NON-NLS-1$ + "}", //$NON-NLS-1$ + "[", //$NON-NLS-1$ + "]", //$NON-NLS-1$ + ";", //$NON-NLS-1$ + "?", //$NON-NLS-1$ + ":", //$NON-NLS-1$ + ",", //$NON-NLS-1$ + ".", //$NON-NLS-1$ + "=", //$NON-NLS-1$ + "", //$NON-NLS-1$ + "$empty", //$NON-NLS-1$ + "Identifier", //$NON-NLS-1$ + "abstract", //$NON-NLS-1$ + "assert", //$NON-NLS-1$ + "boolean", //$NON-NLS-1$ + "break", //$NON-NLS-1$ + "byte", //$NON-NLS-1$ + "case", //$NON-NLS-1$ + "catch", //$NON-NLS-1$ + "char", //$NON-NLS-1$ + "class", //$NON-NLS-1$ + "continue", //$NON-NLS-1$ + "default", //$NON-NLS-1$ + "do", //$NON-NLS-1$ + "double", //$NON-NLS-1$ + "else", //$NON-NLS-1$ + "extends", //$NON-NLS-1$ + "false", //$NON-NLS-1$ + "final", //$NON-NLS-1$ + "finally", //$NON-NLS-1$ + "float", //$NON-NLS-1$ + "for", //$NON-NLS-1$ + "if", //$NON-NLS-1$ + "implements", //$NON-NLS-1$ + "import", //$NON-NLS-1$ + "instanceof", //$NON-NLS-1$ + "int", //$NON-NLS-1$ + "interface", //$NON-NLS-1$ + "long", //$NON-NLS-1$ + "native", //$NON-NLS-1$ + "new", //$NON-NLS-1$ + "null", //$NON-NLS-1$ + "package", //$NON-NLS-1$ + "private", //$NON-NLS-1$ + "protected", //$NON-NLS-1$ + "public", //$NON-NLS-1$ + "return", //$NON-NLS-1$ + "short", //$NON-NLS-1$ + "static", //$NON-NLS-1$ + "strictfp", //$NON-NLS-1$ + "super", //$NON-NLS-1$ + "switch", //$NON-NLS-1$ + "synchronized", //$NON-NLS-1$ + "this", //$NON-NLS-1$ + "throw", //$NON-NLS-1$ + "throws", //$NON-NLS-1$ + "transient", //$NON-NLS-1$ + "true", //$NON-NLS-1$ + "try", //$NON-NLS-1$ + "void", //$NON-NLS-1$ + "volatile", //$NON-NLS-1$ + "while", //$NON-NLS-1$ + "IntegerLiteral", //$NON-NLS-1$ + "LongLiteral", //$NON-NLS-1$ + "FloatingPointLiteral", //$NON-NLS-1$ + "DoubleLiteral", //$NON-NLS-1$ + "CharacterLiteral", //$NON-NLS-1$ + "StringLiteral", //$NON-NLS-1$ + UNEXPECTED_EOF, "Invalid Character", + //$NON-NLS-1$ + "Goal", //$NON-NLS-1$ + "MethodBody", //$NON-NLS-1$ + "ConstructorBody", //$NON-NLS-1$ + "StaticInitializer", //$NON-NLS-1$ + "Initializer", //$NON-NLS-1$ + "Headers", //$NON-NLS-1$ + "BlockStatements", //$NON-NLS-1$ + "MethodPushModifiersHeader", //$NON-NLS-1$ + "CatchHeader", //$NON-NLS-1$ + "FieldDeclaration", //$NON-NLS-1$ + "ImportDeclaration", //$NON-NLS-1$ + "PackageDeclaration", //$NON-NLS-1$ + "TypeDeclaration", //$NON-NLS-1$ + "GenericMethodDeclaration", //$NON-NLS-1$ + "ClassBodyDeclaration", //$NON-NLS-1$ + "Expression", //$NON-NLS-1$ + "Type", //$NON-NLS-1$ + "PrimitiveType", //$NON-NLS-1$ + "ReferenceType", //$NON-NLS-1$ + "ClassOrInterfaceType", //$NON-NLS-1$ + "ArrayType", //$NON-NLS-1$ + "Name", //$NON-NLS-1$ + "Dims", //$NON-NLS-1$ + "ClassType", //$NON-NLS-1$ + "SimpleName", //$NON-NLS-1$ + "Header", //$NON-NLS-1$ + "ClassHeader", //$NON-NLS-1$ + "InterfaceHeader", //$NON-NLS-1$ + "MethodHeader", //$NON-NLS-1$ + "ConstructorHeader", //$NON-NLS-1$ + "FormalParameter", //$NON-NLS-1$ + "ImportDeclarations", //$NON-NLS-1$ + "TypeDeclarations", //$NON-NLS-1$ + "PackageDeclarationName", //$NON-NLS-1$ + "SingleTypeImportDeclarationName", //$NON-NLS-1$ + "TypeImportOnDemandDeclarationName", //$NON-NLS-1$ + "Modifiers", //$NON-NLS-1$ + "Modifier", //$NON-NLS-1$ + "ClassBody", //$NON-NLS-1$ + "ClassHeaderName", //$NON-NLS-1$ + "InterfaceTypeList", //$NON-NLS-1$ + "InterfaceType", //$NON-NLS-1$ + "ClassBodyDeclarations", //$NON-NLS-1$ + "Block", //$NON-NLS-1$ + "VariableDeclarators", //$NON-NLS-1$ + "VariableDeclarator", //$NON-NLS-1$ + "VariableDeclaratorId", //$NON-NLS-1$ + "VariableInitializer", //$NON-NLS-1$ + "ArrayInitializer", //$NON-NLS-1$ + "MethodHeaderName", //$NON-NLS-1$ + "MethodHeaderParameters", //$NON-NLS-1$ + "MethodPushModifiersHeaderName", //$NON-NLS-1$ + "ClassTypeList", //$NON-NLS-1$ + "ConstructorHeaderName", //$NON-NLS-1$ + "FormalParameterList", //$NON-NLS-1$ + "ClassTypeElt", //$NON-NLS-1$ + "StaticOnly", //$NON-NLS-1$ + "ExplicitConstructorInvocation", //$NON-NLS-1$ + "Primary", //$NON-NLS-1$ + "InterfaceBody", //$NON-NLS-1$ + "InterfaceHeaderName", //$NON-NLS-1$ + "InterfaceMemberDeclarations", //$NON-NLS-1$ + "InterfaceMemberDeclaration", //$NON-NLS-1$ + "VariableInitializers", //$NON-NLS-1$ + "BlockStatement", //$NON-NLS-1$ + "Statement", //$NON-NLS-1$ + "LocalVariableDeclaration", //$NON-NLS-1$ + "StatementWithoutTrailingSubstatement", //$NON-NLS-1$ + "StatementNoShortIf", //$NON-NLS-1$ + "StatementExpression", //$NON-NLS-1$ + "PostIncrementExpression", //$NON-NLS-1$ + "PostDecrementExpression", //$NON-NLS-1$ + "MethodInvocation", //$NON-NLS-1$ + "ClassInstanceCreationExpression", //$NON-NLS-1$ + "SwitchBlock", //$NON-NLS-1$ + "SwitchBlockStatements", //$NON-NLS-1$ + "SwitchLabels", //$NON-NLS-1$ + "SwitchBlockStatement", //$NON-NLS-1$ + "SwitchLabel", //$NON-NLS-1$ + "ConstantExpression", //$NON-NLS-1$ + "StatementExpressionList", //$NON-NLS-1$ + "OnlySynchronized", //$NON-NLS-1$ + "Catches", //$NON-NLS-1$ + "Finally", //$NON-NLS-1$ + "CatchClause", //$NON-NLS-1$ + "PushLPAREN", //$NON-NLS-1$ + "PushRPAREN", //$NON-NLS-1$ + "PrimaryNoNewArray", //$NON-NLS-1$ + "FieldAccess", //$NON-NLS-1$ + "ArrayAccess", //$NON-NLS-1$ + "ClassInstanceCreationExpressionName", //$NON-NLS-1$ + "ArgumentList", //$NON-NLS-1$ + "DimWithOrWithOutExprs", //$NON-NLS-1$ + "DimWithOrWithOutExpr", //$NON-NLS-1$ + "DimsLoop", //$NON-NLS-1$ + "OneDimLoop", //$NON-NLS-1$ + "PostfixExpression", //$NON-NLS-1$ + "UnaryExpression", //$NON-NLS-1$ + "UnaryExpressionNotPlusMinus", //$NON-NLS-1$ + "MultiplicativeExpression", //$NON-NLS-1$ + "AdditiveExpression", //$NON-NLS-1$ + "ShiftExpression", //$NON-NLS-1$ + "RelationalExpression", //$NON-NLS-1$ + "EqualityExpression", //$NON-NLS-1$ + "AndExpression", //$NON-NLS-1$ + "ExclusiveOrExpression", //$NON-NLS-1$ + "InclusiveOrExpression", //$NON-NLS-1$ + "ConditionalAndExpression", //$NON-NLS-1$ + "ConditionalOrExpression", //$NON-NLS-1$ + "ConditionalExpression", //$NON-NLS-1$ + "AssignmentExpression", //$NON-NLS-1$ + "LeftHandSide", //$NON-NLS-1$ + "AssignmentOperator" //$NON-NLS-1$ + }; + + public static short check_table[] = null; + public static char lhs[] = null; + public static char action[] = lhs; + private final static String FILEPREFIX = "parser"; //$NON-NLS-1$ + + static { + try { + initTables(); + } catch (java.io.IOException ex) { + throw new ExceptionInInitializerError(ex.getMessage()); + } + } + + public static final int RoundBracket = 0; + public static final int SquareBracket = 1; + public static final int CurlyBracket = 2; + public static final int BracketKinds = 3; + + public Parser(ProblemReporter problemReporter, boolean optimizeStringLiterals, boolean assertMode) { + + this.problemReporter = problemReporter; + this.optimizeStringLiterals = optimizeStringLiterals; + this.assertMode = assertMode; + this.initializeScanner(); + astLengthStack = new int[50]; + expressionLengthStack = new int[30]; + intStack = new int[50]; + identifierStack = new char[30][]; + identifierLengthStack = new int[30]; + nestedMethod = new int[30]; + realBlockStack = new int[30]; + identifierPositionStack = new long[30]; + variablesCounter = new int[30]; + } + /** + * + * INTERNAL USE-ONLY + */ + protected void adjustInterfaceModifiers() { + intStack[intPtr - 1] |= AccInterface; + } + public final void arrayInitializer(int length) { + //length is the size of the array Initializer + //expressionPtr points on the last elt of the arrayInitializer + //i.e. it has not been decremented yet. + + ArrayInitializer ai = new ArrayInitializer(); + if (length != 0) { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, ai.expressions = new Expression[length], 0, length); + } + pushOnExpressionStack(ai); + //positionning + ai.sourceEnd = endStatementPosition; + int searchPosition = length == 0 ? endPosition : ai.expressions[0].sourceStart; + try { + //does not work with comments(that contain '{') nor '{' describes as a unicode.... + while (scanner.source[--searchPosition] != '{') { + } + } catch (IndexOutOfBoundsException ex) { + //should never occur (except for strange cases like whose describe above) + searchPosition = (length == 0 ? endPosition : ai.expressions[0].sourceStart) - 1; + } + ai.sourceStart = searchPosition; + } + protected static int asi(int state) { + + return asb[original_state(state)]; + } + protected void blockReal() { + // See consumeLocalVariableDeclarationStatement in case of change: duplicated code + // increment the amount of declared variables for this block + realBlockStack[realBlockPtr]++; + } + private final static void buildFileFor(String filename, String tag, String[] tokens, boolean isShort) + throws java.io.IOException { + + //transform the String tokens into chars before dumping then into file + + int i = 0; + //read upto the tag + while (!tokens[i++].equals(tag)) { + } + //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); + if (isShort) + c += 32768; + chars[ic++] = (char) c; + } + + //resize + System.arraycopy(chars, 0, chars = new char[ic], 0, ic); + + buildFileForTable(filename, chars); + } + private final static void buildFileForTable(String filename, char[] chars) throws java.io.IOException { + + 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 = new java.io.FileOutputStream(filename); + stream.write(bytes); + stream.close(); + System.out.println(filename + " creation complete"); //$NON-NLS-1$ + } + public final static void buildFilesFromLPG(String dataFilename) throws java.io.IOException { + + //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.jdt.internal.compiler.parser.Parser.buildFilesFromLPG("d:/leapfrog/grammar/javadcl.java")] + + char[] contents = new char[] { }; - - - public static char asb[] = null; - public static char asr[] = null; - public static char symbol_index[] = null; - private static final String UNEXPECTED_EOF = "Unexpected End Of File" ; //$NON-NLS-1$ - - public final static String name[] = { null, - "++",//$NON-NLS-1$ - "--",//$NON-NLS-1$ - "==",//$NON-NLS-1$ - "<=",//$NON-NLS-1$ - ">=",//$NON-NLS-1$ - "!=",//$NON-NLS-1$ - "<<",//$NON-NLS-1$ - ">>",//$NON-NLS-1$ - ">>>",//$NON-NLS-1$ - "+=",//$NON-NLS-1$ - "-=",//$NON-NLS-1$ - "*=",//$NON-NLS-1$ - "/=",//$NON-NLS-1$ - "&=",//$NON-NLS-1$ - "|=",//$NON-NLS-1$ - "^=",//$NON-NLS-1$ - "%=",//$NON-NLS-1$ - "<<=",//$NON-NLS-1$ - ">>=",//$NON-NLS-1$ - ">>>=",//$NON-NLS-1$ - "||",//$NON-NLS-1$ - "&&",//$NON-NLS-1$ - "+",//$NON-NLS-1$ - "-",//$NON-NLS-1$ - "!",//$NON-NLS-1$ - "%",//$NON-NLS-1$ - "^",//$NON-NLS-1$ - "&",//$NON-NLS-1$ - "*",//$NON-NLS-1$ - "|",//$NON-NLS-1$ - "~",//$NON-NLS-1$ - "/",//$NON-NLS-1$ - ">",//$NON-NLS-1$ - "<",//$NON-NLS-1$ - "(",//$NON-NLS-1$ - ")",//$NON-NLS-1$ - "{",//$NON-NLS-1$ - "}",//$NON-NLS-1$ - "[",//$NON-NLS-1$ - "]",//$NON-NLS-1$ - ";",//$NON-NLS-1$ - "?",//$NON-NLS-1$ - ":",//$NON-NLS-1$ - ",",//$NON-NLS-1$ - ".",//$NON-NLS-1$ - "=",//$NON-NLS-1$ - "",//$NON-NLS-1$ - "$empty",//$NON-NLS-1$ - "Identifier",//$NON-NLS-1$ - "abstract",//$NON-NLS-1$ - "assert",//$NON-NLS-1$ - "boolean",//$NON-NLS-1$ - "break",//$NON-NLS-1$ - "byte",//$NON-NLS-1$ - "case",//$NON-NLS-1$ - "catch",//$NON-NLS-1$ - "char",//$NON-NLS-1$ - "class",//$NON-NLS-1$ - "continue",//$NON-NLS-1$ - "default",//$NON-NLS-1$ - "do",//$NON-NLS-1$ - "double",//$NON-NLS-1$ - "else",//$NON-NLS-1$ - "extends",//$NON-NLS-1$ - "false",//$NON-NLS-1$ - "final",//$NON-NLS-1$ - "finally",//$NON-NLS-1$ - "float",//$NON-NLS-1$ - "for",//$NON-NLS-1$ - "if",//$NON-NLS-1$ - "implements",//$NON-NLS-1$ - "import",//$NON-NLS-1$ - "instanceof",//$NON-NLS-1$ - "int",//$NON-NLS-1$ - "interface",//$NON-NLS-1$ - "long",//$NON-NLS-1$ - "native",//$NON-NLS-1$ - "new",//$NON-NLS-1$ - "null",//$NON-NLS-1$ - "package",//$NON-NLS-1$ - "private",//$NON-NLS-1$ - "protected",//$NON-NLS-1$ - "public",//$NON-NLS-1$ - "return",//$NON-NLS-1$ - "short",//$NON-NLS-1$ - "static",//$NON-NLS-1$ - "strictfp",//$NON-NLS-1$ - "super",//$NON-NLS-1$ - "switch",//$NON-NLS-1$ - "synchronized",//$NON-NLS-1$ - "this",//$NON-NLS-1$ - "throw",//$NON-NLS-1$ - "throws",//$NON-NLS-1$ - "transient",//$NON-NLS-1$ - "true",//$NON-NLS-1$ - "try",//$NON-NLS-1$ - "void",//$NON-NLS-1$ - "volatile",//$NON-NLS-1$ - "while",//$NON-NLS-1$ - "IntegerLiteral",//$NON-NLS-1$ - "LongLiteral",//$NON-NLS-1$ - "FloatingPointLiteral",//$NON-NLS-1$ - "DoubleLiteral",//$NON-NLS-1$ - "CharacterLiteral",//$NON-NLS-1$ - "StringLiteral",//$NON-NLS-1$ - UNEXPECTED_EOF, - "Invalid Character",//$NON-NLS-1$ - "Goal",//$NON-NLS-1$ - "MethodBody",//$NON-NLS-1$ - "ConstructorBody",//$NON-NLS-1$ - "StaticInitializer",//$NON-NLS-1$ - "Initializer",//$NON-NLS-1$ - "Headers",//$NON-NLS-1$ - "BlockStatements",//$NON-NLS-1$ - "MethodPushModifiersHeader",//$NON-NLS-1$ - "CatchHeader",//$NON-NLS-1$ - "FieldDeclaration",//$NON-NLS-1$ - "ImportDeclaration",//$NON-NLS-1$ - "PackageDeclaration",//$NON-NLS-1$ - "TypeDeclaration",//$NON-NLS-1$ - "GenericMethodDeclaration",//$NON-NLS-1$ - "ClassBodyDeclaration",//$NON-NLS-1$ - "Expression",//$NON-NLS-1$ - "Type",//$NON-NLS-1$ - "PrimitiveType",//$NON-NLS-1$ - "ReferenceType",//$NON-NLS-1$ - "ClassOrInterfaceType",//$NON-NLS-1$ - "ArrayType",//$NON-NLS-1$ - "Name",//$NON-NLS-1$ - "Dims",//$NON-NLS-1$ - "ClassType",//$NON-NLS-1$ - "SimpleName",//$NON-NLS-1$ - "Header",//$NON-NLS-1$ - "ClassHeader",//$NON-NLS-1$ - "InterfaceHeader",//$NON-NLS-1$ - "MethodHeader",//$NON-NLS-1$ - "ConstructorHeader",//$NON-NLS-1$ - "FormalParameter",//$NON-NLS-1$ - "ImportDeclarations",//$NON-NLS-1$ - "TypeDeclarations",//$NON-NLS-1$ - "PackageDeclarationName",//$NON-NLS-1$ - "SingleTypeImportDeclarationName",//$NON-NLS-1$ - "TypeImportOnDemandDeclarationName",//$NON-NLS-1$ - "Modifiers",//$NON-NLS-1$ - "Modifier",//$NON-NLS-1$ - "ClassBody",//$NON-NLS-1$ - "ClassHeaderName",//$NON-NLS-1$ - "InterfaceTypeList",//$NON-NLS-1$ - "InterfaceType",//$NON-NLS-1$ - "ClassBodyDeclarations",//$NON-NLS-1$ - "Block",//$NON-NLS-1$ - "VariableDeclarators",//$NON-NLS-1$ - "VariableDeclarator",//$NON-NLS-1$ - "VariableDeclaratorId",//$NON-NLS-1$ - "VariableInitializer",//$NON-NLS-1$ - "ArrayInitializer",//$NON-NLS-1$ - "MethodHeaderName",//$NON-NLS-1$ - "MethodHeaderParameters",//$NON-NLS-1$ - "MethodPushModifiersHeaderName",//$NON-NLS-1$ - "ClassTypeList",//$NON-NLS-1$ - "ConstructorHeaderName",//$NON-NLS-1$ - "FormalParameterList",//$NON-NLS-1$ - "ClassTypeElt",//$NON-NLS-1$ - "StaticOnly",//$NON-NLS-1$ - "ExplicitConstructorInvocation",//$NON-NLS-1$ - "Primary",//$NON-NLS-1$ - "InterfaceBody",//$NON-NLS-1$ - "InterfaceHeaderName",//$NON-NLS-1$ - "InterfaceMemberDeclarations",//$NON-NLS-1$ - "InterfaceMemberDeclaration",//$NON-NLS-1$ - "VariableInitializers",//$NON-NLS-1$ - "BlockStatement",//$NON-NLS-1$ - "Statement",//$NON-NLS-1$ - "LocalVariableDeclaration",//$NON-NLS-1$ - "StatementWithoutTrailingSubstatement",//$NON-NLS-1$ - "StatementNoShortIf",//$NON-NLS-1$ - "StatementExpression",//$NON-NLS-1$ - "PostIncrementExpression",//$NON-NLS-1$ - "PostDecrementExpression",//$NON-NLS-1$ - "MethodInvocation",//$NON-NLS-1$ - "ClassInstanceCreationExpression",//$NON-NLS-1$ - "SwitchBlock",//$NON-NLS-1$ - "SwitchBlockStatements",//$NON-NLS-1$ - "SwitchLabels",//$NON-NLS-1$ - "SwitchBlockStatement",//$NON-NLS-1$ - "SwitchLabel",//$NON-NLS-1$ - "ConstantExpression",//$NON-NLS-1$ - "StatementExpressionList",//$NON-NLS-1$ - "OnlySynchronized",//$NON-NLS-1$ - "Catches",//$NON-NLS-1$ - "Finally",//$NON-NLS-1$ - "CatchClause",//$NON-NLS-1$ - "PushLPAREN",//$NON-NLS-1$ - "PushRPAREN",//$NON-NLS-1$ - "PrimaryNoNewArray",//$NON-NLS-1$ - "FieldAccess",//$NON-NLS-1$ - "ArrayAccess",//$NON-NLS-1$ - "ClassInstanceCreationExpressionName",//$NON-NLS-1$ - "ArgumentList",//$NON-NLS-1$ - "DimWithOrWithOutExprs",//$NON-NLS-1$ - "DimWithOrWithOutExpr",//$NON-NLS-1$ - "DimsLoop",//$NON-NLS-1$ - "OneDimLoop",//$NON-NLS-1$ - "PostfixExpression",//$NON-NLS-1$ - "UnaryExpression",//$NON-NLS-1$ - "UnaryExpressionNotPlusMinus",//$NON-NLS-1$ - "MultiplicativeExpression",//$NON-NLS-1$ - "AdditiveExpression",//$NON-NLS-1$ - "ShiftExpression",//$NON-NLS-1$ - "RelationalExpression",//$NON-NLS-1$ - "EqualityExpression",//$NON-NLS-1$ - "AndExpression",//$NON-NLS-1$ - "ExclusiveOrExpression",//$NON-NLS-1$ - "InclusiveOrExpression",//$NON-NLS-1$ - "ConditionalAndExpression",//$NON-NLS-1$ - "ConditionalOrExpression",//$NON-NLS-1$ - "ConditionalExpression",//$NON-NLS-1$ - "AssignmentExpression",//$NON-NLS-1$ - "LeftHandSide",//$NON-NLS-1$ - "AssignmentOperator"//$NON-NLS-1$ + try { + contents = Util.getFileCharContent(new File(dataFilename), null); + } catch (IOException ex) { + System.out.println(Util.bind("parser.incorrectPath")); //$NON-NLS-1$ + 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 i = 0; + while (st.hasMoreTokens()) { + tokens[i++] = st.nextToken(); + } + final String prefix = FILEPREFIX; + i = 0; + buildFileFor(prefix + (++i) + ".rsc", "lhs", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileFor(prefix + (++i) + ".rsc", "check_table", tokens, true); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileFor(prefix + (++i) + ".rsc", "asb", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileFor(prefix + (++i) + ".rsc", "asr", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileFor(prefix + (++i) + ".rsc", "symbol_index", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ + System.out.println(Util.bind("parser.moveFiles")); //$NON-NLS-1$ + } + /* + * 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 + */ + lastCheckPoint = 0; + + RecoveredElement element = null; + if (referenceContext instanceof CompilationUnitDeclaration) { + element = new RecoveredUnit(compilationUnit, 0, this); + + /* ignore current stack state, since restarting from the beginnning + since could not trust simple brace count */ + if (true) { // experimenting restart recovery from scratch + compilationUnit.currentPackage = null; + compilationUnit.imports = null; + compilationUnit.types = null; + currentToken = 0; + listLength = 0; + return element; + } + if (compilationUnit.currentPackage != null) { + lastCheckPoint = compilationUnit.currentPackage.declarationSourceEnd + 1; + } + if (compilationUnit.imports != null) { + lastCheckPoint = compilationUnit.imports[compilationUnit.imports.length - 1].declarationSourceEnd + 1; + } + } else { + if (referenceContext instanceof AbstractMethodDeclaration) { + element = new RecoveredMethod((AbstractMethodDeclaration) referenceContext, null, 0, this); + lastCheckPoint = ((AbstractMethodDeclaration) referenceContext).bodyStart; + } else { + /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */ + if (referenceContext instanceof TypeDeclaration) { + TypeDeclaration type = (TypeDeclaration) referenceContext; + for (int i = 0; i < type.fields.length; i++) { + FieldDeclaration field = type.fields[i]; + if (!field.isField() + && field.declarationSourceStart <= scanner.initialPosition + && scanner.initialPosition <= field.declarationSourceEnd + && scanner.eofPosition <= field.declarationSourceEnd + 1) { + element = new RecoveredInitializer((Initializer) field, null, 1, this); + lastCheckPoint = field.declarationSourceStart; + break; + } + } + } + } + } + + if (element == null) + return element; + + for (int i = 0; i <= astPtr; i++) { + AstNode node = astStack[i]; + if (node instanceof AbstractMethodDeclaration) { + AbstractMethodDeclaration method = (AbstractMethodDeclaration) node; + if (method.declarationSourceEnd == 0) { + element = element.add(method, 0); + lastCheckPoint = method.bodyStart; + } else { + element = element.add(method, 0); + lastCheckPoint = method.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof Initializer) { + Initializer initializer = (Initializer) node; + if (initializer.declarationSourceEnd == 0) { + element = element.add(initializer, 1); + lastCheckPoint = initializer.bodyStart; + } else { + element = element.add(initializer, 0); + lastCheckPoint = initializer.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof FieldDeclaration) { + FieldDeclaration field = (FieldDeclaration) node; + if (field.declarationSourceEnd == 0) { + element = element.add(field, 0); + if (field.initialization == null) { + lastCheckPoint = field.sourceEnd + 1; + } else { + lastCheckPoint = field.initialization.sourceEnd + 1; + } + } else { + element = element.add(field, 0); + lastCheckPoint = field.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof TypeDeclaration) { + TypeDeclaration type = (TypeDeclaration) node; + if (type.declarationSourceEnd == 0) { + element = element.add(type, 0); + lastCheckPoint = type.bodyStart; + } else { + element = element.add(type, 0); + lastCheckPoint = type.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof ImportReference) { + ImportReference importRef = (ImportReference) node; + element = element.add(importRef, 0); + lastCheckPoint = importRef.declarationSourceEnd + 1; + } + } + return element; + } + protected static short check(int i) { + return check_table[i - (NUM_RULES + 1)]; + } + /* + * Reconsider the entire source looking for inconsistencies in {} () [] + */ + public boolean checkAndReportBracketAnomalies(ProblemReporter problemReporter) { + + scanner.wasAcr = false; + boolean anomaliesDetected = false; + try { + char[] source = scanner.source; + int[] leftCount = { 0, 0, 0 }; + int[] rightCount = { 0, 0, 0 }; + int[] depths = { 0, 0, 0 }; + int[][] leftPositions = new int[][] { new int[10], new int[10], new int[10] }; + int[][] leftDepths = new int[][] { new int[10], new int[10], new int[10] }; + int[][] rightPositions = new int[][] { new int[10], new int[10], new int[10] }; + int[][] rightDepths = new int[][] { new int[10], new int[10], new int[10] }; + scanner.currentPosition = scanner.initialPosition; //starting point (first-zero-based char) + while (scanner.currentPosition < scanner.eofPosition) { //loop for jumping over comments + try { + // ---------Consume white space and handles startPosition--------- + boolean isWhiteSpace; + do { + scanner.startPosition = scanner.currentPosition; + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + isWhiteSpace = scanner.jumpOverUnicodeWhiteSpace(); + } else { + if (scanner.recordLineSeparator && ((scanner.currentCharacter == '\r') || (scanner.currentCharacter == '\n'))) { + if (scanner.lineEnds[scanner.linePtr] < scanner.startPosition) { + // only record line positions we have not recorded yet + scanner.pushLineSeparator(); + } + } + isWhiteSpace = Character.isWhitespace(scanner.currentCharacter); + } + } while (isWhiteSpace && (scanner.currentPosition < scanner.eofPosition)); + + // -------consume token until } is found--------- + + switch (scanner.currentCharacter) { + case '{' : + { + int index = leftCount[CurlyBracket]++; + if (index == leftPositions[CurlyBracket].length) { + System.arraycopy(leftPositions[CurlyBracket], 0, (leftPositions[CurlyBracket] = new int[index * 2]), 0, index); + System.arraycopy(leftDepths[CurlyBracket], 0, (leftDepths[CurlyBracket] = new int[index * 2]), 0, index); + } + leftPositions[CurlyBracket][index] = scanner.startPosition; + leftDepths[CurlyBracket][index] = depths[CurlyBracket]++; + } + break; + case '}' : + { + int index = rightCount[CurlyBracket]++; + if (index == rightPositions[CurlyBracket].length) { + System.arraycopy(rightPositions[CurlyBracket], 0, (rightPositions[CurlyBracket] = new int[index * 2]), 0, index); + System.arraycopy(rightDepths[CurlyBracket], 0, (rightDepths[CurlyBracket] = new int[index * 2]), 0, index); + } + rightPositions[CurlyBracket][index] = scanner.startPosition; + rightDepths[CurlyBracket][index] = --depths[CurlyBracket]; + } + break; + case '(' : + { + int index = leftCount[RoundBracket]++; + if (index == leftPositions[RoundBracket].length) { + System.arraycopy(leftPositions[RoundBracket], 0, (leftPositions[RoundBracket] = new int[index * 2]), 0, index); + System.arraycopy(leftDepths[RoundBracket], 0, (leftDepths[RoundBracket] = new int[index * 2]), 0, index); + } + leftPositions[RoundBracket][index] = scanner.startPosition; + leftDepths[RoundBracket][index] = depths[RoundBracket]++; + } + break; + case ')' : + { + int index = rightCount[RoundBracket]++; + if (index == rightPositions[RoundBracket].length) { + System.arraycopy(rightPositions[RoundBracket], 0, (rightPositions[RoundBracket] = new int[index * 2]), 0, index); + System.arraycopy(rightDepths[RoundBracket], 0, (rightDepths[RoundBracket] = new int[index * 2]), 0, index); + } + rightPositions[RoundBracket][index] = scanner.startPosition; + rightDepths[RoundBracket][index] = --depths[RoundBracket]; + } + break; + case '[' : + { + int index = leftCount[SquareBracket]++; + if (index == leftPositions[SquareBracket].length) { + System.arraycopy(leftPositions[SquareBracket], 0, (leftPositions[SquareBracket] = new int[index * 2]), 0, index); + System.arraycopy(leftDepths[SquareBracket], 0, (leftDepths[SquareBracket] = new int[index * 2]), 0, index); + } + leftPositions[SquareBracket][index] = scanner.startPosition; + leftDepths[SquareBracket][index] = depths[SquareBracket]++; + } + break; + case ']' : + { + int index = rightCount[SquareBracket]++; + if (index == rightPositions[SquareBracket].length) { + System.arraycopy( + rightPositions[SquareBracket], + 0, + (rightPositions[SquareBracket] = new int[index * 2]), + 0, + index); + System.arraycopy(rightDepths[SquareBracket], 0, (rightDepths[SquareBracket] = new int[index * 2]), 0, index); + } + rightPositions[SquareBracket][index] = scanner.startPosition; + rightDepths[SquareBracket][index] = --depths[SquareBracket]; + } + break; + case '\'' : + { + if (scanner.getNextChar('\\')) { + scanner.scanEscapeCharacter(); + } else { // consume next character + scanner.unicodeAsBackSlash = false; + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + scanner.getNextUnicodeChar(); + } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + } + } + } + scanner.getNextChar('\''); + break; + } + case '"' : // consume next character + scanner.unicodeAsBackSlash = false; + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + scanner.getNextUnicodeChar(); + } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + } + } + while (scanner.currentCharacter != '"') { + if (scanner.currentCharacter == '\r') { + if (source[scanner.currentPosition] == '\n') + scanner.currentPosition++; + break; // the string cannot go further that the line + } + if (scanner.currentCharacter == '\n') { + break; // the string cannot go further that the line + } + if (scanner.currentCharacter == '\\') { + scanner.scanEscapeCharacter(); + } + // consume next character + scanner.unicodeAsBackSlash = false; + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + scanner.getNextUnicodeChar(); + } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + } + } + } + break; + case '/' : + { + int test; + if ((test = scanner.getNextChar('/', '*')) == 0) { //line comment + //get the next char + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + scanner.currentPosition++; + while (source[scanner.currentPosition] == 'u') { + scanner.currentPosition++; + } + if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c4 < 0) { //error don't care of the value + scanner.currentCharacter = 'A'; + } //something different from \n and \r + else { + scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + while (scanner.currentCharacter != '\r' && scanner.currentCharacter != '\n') { + //get the next char + scanner.startPosition = scanner.currentPosition; + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + scanner.currentPosition++; + while (source[scanner.currentPosition] == 'u') { + scanner.currentPosition++; + } + if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c4 < 0) { //error don't care of the value + scanner.currentCharacter = 'A'; + } //something different from \n and \r + else { + scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + } + if (scanner.recordLineSeparator && ((scanner.currentCharacter == '\r') || (scanner.currentCharacter == '\n'))) { + if (scanner.lineEnds[scanner.linePtr] < scanner.startPosition) { + // only record line positions we have not recorded yet + scanner.pushLineSeparator(); + } + } + break; + } + if (test > 0) { //traditional and annotation comment + boolean star = false; + // consume next character + scanner.unicodeAsBackSlash = false; + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + scanner.getNextUnicodeChar(); + } else { + if (scanner.withoutUnicodePtr != 0) { + scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; + } + } + if (scanner.currentCharacter == '*') { + star = true; + } + //get the next char + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + scanner.currentPosition++; + while (source[scanner.currentPosition] == 'u') { + scanner.currentPosition++; + } + if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c4 < 0) { //error don't care of the value + scanner.currentCharacter = 'A'; + } //something different from * and / + else { + scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + //loop until end of comment */ + while ((scanner.currentCharacter != '/') || (!star)) { + star = scanner.currentCharacter == '*'; + //get next char + if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') + && (source[scanner.currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + scanner.currentPosition++; + while (source[scanner.currentPosition] == 'u') { + scanner.currentPosition++; + } + if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 + || c4 < 0) { //error don't care of the value + scanner.currentCharacter = 'A'; + } //something different from * and / + else { + scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + } + break; + } + break; + } + default : + if (Character.isJavaIdentifierStart(scanner.currentCharacter)) { + scanner.scanIdentifierOrKeyword(); + break; + } + if (Character.isDigit(scanner.currentCharacter)) { + scanner.scanNumber(false); + break; + } + } + //-----------------end switch while try-------------------- + } catch (IndexOutOfBoundsException e) { + break; // read until EOF + } catch (InvalidInputException e) { + return false; // no clue + } + } + if (scanner.recordLineSeparator) { + compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); + } + + // check placement anomalies against other kinds of brackets + for (int kind = 0; kind < BracketKinds; kind++) { + for (int leftIndex = leftCount[kind] - 1; leftIndex >= 0; leftIndex--) { + int start = leftPositions[kind][leftIndex]; // deepest first + // find matching closing bracket + int depth = leftDepths[kind][leftIndex]; + int end = -1; + for (int i = 0; i < rightCount[kind]; i++) { + int pos = rightPositions[kind][i]; + // want matching bracket further in source with same depth + if ((pos > start) && (depth == rightDepths[kind][i])) { + end = pos; + break; + } + } + if (end < 0) { // did not find a good closing match + problemReporter.unmatchedBracket(start, referenceContext, compilationUnit.compilationResult); + return true; + } + // check if even number of opening/closing other brackets in between this pair of brackets + int balance = 0; + for (int otherKind = 0;(balance == 0) && (otherKind < BracketKinds); otherKind++) { + for (int i = 0; i < leftCount[otherKind]; i++) { + int pos = leftPositions[otherKind][i]; + if ((pos > start) && (pos < end)) + balance++; + } + for (int i = 0; i < rightCount[otherKind]; i++) { + int pos = rightPositions[otherKind][i]; + if ((pos > start) && (pos < end)) + balance--; + } + if (balance != 0) { + problemReporter.unmatchedBracket(start, referenceContext, compilationUnit.compilationResult); //bracket anomaly + return true; + } + } + } + // too many opening brackets ? + for (int i = rightCount[kind]; i < leftCount[kind]; i++) { + anomaliesDetected = true; + problemReporter.unmatchedBracket( + leftPositions[kind][leftCount[kind] - i - 1], + referenceContext, + compilationUnit.compilationResult); + } + // too many closing brackets ? + for (int i = leftCount[kind]; i < rightCount[kind]; i++) { + anomaliesDetected = true; + problemReporter.unmatchedBracket(rightPositions[kind][i], referenceContext, compilationUnit.compilationResult); + } + if (anomaliesDetected) + return true; + } + + return anomaliesDetected; + } catch (ArrayStoreException e) { // jdk1.2.2 jit bug + return anomaliesDetected; + } catch (NullPointerException e) { // jdk1.2.2 jit bug + return anomaliesDetected; + } + } + public final 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 astStack. */ + + if ((modifiers & flag) != 0) { // duplicate modifier + modifiers |= AccAlternateModifierProblem; + } + modifiers |= flag; + + if (modifiersSourceStart < 0) + modifiersSourceStart = scanner.startPosition; + } + public void checkAnnotation() { + + boolean deprecated = false; + boolean checkDeprecated = false; + int lastAnnotationIndex = -1; + + //since jdk1.2 look only in the last java doc comment... + found : for (lastAnnotationIndex = scanner.commentPtr; lastAnnotationIndex >= 0; lastAnnotationIndex--) { + //look for @deprecated into the first javadoc comment preceeding the declaration + int commentSourceStart = scanner.commentStarts[lastAnnotationIndex]; + // javadoc only (non javadoc comment have negative end positions.) + if (modifiersSourceStart != -1 && modifiersSourceStart < commentSourceStart) { + continue; + } + if (scanner.commentStops[lastAnnotationIndex] < 0) { + break found; + } + checkDeprecated = true; + int commentSourceEnd = scanner.commentStops[lastAnnotationIndex] - 1; //stop is one over + char[] comment = scanner.source; + + for (int i = commentSourceStart + 3; i < commentSourceEnd - 10; i++) { + if ((comment[i] == '@') + && (comment[i + 1] == 'd') + && (comment[i + 2] == 'e') + && (comment[i + 3] == 'p') + && (comment[i + 4] == 'r') + && (comment[i + 5] == 'e') + && (comment[i + 6] == 'c') + && (comment[i + 7] == 'a') + && (comment[i + 8] == 't') + && (comment[i + 9] == 'e') + && (comment[i + 10] == 'd')) { + // ensure the tag is properly ended: either followed by a space, a tab, line end or asterisk. + int nextPos = i + 11; + deprecated = + (comment[nextPos] == ' ') + || (comment[nextPos] == '\t') + || (comment[nextPos] == '\n') + || (comment[nextPos] == '\r') + || (comment[nextPos] == '*'); + break found; + } + } + break found; + } + if (deprecated) { + checkAndSetModifiers(AccDeprecated); + } + // modify the modifier source start to point at the first comment + if (lastAnnotationIndex >= 0 && checkDeprecated) { + modifiersSourceStart = scanner.commentStarts[lastAnnotationIndex]; + } + } + protected void classInstanceCreation(boolean alwaysQualified) { + // 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; + int length; + if (((length = astLengthStack[astLengthPtr--]) == 1) && (astStack[astPtr] == null)) { + //NO ClassBody + astPtr--; + if (alwaysQualified) { + alloc = new QualifiedAllocationExpression(); + } else { + alloc = new AllocationExpression(); + } + alloc.sourceEnd = endPosition; //the position has been stored explicitly + + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, alloc.arguments = new Expression[length], 0, length); + } + alloc.type = getTypeReference(0); + //the default constructor with the correct number of argument + //will be created and added by the TC (see createsInternalConstructorWithBinding) + alloc.sourceStart = intStack[intPtr--]; + pushOnExpressionStack(alloc); + } else { + dispatchDeclarationInto(length); + AnonymousLocalTypeDeclaration anonymousTypeDeclaration = (AnonymousLocalTypeDeclaration) astStack[astPtr]; + anonymousTypeDeclaration.declarationSourceEnd = endStatementPosition; + anonymousTypeDeclaration.bodyEnd = endStatementPosition; + if (anonymousTypeDeclaration.allocation != null) { + anonymousTypeDeclaration.allocation.sourceEnd = endStatementPosition; + } + astPtr--; + astLengthPtr--; + + // mark fields and initializer with local type mark if needed + markFieldsWithLocalType(anonymousTypeDeclaration); + } + } + protected final void concatExpressionLists() { + expressionLengthStack[--expressionLengthPtr]++; + } + private final void concatNodeLists() { + /* + * This is a case where you have two sublists into the astStack that you want + * to merge in one list. There is no action required on the 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 astStack. + * Look at the InterfaceMemberDeclarations for an example. + */ + + astLengthStack[astLengthPtr - 1] += astLengthStack[astLengthPtr--]; + } + protected void consumeAllocationHeader() { + // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt + + // ClassBodyopt produces a null item on the astStak if it produces NO class body + // An empty class body produces a 0 on the length stack..... + + if (currentElement == null) { + return; // should never occur, this consumeRule is only used in recovery mode + } + if (currentToken == TokenNameLBRACE) { + // beginning of an anonymous type + AnonymousLocalTypeDeclaration anonymousType = new AnonymousLocalTypeDeclaration(this.compilationUnit.compilationResult); + anonymousType.sourceStart = intStack[intPtr--]; + anonymousType.sourceEnd = rParenPos; // closing parenthesis + lastCheckPoint = anonymousType.bodyStart = scanner.currentPosition; + currentElement = currentElement.add(anonymousType, 0); + lastIgnoredToken = -1; + currentToken = 0; // opening brace already taken into account + return; + } + lastCheckPoint = scanner.startPosition; // force to restart at this exact position + restartRecovery = true; // request to restart from here on + } + protected void consumeArgumentList() { + // ArgumentList ::= ArgumentList ',' Expression + concatExpressionLists(); + } + protected void consumeArrayAccess(boolean unspecifiedReference) { + // ArrayAccess ::= Name '[' Expression ']' ==> true + // ArrayAccess ::= PrimaryNoNewArray '[' Expression ']' ==> false + + //optimize push/pop + Expression exp; + if (unspecifiedReference) { + exp = expressionStack[expressionPtr] = new ArrayReference(getUnspecifiedReferenceOptimized(), expressionStack[expressionPtr]); + } else { + expressionPtr--; + expressionLengthPtr--; + exp = expressionStack[expressionPtr] = new ArrayReference(expressionStack[expressionPtr], expressionStack[expressionPtr + 1]); + } + exp.sourceEnd = endPosition; + } + protected void consumeArrayCreationExpression() { + // ArrayCreationExpression ::= 'new' PrimitiveType DimWithOrWithOutExprs ArrayInitializeropt + // ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimWithOrWithOutExprs ArrayInitializeropt + + int length; + ArrayAllocationExpression aae = new ArrayAllocationExpression(); + if (expressionLengthStack[expressionLengthPtr] != 0) { + expressionLengthPtr--; + aae.initializer = (ArrayInitializer) expressionStack[expressionPtr--]; + } else { + expressionLengthPtr--; + } + + aae.type = getTypeReference(0); + length = (expressionLengthStack[expressionLengthPtr--]); + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, aae.dimensions = new Expression[length], 0, length); + aae.sourceStart = intStack[intPtr--]; + if (aae.initializer == null) { + aae.sourceEnd = endPosition; + } else { + aae.sourceEnd = aae.initializer.sourceEnd; + } + pushOnExpressionStack(aae); + } + protected void consumeArrayInitializer() { + // ArrayInitializer ::= '{' VariableInitializers '}' + // ArrayInitializer ::= '{' VariableInitializers , '}' + + arrayInitializer(expressionLengthStack[expressionLengthPtr--]); + } + + protected void consumeAssertStatement() { + // AssertStatement ::= 'assert' Expression ':' Expression ';' + expressionLengthPtr -= 2; + pushOnAstStack(new AssertStatement(expressionStack[expressionPtr--], expressionStack[expressionPtr--], intStack[intPtr--])); + } + + protected void consumeAssignment() { + // Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression + //optimize the push/pop + + int op = intStack[intPtr--]; //<--the encoded operator + + expressionPtr--; + expressionLengthPtr--; + expressionStack[expressionPtr] = + (op != EQUAL) + ? new CompoundAssignment(expressionStack[expressionPtr], expressionStack[expressionPtr + 1], op, scanner.startPosition - 1) + : new Assignment(expressionStack[expressionPtr], expressionStack[expressionPtr + 1], scanner.startPosition - 1); + } + protected void consumeAssignmentOperator(int pos) { + // AssignmentOperator ::= '=' + // AssignmentOperator ::= '*=' + // AssignmentOperator ::= '/=' + // AssignmentOperator ::= '%=' + // AssignmentOperator ::= '+=' + // AssignmentOperator ::= '-=' + // AssignmentOperator ::= '<<=' + // AssignmentOperator ::= '>>=' + // AssignmentOperator ::= '>>>=' + // AssignmentOperator ::= '&=' + // AssignmentOperator ::= '^=' + // AssignmentOperator ::= '|=' + + try { + intStack[++intPtr] = pos; + } catch (IndexOutOfBoundsException e) { + //intPtr is correct + int oldStackLength = intStack.length; + int oldStack[] = intStack; + intStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, intStack, 0, oldStackLength); + intStack[intPtr] = 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 + + expressionPtr--; + expressionLengthPtr--; + if (op == OR_OR) { + expressionStack[expressionPtr] = new OR_OR_Expression(expressionStack[expressionPtr], expressionStack[expressionPtr + 1], op); + } else { + if (op == AND_AND) { + expressionStack[expressionPtr] = + new AND_AND_Expression(expressionStack[expressionPtr], expressionStack[expressionPtr + 1], op); + } else { + // look for "string1" + "string2" + if ((op == PLUS) && optimizeStringLiterals) { + Expression expr1, expr2; + expr1 = expressionStack[expressionPtr]; + expr2 = expressionStack[expressionPtr + 1]; + if (expr1 instanceof StringLiteral) { + if (expr2 instanceof CharLiteral) { // string+char + expressionStack[expressionPtr] = ((StringLiteral) expr1).extendWith((CharLiteral) expr2); + } else if (expr2 instanceof StringLiteral) { //string+string + expressionStack[expressionPtr] = ((StringLiteral) expr1).extendWith((StringLiteral) expr2); + } else { + expressionStack[expressionPtr] = new BinaryExpression(expr1, expr2, PLUS); + } + } else { + expressionStack[expressionPtr] = new BinaryExpression(expr1, expr2, PLUS); + } + } else { + expressionStack[expressionPtr] = + new BinaryExpression(expressionStack[expressionPtr], expressionStack[expressionPtr + 1], op); + } + } + } + } + protected void consumeBlock() { + // Block ::= OpenBlock '{' BlockStatementsopt '}' + // simpler action for empty blocks + + int length; + if ((length = astLengthStack[astLengthPtr--]) == 0) { // empty block + pushOnAstStack(Block.EmptyWith(intStack[intPtr--], endStatementPosition)); + realBlockPtr--; // still need to pop the block variable counter + } else { + Block bk = new Block(realBlockStack[realBlockPtr--]); + astPtr -= length; + System.arraycopy(astStack, astPtr + 1, bk.statements = new Statement[length], 0, length); + pushOnAstStack(bk); + bk.sourceStart = intStack[intPtr--]; + bk.sourceEnd = endStatementPosition; + } + } + protected void consumeBlockStatements() { + // BlockStatements ::= BlockStatements BlockStatement + concatNodeLists(); + } + protected void consumeCaseLabel() { + // SwitchLabel ::= 'case' ConstantExpression ':' + expressionLengthPtr--; + pushOnAstStack(new Case(intStack[intPtr--], expressionStack[expressionPtr--])); + } + protected void consumeCastExpression() { + // CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN UnaryExpression + // CastExpression ::= PushLPAREN Name Dims PushRPAREN UnaryExpressionNotPlusMinus + + //intStack : posOfLeftParen dim posOfRightParen + + //optimize the push/pop + + Expression exp, cast, castType; + int end = intStack[intPtr--]; + expressionStack[expressionPtr] = + cast = new CastExpression(exp = expressionStack[expressionPtr], castType = getTypeReference(intStack[intPtr--])); + castType.sourceEnd = end - 1; + castType.sourceStart = (cast.sourceStart = intStack[intPtr--]) + 1; + cast.sourceEnd = exp.sourceEnd; + } + protected void consumeCastExpressionLL1() { + //CastExpression ::= '(' Expression ')' UnaryExpressionNotPlusMinus + // Expression is used in order to make the grammar LL1 + + //optimize push/pop + + Expression castType, cast, exp; + expressionPtr--; + expressionStack[expressionPtr] = + cast = + new CastExpression(exp = expressionStack[expressionPtr + 1], castType = getTypeReference(expressionStack[expressionPtr])); + expressionLengthPtr--; + updateSourcePosition(castType); + cast.sourceStart = castType.sourceStart; + cast.sourceEnd = exp.sourceEnd; + castType.sourceStart++; + castType.sourceEnd--; + } + protected void consumeCatches() { + // Catches ::= Catches CatchClause + optimizedConcatNodeLists(); + } + protected void consumeCatchHeader() { + // CatchDeclaration ::= 'catch' '(' FormalParameter ')' '{' + + if (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 (!(currentElement instanceof RecoveredBlock)) { + return; + } + // exception argument is already on astStack + ((RecoveredBlock) currentElement).attach(new RecoveredLocalVariable((Argument) astStack[astPtr--], currentElement, 0)); + // insert catch variable in catch block + lastCheckPoint = scanner.startPosition; // force to restart at this exact position + restartRecovery = true; // request to restart from here on + lastIgnoredToken = -1; + } + protected void consumeClassBodyDeclaration() { + // ClassBodyDeclaration ::= Diet Block + //push an Initializer + //optimize the push/pop + nestedMethod[nestedType]--; + Initializer initializer = new Initializer((Block) astStack[astPtr], 0); + intPtr--; // pop sourcestart left on the stack by consumeNestedMethod. + realBlockPtr--; // pop the block variable counter left on the stack by consumeNestedMethod + int javadocCommentStart = intStack[intPtr--]; + if (javadocCommentStart != -1) { + initializer.declarationSourceStart = javadocCommentStart; + } + astStack[astPtr] = initializer; + initializer.sourceEnd = endStatementPosition; + initializer.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + } + protected void consumeClassBodyDeclarations() { + // ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration + concatNodeLists(); + } + protected void consumeClassBodyDeclarationsopt() { + // ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations + nestedType--; + } + protected void consumeClassBodyopt() { + // ClassBodyopt ::= $empty + pushOnAstStack(null); + endPosition = scanner.startPosition - 1; + } + protected void consumeClassDeclaration() { + // ClassDeclaration ::= ClassHeader ClassBody + + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + //there are length declarations + //dispatch according to the type of the declarations + dispatchDeclarationInto(length); + } + + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + + // mark fields and initializer with local type mark if needed + markFieldsWithLocalType(typeDecl); + + //convert constructor that do not have the type's name into methods + boolean hasConstructor = typeDecl.checkConstructors(this); + + //add the default constructor when needed (interface don't have it) + if (!hasConstructor) { + boolean insideFieldInitializer = false; + if (diet) { + for (int i = nestedType; i > 0; i--) { + if (variablesCounter[i] > 0) { + insideFieldInitializer = true; + break; + } + } + } + typeDecl.createsInternalConstructor(!diet || insideFieldInitializer, true); + } + + //always add (will be remove at code gen time if empty) + if (this.scanner.containsAssertKeyword) { + typeDecl.bits |= AstNode.AddAssertionMASK; + } + typeDecl.addClinit(); + typeDecl.bodyEnd = endStatementPosition; + typeDecl.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + } + protected void consumeClassHeader() { + // ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt + + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + if (currentToken == TokenNameLBRACE) { + typeDecl.bodyStart = scanner.currentPosition; + } + if (currentElement != null) { + restartRecovery = true; // used to avoid branching back into the regular automaton + } + // flush the comments related to the class header + scanner.commentPtr = -1; + } + protected void consumeClassHeaderExtends() { + // ClassHeaderExtends ::= 'extends' ClassType + // There is a class declaration on the top of stack + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + //superclass + typeDecl.superclass = getTypeReference(0); + typeDecl.bodyStart = typeDecl.superclass.sourceEnd + 1; + // recovery + if (currentElement != null) { + lastCheckPoint = typeDecl.bodyStart; + } + } + protected void consumeClassHeaderImplements() { + // ClassHeaderImplements ::= 'implements' InterfaceTypeList + int length = astLengthStack[astLengthPtr--]; + //super interfaces + astPtr -= length; + // There is a class declaration on the top of stack + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + System.arraycopy(astStack, astPtr + 1, typeDecl.superInterfaces = new TypeReference[length], 0, length); + typeDecl.bodyStart = typeDecl.superInterfaces[length - 1].sourceEnd + 1; + listLength = 0; // reset after having read super-interfaces + // recovery + if (currentElement != null) { // is recovering + lastCheckPoint = typeDecl.bodyStart; + } + } + protected void consumeClassHeaderName() { + // ClassHeaderName ::= Modifiersopt 'class' 'Identifier' + TypeDeclaration typeDecl; + if (nestedMethod[nestedType] == 0) { + if (nestedType != 0) { + typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult); + } else { + typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); + } + } else { + // Record that the block has a declaration for local types + typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult); + markCurrentMethodWithLocalType(); + blockReal(); + } + + //highlight the name of the type + long pos = identifierPositionStack[identifierPtr]; + typeDecl.sourceEnd = (int) pos; + typeDecl.sourceStart = (int) (pos >>> 32); + typeDecl.name = identifierStack[identifierPtr--]; + identifierLengthPtr--; + + //compute the declaration source too + // 'class' and 'interface' push two int positions: the beginning of the class token and its end. + // we want to keep the beginning position but get rid of the end position + // it is only used for the ClassLiteralAccess positions. + typeDecl.declarationSourceStart = intStack[intPtr--]; + intPtr--; // remove the end position of the class token + + typeDecl.modifiersSourceStart = intStack[intPtr--]; + typeDecl.modifiers = intStack[intPtr--]; + if (typeDecl.modifiersSourceStart >= 0) { + typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart; + } + typeDecl.bodyStart = typeDecl.sourceEnd + 1; + pushOnAstStack(typeDecl); + + listLength = 0; // will be updated when reading super-interfaces + // recovery + if (currentElement != null) { + lastCheckPoint = typeDecl.bodyStart; + currentElement = currentElement.add(typeDecl, 0); + lastIgnoredToken = -1; + } + } + protected void consumeClassInstanceCreationExpression() { + // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt + classInstanceCreation(false); + } + protected void consumeClassInstanceCreationExpressionName() { + // ClassInstanceCreationExpressionName ::= Name '.' + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); + } + protected void consumeClassInstanceCreationExpressionQualified() { + // ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt + // ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt + + classInstanceCreation(true); // <-- push the Qualifed.... + + expressionLengthPtr--; + QualifiedAllocationExpression qae = (QualifiedAllocationExpression) expressionStack[expressionPtr--]; + qae.enclosingInstance = expressionStack[expressionPtr]; + expressionStack[expressionPtr] = qae; + qae.sourceStart = qae.enclosingInstance.sourceStart; + } + protected void consumeClassTypeElt() { + // ClassTypeElt ::= ClassType + pushOnAstStack(getTypeReference(0)); + /* if incomplete thrown exception list, listLength counter will not have been reset, + indicating that some items are available on the stack */ + listLength++; + } + protected void consumeClassTypeList() { + // ClassTypeList ::= ClassTypeList ',' ClassTypeElt + optimizedConcatNodeLists(); + } + protected void consumeCompilationUnit() { + // CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt + // do nothing by default + } + protected void consumeConditionalExpression(int op) { + // ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression + //optimize the push/pop + + expressionPtr -= 2; + expressionLengthPtr -= 2; + expressionStack[expressionPtr] = + new ConditionalExpression( + expressionStack[expressionPtr], + expressionStack[expressionPtr + 1], + expressionStack[expressionPtr + 2]); + } + protected void consumeConstructorBlockStatements() { + // ConstructorBody ::= NestedMethod '{' ExplicitConstructorInvocation BlockStatements '}' + concatNodeLists(); // explictly add the first statement into the list of statements + } + protected void consumeConstructorBody() { + // ConstructorBody ::= NestedMethod '{' BlockStatementsopt '}' + // ConstructorBody ::= NestedMethod '{' ExplicitConstructorInvocation '}' + nestedMethod[nestedType]--; + } + protected void consumeConstructorDeclaration() { + // ConstructorDeclaration ::= ConstructorHeader ConstructorBody + + /* + astStack : MethodDeclaration statements + identifierStack : name + ==> + astStack : MethodDeclaration + identifierStack : + */ + + //must provide a default constructor call when needed + + int length; + + // pop the position of the { (body of the method) pushed in block decl + intPtr--; + + //statements + realBlockPtr--; + ExplicitConstructorCall constructorCall = null; + Statement[] statements = null; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + astPtr -= length; + if (astStack[astPtr + 1] instanceof ExplicitConstructorCall) { + //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? + System.arraycopy(astStack, astPtr + 2, statements = new Statement[length - 1], 0, length - 1); + constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1]; + } else { //need to add explicitly the super(); + System.arraycopy(astStack, astPtr + 1, statements = new Statement[length], 0, length); + constructorCall = SuperReference.implicitSuperConstructorCall(); + } + } else { + if (!diet) { + // add it only in non-diet mode, if diet_bodies, then constructor call will be added elsewhere. + constructorCall = SuperReference.implicitSuperConstructorCall(); + } + } + + // now we know that the top of stack is a constructorDeclaration + ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; + cd.constructorCall = constructorCall; + cd.statements = statements; + + //highlight of the implicit call on the method name + if (constructorCall != null && cd.constructorCall.sourceEnd == 0) { + cd.constructorCall.sourceEnd = cd.sourceEnd; + cd.constructorCall.sourceStart = cd.sourceStart; + } + + //watch for } that could be given as a unicode ! ( u007D is '}' ) + // store the endPosition (position just before the '}') in case there is + // a trailing comment behind the end of the method + cd.bodyEnd = endPosition; + cd.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + } + + protected void consumeInvalidConstructorDeclaration() { + // ConstructorDeclaration ::= ConstructorHeader ';' + // now we know that the top of stack is a constructorDeclaration + ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; + + cd.bodyEnd = endPosition; // position just before the trailing semi-colon + cd.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + // report the problem and continue the parsing - narrowing the problem onto the method + } + protected void consumeConstructorHeader() { + // ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters MethodHeaderThrowsClauseopt + + AbstractMethodDeclaration method = (AbstractMethodDeclaration) astStack[astPtr]; + + if (currentToken == TokenNameLBRACE) { + method.bodyStart = scanner.currentPosition; + } + // recovery + if (currentElement != null) { + restartRecovery = true; // used to avoid branching back into the regular automaton + } + } + protected void consumeConstructorHeaderName() { + + /* recovering - might be an empty message send */ + if (currentElement != null) { + if (lastIgnoredToken == TokenNamenew) { // was an allocation expression + lastCheckPoint = scanner.startPosition; // force to restart at this exact position + restartRecovery = true; + return; + } + } + + // ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' + ConstructorDeclaration cd = new ConstructorDeclaration(this.compilationUnit.compilationResult); + + //name -- this is not really revelant but we do ..... + cd.selector = identifierStack[identifierPtr]; + long selectorSource = identifierPositionStack[identifierPtr--]; + identifierLengthPtr--; + + //modifiers + cd.declarationSourceStart = intStack[intPtr--]; + cd.modifiers = intStack[intPtr--]; + + //highlight starts at the selector starts + cd.sourceStart = (int) (selectorSource >>> 32); + pushOnAstStack(cd); + cd.sourceEnd = lParenPos; + cd.bodyStart = lParenPos + 1; + listLength = 0; // initialize listLength before reading parameters/throws + + // recovery + if (currentElement != null) { + lastCheckPoint = cd.bodyStart; + if ((currentElement instanceof RecoveredType && lastIgnoredToken != TokenNameDOT) || cd.modifiers != 0) { + currentElement = currentElement.add(cd, 0); + lastIgnoredToken = -1; + } + } + } + protected void consumeDefaultLabel() { + // SwitchLabel ::= 'default' ':' + pushOnAstStack(new DefaultCase(intStack[intPtr--], intStack[intPtr--])); + } + protected void consumeDefaultModifiers() { + checkAnnotation(); // might update modifiers with AccDeprecated + pushOnIntStack(modifiers); // modifiers + pushOnIntStack(modifiersSourceStart >= 0 ? modifiersSourceStart : scanner.startPosition); + resetModifiers(); + } + protected void consumeDiet() { + // Diet ::= $empty + checkAnnotation(); + pushOnIntStack(modifiersSourceStart); // push the start position of a javadoc comment if there is one + jumpOverMethodBody(); + } + protected void consumeDims() { + // Dims ::= DimsLoop + pushOnIntStack(dimensions); + dimensions = 0; + } + protected void consumeDimWithOrWithOutExpr() { + // DimWithOrWithOutExpr ::= '[' ']' + pushOnExpressionStack(null); + } + protected void consumeDimWithOrWithOutExprs() { + // DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr + concatExpressionLists(); + } + protected void consumeEmptyArgumentListopt() { + // ArgumentListopt ::= $empty + pushOnExpressionStackLengthStack(0); + } + protected void consumeEmptyArrayInitializer() { + // ArrayInitializer ::= '{' ,opt '}' + arrayInitializer(0); + } + protected void consumeEmptyArrayInitializeropt() { + // ArrayInitializeropt ::= $empty + pushOnExpressionStackLengthStack(0); + } + protected void consumeEmptyBlockStatementsopt() { + // BlockStatementsopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEmptyCatchesopt() { + // Catchesopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEmptyClassBodyDeclarationsopt() { + // ClassBodyDeclarationsopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEmptyClassMemberDeclaration() { + // ClassMemberDeclaration ::= ';' + pushOnAstLengthStack(0); + } + protected void consumeEmptyDimsopt() { + // Dimsopt ::= $empty + pushOnIntStack(0); + } + protected void consumeEmptyExpression() { + // Expressionopt ::= $empty + pushOnExpressionStackLengthStack(0); + } + protected void consumeEmptyForInitopt() { + // ForInitopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEmptyForUpdateopt() { + // ForUpdateopt ::= $empty + pushOnExpressionStackLengthStack(0); + } + protected void consumeEmptyImportDeclarationsopt() { + // ImportDeclarationsopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEmptyInterfaceMemberDeclaration() { + // InterfaceMemberDeclaration ::= ';' + pushOnAstLengthStack(0); + } + protected void consumeEmptyInterfaceMemberDeclarationsopt() { + // InterfaceMemberDeclarationsopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEmptyStatement() { + // EmptyStatement ::= ';' + if (this.scanner.source[endStatementPosition] == ';') { + pushOnAstStack(new EmptyStatement(endStatementPosition, endStatementPosition)); + } else { + // we have a Unicode for the ';' (/u003B) + pushOnAstStack(new EmptyStatement(endStatementPosition - 5, endStatementPosition)); + } + } + protected void consumeEmptySwitchBlock() { + // SwitchBlock ::= '{' '}' + pushOnAstLengthStack(0); + } + protected void consumeEmptyTypeDeclaration() { + // TypeDeclaration ::= ';' + pushOnAstLengthStack(0); + } + protected void consumeEmptyTypeDeclarationsopt() { + // TypeDeclarationsopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeEnterAnonymousClassBody() { + // EnterAnonymousClassBody ::= $empty + QualifiedAllocationExpression alloc; + AnonymousLocalTypeDeclaration anonymousType = new AnonymousLocalTypeDeclaration(this.compilationUnit.compilationResult); + alloc = anonymousType.allocation = new QualifiedAllocationExpression(anonymousType); + markCurrentMethodWithLocalType(); + pushOnAstStack(anonymousType); + + alloc.sourceEnd = rParenPos; //the position has been stored explicitly + int argumentLength; + if ((argumentLength = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= argumentLength; + System.arraycopy(expressionStack, expressionPtr + 1, alloc.arguments = new Expression[argumentLength], 0, argumentLength); + } + alloc.type = getTypeReference(0); + + anonymousType.sourceEnd = alloc.sourceEnd; + //position at the type while it impacts the anonymous declaration + anonymousType.sourceStart = anonymousType.declarationSourceStart = alloc.type.sourceStart; + alloc.sourceStart = intStack[intPtr--]; + pushOnExpressionStack(alloc); + + anonymousType.bodyStart = scanner.currentPosition; + listLength = 0; // will be updated when reading super-interfaces + // recovery + if (currentElement != null) { + lastCheckPoint = anonymousType.bodyStart; + // the recoveryTokenCheck will deal with the open brace + currentElement = currentElement.add(anonymousType, 0); + currentToken = 0; // opening brace already taken into account + lastIgnoredToken = -1; + } + } + protected void consumeEnterCompilationUnit() { + // EnterCompilationUnit ::= $empty + // do nothing by default + } + protected void consumeEnterVariable() { + // EnterVariable ::= $empty + // do nothing by default + + char[] name = identifierStack[identifierPtr]; + long namePosition = identifierPositionStack[identifierPtr]; + int extendedDimension = intStack[intPtr--]; + AbstractVariableDeclaration declaration; + // create the ast node + boolean isLocalDeclaration = nestedMethod[nestedType] != 0; + if (isLocalDeclaration) { + // create the local variable declarations + declaration = this.createLocalDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition); + } else { + // create the field declaration + declaration = this.createFieldDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition); + } + + identifierPtr--; + identifierLengthPtr--; + TypeReference type; + int variableIndex = variablesCounter[nestedType]; + int typeDim = 0; + if (variableIndex == 0) { + // first variable of the declaration (FieldDeclaration or LocalDeclaration) + if (isLocalDeclaration) { + declaration.declarationSourceStart = intStack[intPtr--]; + declaration.modifiers = intStack[intPtr--]; + type = getTypeReference(typeDim = intStack[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 = intStack[intPtr--]); // type dimension + pushOnAstStack(type); + declaration.declarationSourceStart = intStack[intPtr--]; + declaration.modifiers = intStack[intPtr--]; + } + } else { + type = (TypeReference) astStack[astPtr - variableIndex]; + typeDim = type.dimensions(); + AbstractVariableDeclaration previousVariable = (AbstractVariableDeclaration) astStack[astPtr]; + declaration.declarationSourceStart = previousVariable.declarationSourceStart; + declaration.modifiers = previousVariable.modifiers; + } + + if (extendedDimension == 0) { + declaration.type = type; + } else { + int dimension = typeDim + extendedDimension; + //on the identifierLengthStack there is the information about the type.... + int baseType; + if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { + //it was a baseType + int typeSourceStart = type.sourceStart; + int typeSourceEnd = type.sourceEnd; + type = TypeReference.baseTypeReference(-baseType, dimension); + type.sourceStart = typeSourceStart; + type.sourceEnd = typeSourceEnd; + declaration.type = type; + } else { + declaration.type = this.copyDims(type, dimension); + } + } + variablesCounter[nestedType]++; + pushOnAstStack(declaration); + // recovery + if (currentElement != null) { + if (!(currentElement instanceof RecoveredType) + && (currentToken == TokenNameDOT //|| declaration.modifiers != 0 + || (scanner.getLineNumber(declaration.type.sourceStart) != scanner.getLineNumber((int) (namePosition >>> 32))))) { + lastCheckPoint = (int) (namePosition >>> 32); + restartRecovery = true; + return; + } + if (isLocalDeclaration) { + LocalDeclaration localDecl = (LocalDeclaration) astStack[astPtr]; + lastCheckPoint = localDecl.sourceEnd + 1; + currentElement = currentElement.add(localDecl, 0); + } else { + FieldDeclaration fieldDecl = (FieldDeclaration) astStack[astPtr]; + lastCheckPoint = fieldDecl.sourceEnd + 1; + currentElement = currentElement.add(fieldDecl, 0); + } + lastIgnoredToken = -1; + } + } + protected void consumeEqualityExpression(int op) { + // EqualityExpression ::= EqualityExpression '==' RelationalExpression + // EqualityExpression ::= EqualityExpression '!=' RelationalExpression + + //optimize the push/pop + + expressionPtr--; + expressionLengthPtr--; + expressionStack[expressionPtr] = new EqualExpression(expressionStack[expressionPtr], expressionStack[expressionPtr + 1], op); + } + protected void consumeExitVariableWithInitialization() { + // ExitVariableWithInitialization ::= $empty + // do nothing by default + expressionLengthPtr--; + AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) astStack[astPtr]; + variableDecl.initialization = expressionStack[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; + } + protected void consumeExitVariableWithoutInitialization() { + // ExitVariableWithoutInitialization ::= $empty + // do nothing by default + } + protected void consumeExplicitConstructorInvocation(int flag, int recFlag) { + + /* flag allows to distinguish 3 cases : + (0) : + ExplicitConstructorInvocation ::= 'this' '(' ArgumentListopt ')' ';' + ExplicitConstructorInvocation ::= 'super' '(' ArgumentListopt ')' ';' + (1) : + ExplicitConstructorInvocation ::= Primary '.' 'super' '(' ArgumentListopt ')' ';' + ExplicitConstructorInvocation ::= Primary '.' 'this' '(' ArgumentListopt ')' ';' + (2) : + ExplicitConstructorInvocation ::= Name '.' 'super' '(' ArgumentListopt ')' ';' + ExplicitConstructorInvocation ::= Name '.' 'this' '(' ArgumentListopt ')' ';' + */ + int startPosition = intStack[intPtr--]; + ExplicitConstructorCall ecc = new ExplicitConstructorCall(recFlag); + int length; + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, ecc.arguments = new Expression[length], 0, length); + } + switch (flag) { + case 0 : + ecc.sourceStart = startPosition; + break; + case 1 : + expressionLengthPtr--; + ecc.sourceStart = (ecc.qualification = expressionStack[expressionPtr--]).sourceStart; + break; + case 2 : + ecc.sourceStart = (ecc.qualification = getUnspecifiedReferenceOptimized()).sourceStart; + break; }; - - public static short check_table[] = null; - public static char lhs[] = null; - public static char action[] = lhs; - private final static String FILEPREFIX = "parser"; //$NON-NLS-1$ - - static { - try{ - initTables(); - } catch(java.io.IOException ex){ - throw new ExceptionInInitializerError(ex.getMessage()); - } - } - - public static final int RoundBracket = 0; - public static final int SquareBracket = 1; - public static final int CurlyBracket = 2; - public static final int BracketKinds = 3; - -public Parser(ProblemReporter problemReporter, boolean optimizeStringLiterals, boolean assertMode) { - - this.problemReporter = problemReporter; - this.optimizeStringLiterals = optimizeStringLiterals; - this.assertMode = assertMode; - this.initializeScanner(); - astLengthStack = new int[50]; - expressionLengthStack = new int[30]; - intStack = new int[50]; - identifierStack = new char[30][]; - identifierLengthStack = new int[30]; - nestedMethod = new int[30]; - realBlockStack = new int[30]; - identifierPositionStack = new long[30]; - variablesCounter = new int[30]; -} -/** - * - * INTERNAL USE-ONLY - */ -protected void adjustInterfaceModifiers() { - intStack[intPtr - 1] |= AccInterface; -} -public final void arrayInitializer(int length) { - //length is the size of the array Initializer - //expressionPtr points on the last elt of the arrayInitializer - //i.e. it has not been decremented yet. - - ArrayInitializer ai = new ArrayInitializer(); - if (length != 0) { - expressionPtr -= length; - System.arraycopy(expressionStack, expressionPtr + 1, ai.expressions = new Expression[length], 0, length); - } - pushOnExpressionStack(ai); - //positionning - ai.sourceEnd = endStatementPosition; - int searchPosition = length == 0 ? endPosition : ai.expressions[0].sourceStart; - try { - //does not work with comments(that contain '{') nor '{' describes as a unicode.... - while (scanner.source[--searchPosition] != '{') { - } - } catch (IndexOutOfBoundsException ex) { - //should never occur (except for strange cases like whose describe above) - searchPosition = (length == 0 ? endPosition : ai.expressions[0].sourceStart) - 1; - } - ai.sourceStart = searchPosition; -} -protected static int asi(int state) { + pushOnAstStack(ecc); + ecc.sourceEnd = endPosition; + } + protected void consumeExpressionStatement() { + // ExpressionStatement ::= StatementExpression ';' + expressionLengthPtr--; + pushOnAstStack(expressionStack[expressionPtr--]); + } + protected void consumeFieldAccess(boolean isSuperAccess) { + // FieldAccess ::= Primary '.' 'Identifier' + // FieldAccess ::= 'super' '.' 'Identifier' + + FieldReference fr = new FieldReference(identifierStack[identifierPtr], identifierPositionStack[identifierPtr--]); + identifierLengthPtr--; + if (isSuperAccess) { + //considerates the fieldReference beginning at the 'super' .... + fr.sourceStart = intStack[intPtr--]; + fr.receiver = new SuperReference(fr.sourceStart, endPosition); + pushOnExpressionStack(fr); + } else { + //optimize push/pop + if ((fr.receiver = expressionStack[expressionPtr]).isThis()) { + //fieldreference begins at the this + fr.sourceStart = fr.receiver.sourceStart; + } + expressionStack[expressionPtr] = fr; + } + } + protected void consumeFieldDeclaration() { + // See consumeLocalVariableDeclarationDefaultModifier() in case of change: duplicated code + // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' + + /* + astStack : + expressionStack: Expression Expression ...... Expression + identifierStack : type identifier identifier ...... identifier + intStack : typeDim dim dim dim + ==> + astStack : FieldDeclaration FieldDeclaration ...... FieldDeclaration + expressionStack : + identifierStack : + intStack : + + */ + int variableDeclaratorsCounter = astLengthStack[astLengthPtr]; + + for (int i = variableDeclaratorsCounter - 1; i >= 0; i--) { + FieldDeclaration fieldDeclaration = (FieldDeclaration) astStack[astPtr - i]; + fieldDeclaration.declarationSourceEnd = endStatementPosition; + fieldDeclaration.declarationEnd = endStatementPosition; // semi-colon included + } + updateSourceDeclarationParts(variableDeclaratorsCounter); + int endPos = flushAnnotationsDefinedPriorTo(endStatementPosition); + if (endPos != endStatementPosition) { + for (int i = 0; i < variableDeclaratorsCounter; i++) { + FieldDeclaration fieldDeclaration = (FieldDeclaration) astStack[astPtr - i]; + fieldDeclaration.declarationSourceEnd = endPos; + } + } + // update the astStack, astPtr and astLengthStack + int startIndex = astPtr - variablesCounter[nestedType] + 1; + System.arraycopy(astStack, startIndex, astStack, startIndex - 1, variableDeclaratorsCounter); + astPtr--; // remove the type reference + astLengthStack[--astLengthPtr] = variableDeclaratorsCounter; + + // recovery + if (currentElement != null) { + lastCheckPoint = endPos + 1; + if (currentElement.parent != null && currentElement instanceof RecoveredField) { + currentElement = currentElement.parent; + } + restartRecovery = true; + } + variablesCounter[nestedType] = 0; + } + protected void consumeForceNoDiet() { + // ForceNoDiet ::= $empty + dietInt++; + } + protected void consumeForInit() { + // ForInit ::= StatementExpressionList + pushOnAstLengthStack(-1); + } + protected void consumeFormalParameter() { + // FormalParameter ::= Type VariableDeclaratorId ==> false + // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true + /* + astStack : + identifierStack : type identifier + intStack : dim dim + ==> + astStack : Argument + identifierStack : + intStack : + */ + + identifierLengthPtr--; + char[] name = identifierStack[identifierPtr]; + long namePositions = identifierPositionStack[identifierPtr--]; + TypeReference type = getTypeReference(intStack[intPtr--] + intStack[intPtr--]); + int modifierPositions = intStack[intPtr--]; + intPtr--; + Argument arg = new Argument(name, namePositions, type, intStack[intPtr + 1] & ~AccDeprecated); // modifiers + arg.declarationSourceStart = modifierPositions; + pushOnAstStack(arg); + + /* if incomplete method header, listLength counter will not have been reset, + indicating that some arguments are available on the stack */ + listLength++; + } + protected void consumeFormalParameterList() { + // FormalParameterList ::= FormalParameterList ',' FormalParameter + optimizedConcatNodeLists(); + } + protected void consumeFormalParameterListopt() { + // FormalParameterListopt ::= $empty + pushOnAstLengthStack(0); + } + protected void consumeImportDeclarations() { + // ImportDeclarations ::= ImportDeclarations ImportDeclaration + optimizedConcatNodeLists(); + } + protected void consumeImportDeclarationsopt() { + // ImportDeclarationsopt ::= ImportDeclarations + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + astPtr -= length; + System.arraycopy(astStack, astPtr + 1, compilationUnit.imports = new ImportReference[length], 0, length); + } + } + protected void consumeInstanceOfExpression(int op) { + // RelationalExpression ::= RelationalExpression 'instanceof' ReferenceType + //optimize the push/pop + + //by construction, no base type may be used in getTypeReference + Expression exp; + expressionStack[expressionPtr] = + exp = new InstanceOfExpression(expressionStack[expressionPtr], getTypeReference(intStack[intPtr--]), op); + if (exp.sourceEnd == 0) { + //array on base type.... + exp.sourceEnd = scanner.startPosition - 1; + } + //the scanner is on the next token already.... + } + protected void consumeInterfaceDeclaration() { + // see consumeClassDeclaration in case of changes: duplicated code + // InterfaceDeclaration ::= InterfaceHeader InterfaceBody + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + //there are length declarations + //dispatch.....according to the type of the declarations + dispatchDeclarationInto(length); + } + + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + + // mark fields and initializer with local type mark if needed + markFieldsWithLocalType(typeDecl); + + //convert constructor that do not have the type's name into methods + typeDecl.checkConstructors(this); + + //always add (will be remove at code gen time if empty) + if (this.scanner.containsAssertKeyword) { + typeDecl.bits |= AstNode.AddAssertionMASK; + } + typeDecl.addClinit(); + typeDecl.bodyEnd = endStatementPosition; + typeDecl.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + } + protected void consumeInterfaceHeader() { + // InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt + + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + if (currentToken == TokenNameLBRACE) { + typeDecl.bodyStart = scanner.currentPosition; + } + if (currentElement != null) { + restartRecovery = true; // used to avoid branching back into the regular automaton + } + // flush the comments related to the interface header + scanner.commentPtr = -1; + } + protected void consumeInterfaceHeaderExtends() { + // InterfaceHeaderExtends ::= 'extends' InterfaceTypeList + int length = astLengthStack[astLengthPtr--]; + //super interfaces + astPtr -= length; + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + System.arraycopy(astStack, astPtr + 1, typeDecl.superInterfaces = new TypeReference[length], 0, length); + typeDecl.bodyStart = typeDecl.superInterfaces[length - 1].sourceEnd + 1; + listLength = 0; // reset after having read super-interfaces + // recovery + if (currentElement != null) { + lastCheckPoint = typeDecl.bodyStart; + } + } + protected void consumeInterfaceHeaderName() { + // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier' + TypeDeclaration typeDecl; + if (nestedMethod[nestedType] == 0) { + if (nestedType != 0) { + typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult); + } else { + typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); + } + } else { + // Record that the block has a declaration for local types + typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult); + markCurrentMethodWithLocalType(); + blockReal(); + } + + //highlight the name of the type + long pos = identifierPositionStack[identifierPtr]; + typeDecl.sourceEnd = (int) pos; + typeDecl.sourceStart = (int) (pos >>> 32); + typeDecl.name = identifierStack[identifierPtr--]; + identifierLengthPtr--; + + //compute the declaration source too + // 'class' and 'interface' push two int positions: the beginning of the class token and its end. + // we want to keep the beginning position but get rid of the end position + // it is only used for the ClassLiteralAccess positions. + typeDecl.declarationSourceStart = intStack[intPtr--]; + intPtr--; // remove the end position of the class token + typeDecl.modifiersSourceStart = intStack[intPtr--]; + typeDecl.modifiers = intStack[intPtr--]; + if (typeDecl.modifiersSourceStart >= 0) { + typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart; + } + typeDecl.bodyStart = typeDecl.sourceEnd + 1; + pushOnAstStack(typeDecl); + listLength = 0; // will be updated when reading super-interfaces + // recovery + if (currentElement != null) { // is recovering + lastCheckPoint = typeDecl.bodyStart; + currentElement = currentElement.add(typeDecl, 0); + lastIgnoredToken = -1; + } + } + protected void consumeInterfaceMemberDeclarations() { + // InterfaceMemberDeclarations ::= InterfaceMemberDeclarations InterfaceMemberDeclaration + concatNodeLists(); + } + protected void consumeInterfaceMemberDeclarationsopt() { + // InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations + nestedType--; + } + protected void consumeInterfaceType() { + // InterfaceType ::= ClassOrInterfaceType + pushOnAstStack(getTypeReference(0)); + /* if incomplete type header, listLength counter will not have been reset, + indicating that some interfaces are available on the stack */ + listLength++; + } + protected void consumeInterfaceTypeList() { + // InterfaceTypeList ::= InterfaceTypeList ',' InterfaceType + optimizedConcatNodeLists(); + } + protected void consumeLeftHandSide() { + // LeftHandSide ::= Name + + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); + } + protected void consumeLeftParen() { + // PushLPAREN ::= '(' + pushOnIntStack(lParenPos); + } + protected void consumeLocalVariableDeclaration() { + // LocalVariableDeclaration ::= Modifiers Type VariableDeclarators ';' + + /* + astStack : + expressionStack: Expression Expression ...... Expression + identifierStack : type identifier identifier ...... identifier + intStack : typeDim dim dim dim + ==> + astStack : FieldDeclaration FieldDeclaration ...... FieldDeclaration + expressionStack : + identifierStack : + intStack : + + */ + int variableDeclaratorsCounter = astLengthStack[astLengthPtr]; + + // update the astStack, astPtr and astLengthStack + int startIndex = astPtr - variablesCounter[nestedType] + 1; + System.arraycopy(astStack, startIndex, astStack, startIndex - 1, variableDeclaratorsCounter); + astPtr--; // remove the type reference + astLengthStack[--astLengthPtr] = variableDeclaratorsCounter; + variablesCounter[nestedType] = 0; + } + protected void consumeLocalVariableDeclarationStatement() { + // LocalVariableDeclarationStatement ::= LocalVariableDeclaration ';' + // see blockReal in case of change: duplicated code + // increment the amount of declared variables for this block + realBlockStack[realBlockPtr]++; + } + protected void consumeMethodBody() { + // MethodBody ::= NestedMethod '{' BlockStatementsopt '}' + nestedMethod[nestedType]--; + } + protected void consumeMethodDeclaration(boolean isNotAbstract) { + // MethodDeclaration ::= MethodHeader MethodBody + // AbstractMethodDeclaration ::= MethodHeader ';' + + /* + astStack : modifiers arguments throws statements + identifierStack : type name + intStack : dim dim dim + ==> + astStack : MethodDeclaration + identifierStack : + intStack : + */ + + int length; + if (isNotAbstract) { + // pop the position of the { (body of the method) pushed in block decl + intPtr--; + } + + int explicitDeclarations = 0; + Statement[] statements = null; + if (isNotAbstract) { + //statements + explicitDeclarations = realBlockStack[realBlockPtr--]; + if ((length = astLengthStack[astLengthPtr--]) != 0) + System.arraycopy(astStack, (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) astStack[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 |= AccSemicolonBody; + } + // store the endPosition (position just before the '}') in case there is + // a trailing comment behind the end of the method + md.bodyEnd = endPosition; + md.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + } + protected void consumeMethodHeader() { + // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt + // retrieve end position of method declarator + AbstractMethodDeclaration method = (AbstractMethodDeclaration) astStack[astPtr]; + + if (currentToken == TokenNameLBRACE) { + method.bodyStart = scanner.currentPosition; + } + // recovery + if (currentElement != null) { + if (currentToken == TokenNameSEMICOLON) { + method.modifiers |= AccSemicolonBody; + method.declarationSourceEnd = scanner.currentPosition - 1; + method.bodyEnd = scanner.currentPosition - 1; + if (currentElement.parent != null) { + currentElement = currentElement.parent; + } + } + restartRecovery = true; // used to avoid branching back into the regular automaton + } + } + protected void consumeMethodHeaderExtendedDims() { + // MethodHeaderExtendedDims ::= Dimsopt + // now we update the returnType of the method + MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; + int extendedDims = intStack[intPtr--]; + if (extendedDims != 0) { + TypeReference returnType = md.returnType; + md.sourceEnd = endPosition; + int dims = returnType.dimensions() + extendedDims; + int baseType; + if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { + //it was a baseType + int sourceStart = returnType.sourceStart; + int sourceEnd = returnType.sourceEnd; + returnType = TypeReference.baseTypeReference(-baseType, dims); + returnType.sourceStart = sourceStart; + returnType.sourceEnd = sourceEnd; + md.returnType = returnType; + } else { + md.returnType = this.copyDims(md.returnType, dims); + } + if (currentToken == TokenNameLBRACE) { + md.bodyStart = endPosition + 1; + } + // recovery + if (currentElement != null) { + lastCheckPoint = md.bodyStart; + } + } + } + protected void consumeMethodHeaderName() { + // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + MethodDeclaration md = new MethodDeclaration(this.compilationUnit.compilationResult); + + //name + md.selector = identifierStack[identifierPtr]; + long selectorSource = identifierPositionStack[identifierPtr--]; + identifierLengthPtr--; + //type + md.returnType = getTypeReference(intStack[intPtr--]); + //modifiers + md.declarationSourceStart = intStack[intPtr--]; + md.modifiers = intStack[intPtr--]; + + //highlight starts at selector start + md.sourceStart = (int) (selectorSource >>> 32); + pushOnAstStack(md); + md.sourceEnd = lParenPos; + md.bodyStart = lParenPos + 1; + listLength = 0; // initialize listLength before reading parameters/throws + + // recovery + if (currentElement != null) { + if (currentElement instanceof RecoveredType //|| md.modifiers != 0 + || (scanner.getLineNumber(md.returnType.sourceStart) == scanner.getLineNumber(md.sourceStart))) { + lastCheckPoint = md.bodyStart; + currentElement = currentElement.add(md, 0); + lastIgnoredToken = -1; + } else { + lastCheckPoint = md.sourceStart; + restartRecovery = true; + } + } + } + protected void consumeMethodHeaderParameters() { + // MethodHeaderParameters ::= FormalParameterListopt ')' + int length = astLengthStack[astLengthPtr--]; + astPtr -= length; + AbstractMethodDeclaration md = (AbstractMethodDeclaration) astStack[astPtr]; + md.sourceEnd = rParenPos; + //arguments + if (length != 0) { + System.arraycopy(astStack, astPtr + 1, md.arguments = new Argument[length], 0, length); + } + md.bodyStart = rParenPos + 1; + listLength = 0; // reset listLength after having read all parameters + // recovery + if (currentElement != null) { + lastCheckPoint = md.bodyStart; + if (currentElement.parseTree() == md) + return; + + // might not have been attached yet - in some constructor scenarii + if (md.isConstructor()) { + if ((length != 0) || (currentToken == TokenNameLBRACE) // || (currentToken == TokenNamethrows) + ) { + currentElement = currentElement.add(md, 0); + lastIgnoredToken = -1; + } + } + } + } + protected void consumeMethodHeaderThrowsClause() { + // MethodHeaderThrowsClause ::= 'throws' ClassTypeList + int length = astLengthStack[astLengthPtr--]; + astPtr -= length; + AbstractMethodDeclaration md = (AbstractMethodDeclaration) astStack[astPtr]; + System.arraycopy(astStack, astPtr + 1, md.thrownExceptions = new TypeReference[length], 0, length); + md.sourceEnd = md.thrownExceptions[length - 1].sourceEnd; + md.bodyStart = md.thrownExceptions[length - 1].sourceEnd + 1; + listLength = 0; // reset listLength after having read all thrown exceptions + // recovery + if (currentElement != null) { + lastCheckPoint = md.bodyStart; + } + } + protected void consumeMethodInvocationName() { + // MethodInvocation ::= Name '(' ArgumentListopt ')' + + // when the name is only an identifier...we have a message send to "this" (implicit) + + MessageSend m = newMessageSend(); + m.sourceEnd = rParenPos; + m.sourceStart = (int) ((m.nameSourcePosition = identifierPositionStack[identifierPtr]) >>> 32); + m.selector = identifierStack[identifierPtr--]; + if (identifierLengthStack[identifierLengthPtr] == 1) { + m.receiver = ThisReference.ThisImplicit; + identifierLengthPtr--; + } else { + identifierLengthStack[identifierLengthPtr]--; + m.receiver = getUnspecifiedReference(); + m.sourceStart = m.receiver.sourceStart; + } + pushOnExpressionStack(m); + } + protected void consumeMethodInvocationPrimary() { + //optimize the push/pop + //MethodInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' + + MessageSend m = newMessageSend(); + m.sourceStart = (int) ((m.nameSourcePosition = identifierPositionStack[identifierPtr]) >>> 32); + m.selector = identifierStack[identifierPtr--]; + identifierLengthPtr--; + m.receiver = expressionStack[expressionPtr]; + m.sourceStart = m.receiver.sourceStart; + m.sourceEnd = rParenPos; + expressionStack[expressionPtr] = m; + } + protected void consumeMethodInvocationSuper() { + // MethodInvocation ::= 'super' '.' 'Identifier' '(' ArgumentListopt ')' + + MessageSend m = newMessageSend(); + m.sourceStart = intStack[intPtr--]; + m.sourceEnd = rParenPos; + m.nameSourcePosition = identifierPositionStack[identifierPtr]; + m.selector = identifierStack[identifierPtr--]; + identifierLengthPtr--; + m.receiver = new SuperReference(m.sourceStart, endPosition); + pushOnExpressionStack(m); + } + protected void consumeMethodPushModifiersHeaderName() { + // MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers 'Identifier' '(' + // MethodPushModifiersHeaderName ::= Type PushModifiers 'Identifier' '(' + MethodDeclaration md = new MethodDeclaration(this.compilationUnit.compilationResult); + + //name + md.selector = identifierStack[identifierPtr]; + long selectorSource = identifierPositionStack[identifierPtr--]; + identifierLengthPtr--; + + //modifiers + md.declarationSourceStart = intStack[intPtr--]; + md.modifiers = intStack[intPtr--]; + + //type + md.returnType = getTypeReference(intStack[intPtr--]); + + //highlight starts at selector start + md.sourceStart = (int) (selectorSource >>> 32); + pushOnAstStack(md); + md.sourceEnd = lParenPos; + md.bodyStart = lParenPos + 1; + listLength = 0; // initialize listLength before reading parameters/throws + + // recovery + if (currentElement != null) { + lastCheckPoint = md.bodyStart; + currentElement = currentElement.add(md, 0); + lastIgnoredToken = -1; + } + } + protected void consumeModifiers() { + int savedModifiersSourceStart = modifiersSourceStart; + checkAnnotation(); // might update modifiers with AccDeprecated + pushOnIntStack(modifiers); // modifiers + if (modifiersSourceStart >= savedModifiersSourceStart) { + modifiersSourceStart = savedModifiersSourceStart; + } + pushOnIntStack(modifiersSourceStart); + resetModifiers(); + } + protected void consumeNestedMethod() { + // NestedMethod ::= $empty + jumpOverMethodBody(); + nestedMethod[nestedType]++; + consumeOpenBlock(); + } + protected void consumeNestedType() { + // NestedType ::= $empty + nestedType++; + try { + nestedMethod[nestedType] = 0; + } catch (IndexOutOfBoundsException e) { + //except in test's cases, it should never raise + int oldL = nestedMethod.length; + System.arraycopy(nestedMethod, 0, (nestedMethod = new int[oldL + 30]), 0, oldL); + nestedMethod[nestedType] = 0; + // increase the size of the fieldsCounter as well. It has to be consistent with the size of the nestedMethod collection + System.arraycopy(variablesCounter, 0, (variablesCounter = new int[oldL + 30]), 0, oldL); + } + variablesCounter[nestedType] = 0; + } + protected void consumeOneDimLoop() { + // OneDimLoop ::= '[' ']' + dimensions++; + } + protected void consumeOnlySynchronized() { + // OnlySynchronized ::= 'synchronized' + pushOnIntStack(this.synchronizedBlockSourceStart); + resetModifiers(); + } + protected void consumeOpenBlock() { + // OpenBlock ::= $empty + + pushOnIntStack(scanner.startPosition); + try { + realBlockStack[++realBlockPtr] = 0; + } catch (IndexOutOfBoundsException e) { + //realBlockPtr is correct + int oldStackLength = realBlockStack.length; + int oldStack[] = realBlockStack; + realBlockStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, realBlockStack, 0, oldStackLength); + realBlockStack[realBlockPtr] = 0; + } + } + protected void consumePackageDeclaration() { + // PackageDeclaration ::= 'package' Name ';' + /* build an ImportRef build from the last name + stored in the identifier stack. */ + + ImportReference impt = compilationUnit.currentPackage; + // flush annotations defined prior to import statements + impt.declarationEnd = endStatementPosition; + impt.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(impt.declarationSourceEnd); + } + protected void consumePackageDeclarationName() { + // PackageDeclarationName ::= 'package' Name + /* build an ImportRef build from the last name + stored in the identifier stack. */ + + ImportReference impt; + int length; + char[][] tokens = new char[length = identifierLengthStack[identifierLengthPtr--]][]; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy(identifierStack, ++identifierPtr, tokens, 0, length); + System.arraycopy(identifierPositionStack, identifierPtr--, positions, 0, length); + compilationUnit.currentPackage = impt = new ImportReference(tokens, positions, true); + + if (currentToken == TokenNameSEMICOLON) { + impt.declarationSourceEnd = scanner.currentPosition - 1; + } else { + impt.declarationSourceEnd = impt.sourceEnd; + } + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = intStack[intPtr--]; + + // recovery + if (currentElement != null) { + lastCheckPoint = impt.declarationSourceEnd + 1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } + } + protected void consumePostfixExpression() { + // PostfixExpression ::= Name + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); + } + protected void consumePrimaryNoNewArray() { + // PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN + updateSourcePosition(expressionStack[expressionPtr]); + } + protected void consumePrimaryNoNewArrayArrayType() { + // PrimaryNoNewArray ::= ArrayType '.' 'class' + intPtr--; + pushOnExpressionStack(new ClassLiteralAccess(intStack[intPtr--], getTypeReference(intStack[intPtr--]))); + } + protected void consumePrimaryNoNewArrayName() { + // PrimaryNoNewArray ::= Name '.' 'class' + intPtr--; + pushOnExpressionStack(new ClassLiteralAccess(intStack[intPtr--], getTypeReference(0))); + } + protected void consumePrimaryNoNewArrayNameSuper() { + // PrimaryNoNewArray ::= Name '.' 'super' + pushOnExpressionStack(new QualifiedSuperReference(getTypeReference(0), intStack[intPtr--], endPosition)); + } + protected void consumePrimaryNoNewArrayNameThis() { + // PrimaryNoNewArray ::= Name '.' 'this' + pushOnExpressionStack(new QualifiedThisReference(getTypeReference(0), intStack[intPtr--], endPosition)); + } + protected void consumePrimaryNoNewArrayPrimitiveType() { + // PrimaryNoNewArray ::= PrimitiveType '.' 'class' + intPtr--; + pushOnExpressionStack(new ClassLiteralAccess(intStack[intPtr--], getTypeReference(0))); + } + protected void consumePrimaryNoNewArrayThis() { + // PrimaryNoNewArray ::= 'this' + pushOnExpressionStack(new ThisReference(intStack[intPtr--], endPosition)); + } + protected void consumePrimitiveType() { + // Type ::= PrimitiveType + pushOnIntStack(0); + } + protected void consumePushModifiers() { + if ((modifiers & AccSynchronized) != 0) { + /* remove the starting position of the synchronized keyword + * we don't need it when synchronized is part of the modifiers + */ + intPtr--; + } + pushOnIntStack(modifiers); // modifiers + pushOnIntStack(modifiersSourceStart); + resetModifiers(); + } + protected void consumePushPosition() { + // for source managment purpose + // PushPosition ::= $empty + pushOnIntStack(endPosition); + } + protected void consumeQualifiedName() { + // QualifiedName ::= Name '.' SimpleName + /*back from the recursive loop of QualifiedName. + Updates identifier length into the length stack*/ + + identifierLengthStack[--identifierLengthPtr]++; + } + protected void consumeReferenceType() { + // ReferenceType ::= ClassOrInterfaceType + pushOnIntStack(0); + } + protected void consumeRestoreDiet() { + // RestoreDiet ::= $empty + dietInt--; + } + protected void consumeRightParen() { + // PushRPAREN ::= ')' + pushOnIntStack(rParenPos); + } + // This method is part of an automatic generation : do NOT edit-modify + // This method is part of an automatic generation : do NOT edit-modify + protected void consumeRule(int act) { + switch (act) { + case 29 : // System.out.println("Type ::= PrimitiveType"); + consumePrimitiveType(); + break; + + case 43 : // System.out.println("ReferenceType ::= ClassOrInterfaceType"); + consumeReferenceType(); + break; + + case 52 : // System.out.println("QualifiedName ::= Name DOT SimpleName"); + consumeQualifiedName(); + break; + + case 53 : // System.out.println("CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt"); + consumeCompilationUnit(); + break; + + case 54 : // System.out.println("EnterCompilationUnit ::="); + consumeEnterCompilationUnit(); + break; + + case 66 : // System.out.println("CatchHeader ::= catch LPAREN FormalParameter RPAREN LBRACE"); + consumeCatchHeader(); + break; + + case 68 : // System.out.println("ImportDeclarations ::= ImportDeclarations ImportDeclaration"); + consumeImportDeclarations(); + break; + + case 70 : // System.out.println("TypeDeclarations ::= TypeDeclarations TypeDeclaration"); + consumeTypeDeclarations(); + break; + + case 71 : // System.out.println("PackageDeclaration ::= PackageDeclarationName SEMICOLON"); + consumePackageDeclaration(); + break; + + case 72 : // System.out.println("PackageDeclarationName ::= package Name"); + consumePackageDeclarationName(); + break; + + case 75 : // System.out.println("SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName SEMICOLON"); + consumeSingleTypeImportDeclaration(); + break; + + case 76 : // System.out.println("SingleTypeImportDeclarationName ::= import Name"); + consumeSingleTypeImportDeclarationName(); + break; + + case 77 : // System.out.println("TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName SEMICOLON"); + consumeTypeImportOnDemandDeclaration(); + break; + + case 78 : // System.out.println("TypeImportOnDemandDeclarationName ::= import Name DOT MULTIPLY"); + consumeTypeImportOnDemandDeclarationName(); + break; + + case 81 : // System.out.println("TypeDeclaration ::= SEMICOLON"); + consumeEmptyTypeDeclaration(); + break; + + case 95 : // System.out.println("ClassDeclaration ::= ClassHeader ClassBody"); + consumeClassDeclaration(); + break; + + case 96 : // System.out.println("ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt"); + consumeClassHeader(); + break; + + case 97 : // System.out.println("ClassHeaderName ::= Modifiersopt class Identifier"); + consumeClassHeaderName(); + break; + + case 98 : // System.out.println("ClassHeaderExtends ::= extends ClassType"); + consumeClassHeaderExtends(); + break; + + case 99 : // System.out.println("ClassHeaderImplements ::= implements InterfaceTypeList"); + consumeClassHeaderImplements(); + break; + + case 101 : // System.out.println("InterfaceTypeList ::= InterfaceTypeList COMMA InterfaceType"); + consumeInterfaceTypeList(); + break; + + case 102 : // System.out.println("InterfaceType ::= ClassOrInterfaceType"); + consumeInterfaceType(); + break; + + case 105 : // System.out.println("ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration"); + consumeClassBodyDeclarations(); + break; + + case 109 : // System.out.println("ClassBodyDeclaration ::= Diet NestedMethod Block"); + consumeClassBodyDeclaration(); + break; + + case 110 : // System.out.println("Diet ::="); + consumeDiet(); + break; + + case 111 : // System.out.println("Initializer ::= Diet NestedMethod Block"); + consumeClassBodyDeclaration(); + break; - return asb[original_state(state)]; -} -protected void blockReal() { - // See consumeLocalVariableDeclarationStatement in case of change: duplicated code - // increment the amount of declared variables for this block - realBlockStack[realBlockPtr]++; -} -private final static void buildFileFor(String filename, String tag, String[] tokens, boolean isShort) throws java.io.IOException { - - //transform the String tokens into chars before dumping then into file - - int i = 0; - //read upto the tag - while (!tokens[i++].equals(tag)) {} - //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); - if (isShort) - c += 32768; - chars[ic++] = (char) c; - } - - //resize - System.arraycopy(chars, 0, chars = new char[ic], 0, ic); - - buildFileForTable(filename, chars); -} -private final static void buildFileForTable(String filename, char[] chars) throws java.io.IOException { - - 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 = new java.io.FileOutputStream(filename); - stream.write(bytes); - stream.close(); - System.out.println(filename + " creation complete"); //$NON-NLS-1$ -} -public final static void buildFilesFromLPG(String dataFilename) throws java.io.IOException { - - //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.jdt.internal.compiler.parser.Parser.buildFilesFromLPG("d:/leapfrog/grammar/javadcl.java")] - - char[] contents = new char[] {}; - try { - contents = Util.getFileCharContent(new File(dataFilename), null); - } catch (IOException ex) { - System.out.println(Util.bind("parser.incorrectPath")); //$NON-NLS-1$ - 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 i = 0; - while (st.hasMoreTokens()) { - tokens[i++] = st.nextToken(); - } - final String prefix = FILEPREFIX; - i = 0; - buildFileFor(prefix + (++i) + ".rsc", "lhs", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileFor(prefix + (++i) + ".rsc", "check_table", tokens, true); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileFor(prefix + (++i) + ".rsc", "asb", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileFor(prefix + (++i) + ".rsc", "asr", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileFor(prefix + (++i) + ".rsc", "symbol_index", tokens, false); //$NON-NLS-2$ //$NON-NLS-1$ - System.out.println(Util.bind("parser.moveFiles")); //$NON-NLS-1$ -} -/* - * 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 - */ - lastCheckPoint = 0; - - RecoveredElement element = null; - if (referenceContext instanceof CompilationUnitDeclaration){ - element = new RecoveredUnit(compilationUnit, 0, this); - - /* ignore current stack state, since restarting from the beginnning - since could not trust simple brace count */ - if (true){ // experimenting restart recovery from scratch - compilationUnit.currentPackage = null; - compilationUnit.imports = null; - compilationUnit.types = null; - currentToken = 0; - listLength = 0; - return element; - } - if (compilationUnit.currentPackage != null){ - lastCheckPoint = compilationUnit.currentPackage.declarationSourceEnd+1; - } - if (compilationUnit.imports != null){ - lastCheckPoint = compilationUnit.imports[compilationUnit.imports.length -1].declarationSourceEnd+1; - } - } else { - if (referenceContext instanceof AbstractMethodDeclaration){ - element = new RecoveredMethod((AbstractMethodDeclaration) referenceContext, null, 0, this); - lastCheckPoint = ((AbstractMethodDeclaration) referenceContext).bodyStart; - } else { - /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */ - if (referenceContext instanceof TypeDeclaration){ - TypeDeclaration type = (TypeDeclaration) referenceContext; - for (int i = 0; i < type.fields.length; i++){ - FieldDeclaration field = type.fields[i]; - if (!field.isField() - && field.declarationSourceStart <= scanner.initialPosition - && scanner.initialPosition <= field.declarationSourceEnd - && scanner.eofPosition <= field.declarationSourceEnd+1){ - element = new RecoveredInitializer((Initializer) field, null, 1, this); - lastCheckPoint = field.declarationSourceStart; - break; - } - } - } - } - } - - if (element == null) return element; - - for(int i = 0; i <= astPtr; i++){ - AstNode node = astStack[i]; - if (node instanceof AbstractMethodDeclaration){ - AbstractMethodDeclaration method = (AbstractMethodDeclaration) node; - if (method.declarationSourceEnd == 0){ - element = element.add(method, 0); - lastCheckPoint = method.bodyStart; - } else { - element = element.add(method, 0); - lastCheckPoint = method.declarationSourceEnd + 1; - } - continue; - } - if (node instanceof Initializer){ - Initializer initializer = (Initializer) node; - if (initializer.declarationSourceEnd == 0){ - element = element.add(initializer, 1); - lastCheckPoint = initializer.bodyStart; - } else { - element = element.add(initializer, 0); - lastCheckPoint = initializer.declarationSourceEnd + 1; - } - continue; - } - if (node instanceof FieldDeclaration){ - FieldDeclaration field = (FieldDeclaration) node; - if (field.declarationSourceEnd == 0){ - element = element.add(field, 0); - if (field.initialization == null){ - lastCheckPoint = field.sourceEnd + 1; - } else { - lastCheckPoint = field.initialization.sourceEnd + 1; - } - } else { - element = element.add(field, 0); - lastCheckPoint = field.declarationSourceEnd + 1; - } - continue; - } - if (node instanceof TypeDeclaration){ - TypeDeclaration type = (TypeDeclaration) node; - if (type.declarationSourceEnd == 0){ - element = element.add(type, 0); - lastCheckPoint = type.bodyStart; - } else { - element = element.add(type, 0); - lastCheckPoint = type.declarationSourceEnd + 1; - } - continue; - } - if (node instanceof ImportReference){ - ImportReference importRef = (ImportReference) node; - element = element.add(importRef, 0); - lastCheckPoint = importRef.declarationSourceEnd + 1; - } - } - return element; -} -protected static short check(int i) { - return check_table[i - (NUM_RULES + 1)]; -} -/* - * Reconsider the entire source looking for inconsistencies in {} () [] - */ -public boolean checkAndReportBracketAnomalies(ProblemReporter problemReporter) { - - scanner.wasAcr = false; - boolean anomaliesDetected = false; - try { - char[] source = scanner.source; - int[] leftCount = {0, 0, 0}; - int[] rightCount = {0, 0, 0}; - int[] depths = {0, 0, 0}; - int[][] leftPositions = new int[][] {new int[10], new int[10], new int[10]}; - int[][] leftDepths = new int[][] {new int[10], new int[10], new int[10]}; - int[][] rightPositions = new int[][] {new int[10], new int[10], new int[10]}; - int[][] rightDepths = new int[][] {new int[10], new int[10], new int[10]}; - scanner.currentPosition = scanner.initialPosition; //starting point (first-zero-based char) - while (scanner.currentPosition < scanner.eofPosition) { //loop for jumping over comments - try { - // ---------Consume white space and handles startPosition--------- - boolean isWhiteSpace; - do { - scanner.startPosition = scanner.currentPosition; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - isWhiteSpace = scanner.jumpOverUnicodeWhiteSpace(); - } else { - if (scanner.recordLineSeparator && ((scanner.currentCharacter == '\r') || (scanner.currentCharacter == '\n'))) { - if (scanner.lineEnds[scanner.linePtr] < scanner.startPosition) { - // only record line positions we have not recorded yet - scanner.pushLineSeparator(); - } - } - isWhiteSpace = Character.isWhitespace(scanner.currentCharacter); - } - } while (isWhiteSpace && (scanner.currentPosition < scanner.eofPosition)); - - // -------consume token until } is found--------- - - switch (scanner.currentCharacter) { - case '{' : - { - int index = leftCount[CurlyBracket] ++; - if (index == leftPositions[CurlyBracket].length) { - System.arraycopy(leftPositions[CurlyBracket], 0, (leftPositions[CurlyBracket] = new int[index * 2]), 0, index); - System.arraycopy(leftDepths[CurlyBracket], 0, (leftDepths[CurlyBracket] = new int[index * 2]), 0, index); - } - leftPositions[CurlyBracket][index] = scanner.startPosition; - leftDepths[CurlyBracket][index] = depths[CurlyBracket] ++; - } - break; - case '}' : - { - int index = rightCount[CurlyBracket] ++; - if (index == rightPositions[CurlyBracket].length) { - System.arraycopy(rightPositions[CurlyBracket], 0, (rightPositions[CurlyBracket] = new int[index * 2]), 0, index); - System.arraycopy(rightDepths[CurlyBracket], 0, (rightDepths[CurlyBracket] = new int[index * 2]), 0, index); - } - rightPositions[CurlyBracket][index] = scanner.startPosition; - rightDepths[CurlyBracket][index] = --depths[CurlyBracket]; - } - break; - case '(' : - { - int index = leftCount[RoundBracket] ++; - if (index == leftPositions[RoundBracket].length) { - System.arraycopy(leftPositions[RoundBracket], 0, (leftPositions[RoundBracket] = new int[index * 2]), 0, index); - System.arraycopy(leftDepths[RoundBracket], 0, (leftDepths[RoundBracket] = new int[index * 2]), 0, index); - } - leftPositions[RoundBracket][index] = scanner.startPosition; - leftDepths[RoundBracket][index] = depths[RoundBracket] ++; - } - break; - case ')' : - { - int index = rightCount[RoundBracket] ++; - if (index == rightPositions[RoundBracket].length) { - System.arraycopy(rightPositions[RoundBracket], 0, (rightPositions[RoundBracket] = new int[index * 2]), 0, index); - System.arraycopy(rightDepths[RoundBracket], 0, (rightDepths[RoundBracket] = new int[index * 2]), 0, index); - } - rightPositions[RoundBracket][index] = scanner.startPosition; - rightDepths[RoundBracket][index] = --depths[RoundBracket]; - } - break; - case '[' : - { - int index = leftCount[SquareBracket] ++; - if (index == leftPositions[SquareBracket].length) { - System.arraycopy(leftPositions[SquareBracket], 0, (leftPositions[SquareBracket] = new int[index * 2]), 0, index); - System.arraycopy(leftDepths[SquareBracket], 0, (leftDepths[SquareBracket] = new int[index * 2]), 0, index); - } - leftPositions[SquareBracket][index] = scanner.startPosition; - leftDepths[SquareBracket][index] = depths[SquareBracket] ++; - } - break; - case ']' : - { - int index = rightCount[SquareBracket] ++; - if (index == rightPositions[SquareBracket].length) { - System.arraycopy(rightPositions[SquareBracket], 0, (rightPositions[SquareBracket] = new int[index * 2]), 0, index); - System.arraycopy(rightDepths[SquareBracket], 0, (rightDepths[SquareBracket] = new int[index * 2]), 0, index); - } - rightPositions[SquareBracket][index] = scanner.startPosition; - rightDepths[SquareBracket][index] = --depths[SquareBracket]; - } - break; - case '\'' : - { - if (scanner.getNextChar('\\')) { - scanner.scanEscapeCharacter(); - } else { // consume next character - scanner.unicodeAsBackSlash = false; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - scanner.getNextUnicodeChar(); - } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; - } - } - } - scanner.getNextChar('\''); - break; - } - case '"' : // consume next character - scanner.unicodeAsBackSlash = false; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - scanner.getNextUnicodeChar(); - } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; - } - } - while (scanner.currentCharacter != '"') { - if (scanner.currentCharacter == '\r') { - if (source[scanner.currentPosition] == '\n') - scanner.currentPosition++; - break; // the string cannot go further that the line - } - if (scanner.currentCharacter == '\n') { - break; // the string cannot go further that the line - } - if (scanner.currentCharacter == '\\') { - scanner.scanEscapeCharacter(); - } - // consume next character - scanner.unicodeAsBackSlash = false; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - scanner.getNextUnicodeChar(); - } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; - } - } - } - break; - case '/' : - { - int test; - if ((test = scanner.getNextChar('/', '*')) == 0) { //line comment - //get the next char - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - //-------------unicode traitement ------------ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - scanner.currentPosition++; - while (source[scanner.currentPosition] == 'u') { - scanner.currentPosition++; - } - if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error don't care of the value - scanner.currentCharacter = 'A'; - } //something different from \n and \r - else { - scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - } - while (scanner.currentCharacter != '\r' && scanner.currentCharacter != '\n') { - //get the next char - scanner.startPosition = scanner.currentPosition; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - //-------------unicode traitement ------------ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - scanner.currentPosition++; - while (source[scanner.currentPosition] == 'u') { - scanner.currentPosition++; - } - if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error don't care of the value - scanner.currentCharacter = 'A'; - } //something different from \n and \r - else { - scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - } - } - if (scanner.recordLineSeparator && ((scanner.currentCharacter == '\r') || (scanner.currentCharacter == '\n'))) { - if (scanner.lineEnds[scanner.linePtr] < scanner.startPosition) { - // only record line positions we have not recorded yet - scanner.pushLineSeparator(); - } - } - break; - } - if (test > 0) { //traditional and annotation comment - boolean star = false; - // consume next character - scanner.unicodeAsBackSlash = false; - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - scanner.getNextUnicodeChar(); - } else { - if (scanner.withoutUnicodePtr != 0) { - scanner.withoutUnicodeBuffer[++scanner.withoutUnicodePtr] = scanner.currentCharacter; - } - } - if (scanner.currentCharacter == '*') { - star = true; - } - //get the next char - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - //-------------unicode traitement ------------ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - scanner.currentPosition++; - while (source[scanner.currentPosition] == 'u') { - scanner.currentPosition++; - } - if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error don't care of the value - scanner.currentCharacter = 'A'; - } //something different from * and / - else { - scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - } - //loop until end of comment */ - while ((scanner.currentCharacter != '/') || (!star)) { - star = scanner.currentCharacter == '*'; - //get next char - if (((scanner.currentCharacter = source[scanner.currentPosition++]) == '\\') && (source[scanner.currentPosition] == 'u')) { - //-------------unicode traitement ------------ - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - scanner.currentPosition++; - while (source[scanner.currentPosition] == 'u') { - scanner.currentPosition++; - } - if ((c1 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c1 < 0 || (c2 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c2 < 0 || (c3 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c3 < 0 || (c4 = Character.getNumericValue(source[scanner.currentPosition++])) > 15 || c4 < 0) { //error don't care of the value - scanner.currentCharacter = 'A'; - } //something different from * and / - else { - scanner.currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - } - } - break; - } - break; - } - default : - if (Character.isJavaIdentifierStart(scanner.currentCharacter)) { - scanner.scanIdentifierOrKeyword(); - break; - } - if (Character.isDigit(scanner.currentCharacter)) { - scanner.scanNumber(false); - break; - } - } - //-----------------end switch while try-------------------- - } catch (IndexOutOfBoundsException e) { - break; // read until EOF - } catch (InvalidInputException e) { - return false; // no clue - } - } - if (scanner.recordLineSeparator) { - compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); - } - - // check placement anomalies against other kinds of brackets - for (int kind = 0; kind < BracketKinds; kind++) { - for (int leftIndex = leftCount[kind] - 1; leftIndex >= 0; leftIndex--) { - int start = leftPositions[kind][leftIndex]; // deepest first - // find matching closing bracket - int depth = leftDepths[kind][leftIndex]; - int end = -1; - for (int i = 0; i < rightCount[kind]; i++) { - int pos = rightPositions[kind][i]; - // want matching bracket further in source with same depth - if ((pos > start) && (depth == rightDepths[kind][i])) { - end = pos; - break; - } - } - if (end < 0) { // did not find a good closing match - problemReporter.unmatchedBracket(start, referenceContext, compilationUnit.compilationResult); - return true; - } - // check if even number of opening/closing other brackets in between this pair of brackets - int balance = 0; - for (int otherKind = 0;(balance == 0) && (otherKind < BracketKinds); otherKind++) { - for (int i = 0; i < leftCount[otherKind]; i++) { - int pos = leftPositions[otherKind][i]; - if ((pos > start) && (pos < end)) - balance++; - } - for (int i = 0; i < rightCount[otherKind]; i++) { - int pos = rightPositions[otherKind][i]; - if ((pos > start) && (pos < end)) - balance--; - } - if (balance != 0) { - problemReporter.unmatchedBracket(start, referenceContext, compilationUnit.compilationResult); //bracket anomaly - return true; - } - } - } - // too many opening brackets ? - for (int i = rightCount[kind]; i < leftCount[kind]; i++) { - anomaliesDetected = true; - problemReporter.unmatchedBracket(leftPositions[kind][leftCount[kind] - i - 1], referenceContext, compilationUnit.compilationResult); - } - // too many closing brackets ? - for (int i = leftCount[kind]; i < rightCount[kind]; i++) { - anomaliesDetected = true; - problemReporter.unmatchedBracket(rightPositions[kind][i], referenceContext, compilationUnit.compilationResult); - } - if (anomaliesDetected) return true; - } - - return anomaliesDetected; - } catch (ArrayStoreException e) { // jdk1.2.2 jit bug - return anomaliesDetected; - } catch (NullPointerException e) { // jdk1.2.2 jit bug - return anomaliesDetected; - } -} -public final 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 astStack. */ - - if ((modifiers & flag) != 0){ // duplicate modifier - modifiers |= AccAlternateModifierProblem; - } - modifiers |= flag; - - if (modifiersSourceStart < 0) modifiersSourceStart = scanner.startPosition; -} -public void checkAnnotation() { - - boolean deprecated = false; - boolean checkDeprecated = false; - int lastAnnotationIndex = -1; - - //since jdk1.2 look only in the last java doc comment... - found : for (lastAnnotationIndex = scanner.commentPtr; lastAnnotationIndex >= 0; lastAnnotationIndex--){ - //look for @deprecated into the first javadoc comment preceeding the declaration - int commentSourceStart = scanner.commentStarts[lastAnnotationIndex]; - // javadoc only (non javadoc comment have negative end positions.) - if (modifiersSourceStart != -1 && modifiersSourceStart < commentSourceStart) { - continue; - } - if (scanner.commentStops[lastAnnotationIndex] < 0) { - break found; - } - checkDeprecated = true; - int commentSourceEnd = scanner.commentStops[lastAnnotationIndex] - 1; //stop is one over - char[] comment = scanner.source; - - for (int i = commentSourceStart + 3; i < commentSourceEnd - 10; i++) { - if ((comment[i] == '@') - && (comment[i + 1] == 'd') - && (comment[i + 2] == 'e') - && (comment[i + 3] == 'p') - && (comment[i + 4] == 'r') - && (comment[i + 5] == 'e') - && (comment[i + 6] == 'c') - && (comment[i + 7] == 'a') - && (comment[i + 8] == 't') - && (comment[i + 9] == 'e') - && (comment[i + 10] == 'd')) { - // ensure the tag is properly ended: either followed by a space, a tab, line end or asterisk. - int nextPos = i+11; - deprecated = (comment[nextPos] == ' ') || (comment[nextPos] == '\t') || (comment[nextPos] == '\n') || (comment[nextPos] == '\r') || (comment[nextPos] == '*'); - break found; - } - } - break found; - } - if (deprecated) { - checkAndSetModifiers(AccDeprecated); - } - // modify the modifier source start to point at the first comment - if (lastAnnotationIndex >= 0 && checkDeprecated) { - modifiersSourceStart = scanner.commentStarts[lastAnnotationIndex]; - } -} -protected void classInstanceCreation(boolean alwaysQualified) { - // 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; - int length; - if (((length = astLengthStack[astLengthPtr--]) == 1) - && (astStack[astPtr] == null)) { - //NO ClassBody - astPtr--; - if (alwaysQualified) { - alloc = new QualifiedAllocationExpression(); - } else { - alloc = new AllocationExpression(); - } - alloc.sourceEnd = endPosition; //the position has been stored explicitly - - if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { - expressionPtr -= length; - System.arraycopy( - expressionStack, - expressionPtr + 1, - alloc.arguments = new Expression[length], - 0, - length); - } - alloc.type = getTypeReference(0); - //the default constructor with the correct number of argument - //will be created and added by the TC (see createsInternalConstructorWithBinding) - alloc.sourceStart = intStack[intPtr--]; - pushOnExpressionStack(alloc); - } else { - dispatchDeclarationInto(length); - AnonymousLocalTypeDeclaration anonymousTypeDeclaration = (AnonymousLocalTypeDeclaration) astStack[astPtr]; - anonymousTypeDeclaration.declarationSourceEnd = endStatementPosition; - anonymousTypeDeclaration.bodyEnd = endStatementPosition; - if (anonymousTypeDeclaration.allocation != null) { - anonymousTypeDeclaration.allocation.sourceEnd = endStatementPosition; - } - astPtr--; - astLengthPtr--; - - // mark fields and initializer with local type mark if needed - markFieldsWithLocalType(anonymousTypeDeclaration); - } -} -protected final void concatExpressionLists() { - expressionLengthStack[--expressionLengthPtr]++; -} -private final void concatNodeLists() { - /* - * This is a case where you have two sublists into the astStack that you want - * to merge in one list. There is no action required on the 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 astStack. - * Look at the InterfaceMemberDeclarations for an example. - */ - - astLengthStack[astLengthPtr - 1] += astLengthStack[astLengthPtr--]; -} -protected void consumeAllocationHeader() { - // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt - - // ClassBodyopt produces a null item on the astStak if it produces NO class body - // An empty class body produces a 0 on the length stack..... - - if (currentElement == null){ - return; // should never occur, this consumeRule is only used in recovery mode - } - if (currentToken == TokenNameLBRACE){ - // beginning of an anonymous type - AnonymousLocalTypeDeclaration anonymousType = new AnonymousLocalTypeDeclaration(this.compilationUnit.compilationResult); - anonymousType.sourceStart = intStack[intPtr--]; - anonymousType.sourceEnd = rParenPos; // closing parenthesis - lastCheckPoint = anonymousType.bodyStart = scanner.currentPosition; - currentElement = currentElement.add(anonymousType, 0); - lastIgnoredToken = -1; - currentToken = 0; // opening brace already taken into account - return; - } - lastCheckPoint = scanner.startPosition; // force to restart at this exact position - restartRecovery = true; // request to restart from here on -} -protected void consumeArgumentList() { - // ArgumentList ::= ArgumentList ',' Expression - concatExpressionLists(); -} -protected void consumeArrayAccess(boolean unspecifiedReference) { - // ArrayAccess ::= Name '[' Expression ']' ==> true - // ArrayAccess ::= PrimaryNoNewArray '[' Expression ']' ==> false - - - //optimize push/pop - Expression exp; - if (unspecifiedReference) { - exp = - expressionStack[expressionPtr] = - new ArrayReference( - getUnspecifiedReferenceOptimized(), - expressionStack[expressionPtr]); - } else { - expressionPtr--; - expressionLengthPtr--; - exp = - expressionStack[expressionPtr] = - new ArrayReference( - expressionStack[expressionPtr], - expressionStack[expressionPtr + 1]); - } - exp.sourceEnd = endPosition; -} -protected void consumeArrayCreationExpression() { - // ArrayCreationExpression ::= 'new' PrimitiveType DimWithOrWithOutExprs ArrayInitializeropt - // ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimWithOrWithOutExprs ArrayInitializeropt - - int length; - ArrayAllocationExpression aae = new ArrayAllocationExpression(); - if (expressionLengthStack[expressionLengthPtr] != 0) { - expressionLengthPtr -- ; - aae.initializer = (ArrayInitializer) expressionStack[expressionPtr--]; - } else { - expressionLengthPtr--; - } - - aae.type = getTypeReference(0); - length = (expressionLengthStack[expressionLengthPtr--]); - expressionPtr -= length ; - System.arraycopy( - expressionStack, - expressionPtr+1, - aae.dimensions = new Expression[length], - 0, - length); - aae.sourceStart = intStack[intPtr--]; - if (aae.initializer == null) { - aae.sourceEnd = endPosition; - } else { - aae.sourceEnd = aae.initializer.sourceEnd ; - } - pushOnExpressionStack(aae); -} -protected void consumeArrayInitializer() { - // ArrayInitializer ::= '{' VariableInitializers '}' - // ArrayInitializer ::= '{' VariableInitializers , '}' + case 118 : // System.out.println("ClassMemberDeclaration ::= SEMICOLON"); + consumeEmptyClassMemberDeclaration(); + break; - arrayInitializer(expressionLengthStack[expressionLengthPtr--]); -} + case 119 : // System.out.println("FieldDeclaration ::= Modifiersopt Type VariableDeclarators SEMICOLON"); + consumeFieldDeclaration(); + break; -protected void consumeAssertStatement() { - // AssertStatement ::= 'assert' Expression ':' Expression ';' - expressionLengthPtr-=2; - pushOnAstStack(new AssertStatement(expressionStack[expressionPtr--], expressionStack[expressionPtr--], intStack[intPtr--])); -} + case 121 : // System.out.println("VariableDeclarators ::= VariableDeclarators COMMA VariableDeclarator"); + consumeVariableDeclarators(); + break; -protected void consumeAssignment() { - // Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression - //optimize the push/pop - - int op = intStack[intPtr--] ; //<--the encoded operator - - expressionPtr -- ; expressionLengthPtr -- ; - expressionStack[expressionPtr] = - (op != EQUAL ) ? - new CompoundAssignment( - expressionStack[expressionPtr] , - expressionStack[expressionPtr+1], - op, - scanner.startPosition - 1) : - new Assignment( - expressionStack[expressionPtr] , - expressionStack[expressionPtr+1], - scanner.startPosition - 1); -} -protected void consumeAssignmentOperator(int pos) { - // AssignmentOperator ::= '=' - // AssignmentOperator ::= '*=' - // AssignmentOperator ::= '/=' - // AssignmentOperator ::= '%=' - // AssignmentOperator ::= '+=' - // AssignmentOperator ::= '-=' - // AssignmentOperator ::= '<<=' - // AssignmentOperator ::= '>>=' - // AssignmentOperator ::= '>>>=' - // AssignmentOperator ::= '&=' - // AssignmentOperator ::= '^=' - // AssignmentOperator ::= '|=' - - try { - intStack[++intPtr] = pos; - } catch (IndexOutOfBoundsException e) { - //intPtr is correct - int oldStackLength = intStack.length; - int oldStack[] = intStack; - intStack = new int[oldStackLength + StackIncrement]; - System.arraycopy(oldStack, 0, intStack, 0, oldStackLength); - intStack[intPtr] = 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 - - expressionPtr--; - expressionLengthPtr--; - if (op == OR_OR) { - expressionStack[expressionPtr] = - new OR_OR_Expression( - expressionStack[expressionPtr], - expressionStack[expressionPtr + 1], - op); - } else { - if (op == AND_AND) { - expressionStack[expressionPtr] = - new AND_AND_Expression( - expressionStack[expressionPtr], - expressionStack[expressionPtr + 1], - op); - } else { - // look for "string1" + "string2" - if ((op == PLUS) && optimizeStringLiterals) { - Expression expr1, expr2; - expr1 = expressionStack[expressionPtr]; - expr2 = expressionStack[expressionPtr + 1]; - if (expr1 instanceof StringLiteral) { - if (expr2 instanceof CharLiteral) { // string+char - expressionStack[expressionPtr] = - ((StringLiteral) expr1).extendWith((CharLiteral) expr2); - } else if (expr2 instanceof StringLiteral) { //string+string - expressionStack[expressionPtr] = - ((StringLiteral) expr1).extendWith((StringLiteral) expr2); - } else { - expressionStack[expressionPtr] = new BinaryExpression(expr1, expr2, PLUS); - } - } else { - expressionStack[expressionPtr] = new BinaryExpression(expr1, expr2, PLUS); - } - } else { - expressionStack[expressionPtr] = - new BinaryExpression( - expressionStack[expressionPtr], - expressionStack[expressionPtr + 1], - op); - } - } - } -} -protected void consumeBlock() { - // Block ::= OpenBlock '{' BlockStatementsopt '}' - // simpler action for empty blocks - - int length; - if ((length = astLengthStack[astLengthPtr--]) == 0) { // empty block - pushOnAstStack(Block.EmptyWith(intStack[intPtr--], endStatementPosition)); - realBlockPtr--; // still need to pop the block variable counter - } else { - Block bk = new Block(realBlockStack[realBlockPtr--]); - astPtr -= length; - System.arraycopy( - astStack, - astPtr + 1, - bk.statements = new Statement[length], - 0, - length); - pushOnAstStack(bk); - bk.sourceStart = intStack[intPtr--]; - bk.sourceEnd = endStatementPosition; - } -} -protected void consumeBlockStatements() { - // BlockStatements ::= BlockStatements BlockStatement - concatNodeLists(); -} -protected void consumeCaseLabel() { - // SwitchLabel ::= 'case' ConstantExpression ':' - expressionLengthPtr--; - pushOnAstStack(new Case(intStack[intPtr--], expressionStack[expressionPtr--])); -} -protected void consumeCastExpression() { - // CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN UnaryExpression - // CastExpression ::= PushLPAREN Name Dims PushRPAREN UnaryExpressionNotPlusMinus + case 124 : // System.out.println("EnterVariable ::="); + consumeEnterVariable(); + break; - //intStack : posOfLeftParen dim posOfRightParen + case 125 : // System.out.println("ExitVariableWithInitialization ::="); + consumeExitVariableWithInitialization(); + break; - //optimize the push/pop + case 126 : // System.out.println("ExitVariableWithoutInitialization ::="); + consumeExitVariableWithoutInitialization(); + break; - Expression exp, cast, castType; - int end = intStack[intPtr--]; - expressionStack[expressionPtr] = cast = new CastExpression(exp = expressionStack[expressionPtr], castType = getTypeReference(intStack[intPtr--])); - castType.sourceEnd = end - 1; - castType.sourceStart = (cast.sourceStart = intStack[intPtr--]) + 1; - cast.sourceEnd = exp.sourceEnd; -} -protected void consumeCastExpressionLL1() { - //CastExpression ::= '(' Expression ')' UnaryExpressionNotPlusMinus - // Expression is used in order to make the grammar LL1 - - //optimize push/pop - - Expression castType,cast,exp; - expressionPtr--; - expressionStack[expressionPtr] = - cast = new CastExpression( exp=expressionStack[expressionPtr+1] , - castType = getTypeReference(expressionStack[expressionPtr])); - expressionLengthPtr -- ; - updateSourcePosition(castType); - cast.sourceStart=castType.sourceStart; - cast.sourceEnd=exp.sourceEnd; - castType.sourceStart++; - castType.sourceEnd--; - } -protected void consumeCatches() { - // Catches ::= Catches CatchClause - optimizedConcatNodeLists(); -} -protected void consumeCatchHeader() { - // CatchDeclaration ::= 'catch' '(' FormalParameter ')' '{' - - if (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 (!(currentElement instanceof RecoveredBlock)){ - return; - } - // exception argument is already on astStack - ((RecoveredBlock)currentElement).attach( - new RecoveredLocalVariable((Argument)astStack[astPtr--], currentElement, 0)); // insert catch variable in catch block - lastCheckPoint = scanner.startPosition; // force to restart at this exact position - restartRecovery = true; // request to restart from here on - lastIgnoredToken = -1; -} -protected void consumeClassBodyDeclaration() { - // ClassBodyDeclaration ::= Diet Block - //push an Initializer - //optimize the push/pop - nestedMethod[nestedType]--; - Initializer initializer = new Initializer((Block) astStack[astPtr], 0); - intPtr--; // pop sourcestart left on the stack by consumeNestedMethod. - realBlockPtr--; // pop the block variable counter left on the stack by consumeNestedMethod - int javadocCommentStart = intStack[intPtr--]; - if (javadocCommentStart != -1) { - initializer.declarationSourceStart = javadocCommentStart; - } - astStack[astPtr] = initializer; - initializer.sourceEnd = endStatementPosition; - initializer.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); -} -protected void consumeClassBodyDeclarations() { - // ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration - concatNodeLists(); -} -protected void consumeClassBodyDeclarationsopt() { - // ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations - nestedType-- ; -} -protected void consumeClassBodyopt() { - // ClassBodyopt ::= $empty - pushOnAstStack(null); - endPosition = scanner.startPosition - 1; -} -protected void consumeClassDeclaration() { - // ClassDeclaration ::= ClassHeader ClassBody - - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - //there are length declarations - //dispatch according to the type of the declarations - dispatchDeclarationInto(length); - } - - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - - // mark fields and initializer with local type mark if needed - markFieldsWithLocalType(typeDecl); - - //convert constructor that do not have the type's name into methods - boolean hasConstructor = typeDecl.checkConstructors(this); - - //add the default constructor when needed (interface don't have it) - if (!hasConstructor) { - boolean insideFieldInitializer = false; - if (diet) { - for (int i = nestedType; i > 0; i--){ - if (variablesCounter[i] > 0) { - insideFieldInitializer = true; - break; - } - } - } - typeDecl.createsInternalConstructor(!diet || insideFieldInitializer, true); - } - - //always add (will be remove at code gen time if empty) - if (this.scanner.containsAssertKeyword) { - typeDecl.bits |= AstNode.AddAssertionMASK; - } - typeDecl.addClinit(); - typeDecl.bodyEnd = endStatementPosition; - typeDecl.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); -} -protected void consumeClassHeader() { - // ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt - - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - if (currentToken == TokenNameLBRACE) { - typeDecl.bodyStart = scanner.currentPosition; - } - if (currentElement != null) { - restartRecovery = true; // used to avoid branching back into the regular automaton - } - // flush the comments related to the class header - scanner.commentPtr = -1; -} -protected void consumeClassHeaderExtends() { - // ClassHeaderExtends ::= 'extends' ClassType - // There is a class declaration on the top of stack - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - //superclass - typeDecl.superclass = getTypeReference(0); - typeDecl.bodyStart = typeDecl.superclass.sourceEnd + 1; - // recovery - if (currentElement != null){ - lastCheckPoint = typeDecl.bodyStart; - } -} -protected void consumeClassHeaderImplements() { - // ClassHeaderImplements ::= 'implements' InterfaceTypeList - int length = astLengthStack[astLengthPtr--]; - //super interfaces - astPtr -= length; - // There is a class declaration on the top of stack - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - System.arraycopy( - astStack, - astPtr + 1, - typeDecl.superInterfaces = new TypeReference[length], - 0, - length); - typeDecl.bodyStart = typeDecl.superInterfaces[length-1].sourceEnd + 1; - listLength = 0; // reset after having read super-interfaces - // recovery - if (currentElement != null) { // is recovering - lastCheckPoint = typeDecl.bodyStart; - } -} -protected void consumeClassHeaderName() { - // ClassHeaderName ::= Modifiersopt 'class' 'Identifier' - TypeDeclaration typeDecl; - if (nestedMethod[nestedType] == 0) { - if (nestedType != 0) { - typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult); - } else { - typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); - } - } else { - // Record that the block has a declaration for local types - typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult); - markCurrentMethodWithLocalType(); - blockReal(); - } - - //highlight the name of the type - long pos = identifierPositionStack[identifierPtr]; - typeDecl.sourceEnd = (int) pos; - typeDecl.sourceStart = (int) (pos >>> 32); - typeDecl.name = identifierStack[identifierPtr--]; - identifierLengthPtr--; - - //compute the declaration source too - // 'class' and 'interface' push two int positions: the beginning of the class token and its end. - // we want to keep the beginning position but get rid of the end position - // it is only used for the ClassLiteralAccess positions. - typeDecl.declarationSourceStart = intStack[intPtr--]; - intPtr--; // remove the end position of the class token - - typeDecl.modifiersSourceStart = intStack[intPtr--]; - typeDecl.modifiers = intStack[intPtr--]; - if (typeDecl.modifiersSourceStart >= 0) { - typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart; - } - typeDecl.bodyStart = typeDecl.sourceEnd + 1; - pushOnAstStack(typeDecl); - - listLength = 0; // will be updated when reading super-interfaces - // recovery - if (currentElement != null){ - lastCheckPoint = typeDecl.bodyStart; - currentElement = currentElement.add(typeDecl, 0); - lastIgnoredToken = -1; - } -} -protected void consumeClassInstanceCreationExpression() { - // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt - classInstanceCreation(false); -} -protected void consumeClassInstanceCreationExpressionName() { - // ClassInstanceCreationExpressionName ::= Name '.' - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumeClassInstanceCreationExpressionQualified() { - // ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt - // ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt - - classInstanceCreation(true); // <-- push the Qualifed.... - - expressionLengthPtr--; - QualifiedAllocationExpression qae = - (QualifiedAllocationExpression) expressionStack[expressionPtr--]; - qae.enclosingInstance = expressionStack[expressionPtr]; - expressionStack[expressionPtr] = qae; - qae.sourceStart = qae.enclosingInstance.sourceStart; -} -protected void consumeClassTypeElt() { - // ClassTypeElt ::= ClassType - pushOnAstStack(getTypeReference(0)); - /* if incomplete thrown exception list, listLength counter will not have been reset, - indicating that some items are available on the stack */ - listLength++; -} -protected void consumeClassTypeList() { - // ClassTypeList ::= ClassTypeList ',' ClassTypeElt - optimizedConcatNodeLists(); -} -protected void consumeCompilationUnit() { - // CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt - // do nothing by default -} -protected void consumeConditionalExpression(int op) { - // ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression - //optimize the push/pop - - expressionPtr -= 2; - expressionLengthPtr -= 2; - expressionStack[expressionPtr] = - new ConditionalExpression( - expressionStack[expressionPtr], - expressionStack[expressionPtr + 1], - expressionStack[expressionPtr + 2]); -} -protected void consumeConstructorBlockStatements() { - // ConstructorBody ::= NestedMethod '{' ExplicitConstructorInvocation BlockStatements '}' - concatNodeLists(); // explictly add the first statement into the list of statements -} -protected void consumeConstructorBody() { - // ConstructorBody ::= NestedMethod '{' BlockStatementsopt '}' - // ConstructorBody ::= NestedMethod '{' ExplicitConstructorInvocation '}' - nestedMethod[nestedType] --; -} -protected void consumeConstructorDeclaration() { - // ConstructorDeclaration ::= ConstructorHeader ConstructorBody - - /* - astStack : MethodDeclaration statements - identifierStack : name - ==> - astStack : MethodDeclaration - identifierStack : - */ - - //must provide a default constructor call when needed - - int length; - - // pop the position of the { (body of the method) pushed in block decl - intPtr--; - - //statements - realBlockPtr--; - ExplicitConstructorCall constructorCall = null; - Statement[] statements = null; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - astPtr -= length; - if (astStack[astPtr + 1] instanceof ExplicitConstructorCall) { - //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? - System.arraycopy( - astStack, - astPtr + 2, - statements = new Statement[length - 1], - 0, - length - 1); - constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1]; - } else { //need to add explicitly the super(); - System.arraycopy( - astStack, - astPtr + 1, - statements = new Statement[length], - 0, - length); - constructorCall = SuperReference.implicitSuperConstructorCall(); - } - } else { - if (!diet){ - // add it only in non-diet mode, if diet_bodies, then constructor call will be added elsewhere. - constructorCall = SuperReference.implicitSuperConstructorCall(); - } - } - - // now we know that the top of stack is a constructorDeclaration - ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; - cd.constructorCall = constructorCall; - cd.statements = statements; - - //highlight of the implicit call on the method name - if (constructorCall != null && cd.constructorCall.sourceEnd == 0) { - cd.constructorCall.sourceEnd = cd.sourceEnd; - cd.constructorCall.sourceStart = cd.sourceStart; - } - - //watch for } that could be given as a unicode ! ( u007D is '}' ) - // store the endPosition (position just before the '}') in case there is - // a trailing comment behind the end of the method - cd.bodyEnd = endPosition; - cd.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); -} + case 127 : // System.out.println("ForceNoDiet ::="); + consumeForceNoDiet(); + break; -protected void consumeInvalidConstructorDeclaration() { - // ConstructorDeclaration ::= ConstructorHeader ';' - // now we know that the top of stack is a constructorDeclaration - ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr]; + case 128 : // System.out.println("RestoreDiet ::="); + consumeRestoreDiet(); + break; - cd.bodyEnd = endPosition; // position just before the trailing semi-colon - cd.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); - // report the problem and continue the parsing - narrowing the problem onto the method -} -protected void consumeConstructorHeader() { - // ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters MethodHeaderThrowsClauseopt - - AbstractMethodDeclaration method = (AbstractMethodDeclaration)astStack[astPtr]; - - if (currentToken == TokenNameLBRACE){ - method.bodyStart = scanner.currentPosition; - } - // recovery - if (currentElement != null){ - restartRecovery = true; // used to avoid branching back into the regular automaton - } -} -protected void consumeConstructorHeaderName() { - - /* recovering - might be an empty message send */ - if (currentElement != null){ - if (lastIgnoredToken == TokenNamenew){ // was an allocation expression - lastCheckPoint = scanner.startPosition; // force to restart at this exact position - restartRecovery = true; - return; - } - } - - // ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' - ConstructorDeclaration cd = new ConstructorDeclaration(this.compilationUnit.compilationResult); - - //name -- this is not really revelant but we do ..... - cd.selector = identifierStack[identifierPtr]; - long selectorSource = identifierPositionStack[identifierPtr--]; - identifierLengthPtr--; - - //modifiers - cd.declarationSourceStart = intStack[intPtr--]; - cd.modifiers = intStack[intPtr--]; - - //highlight starts at the selector starts - cd.sourceStart = (int) (selectorSource >>> 32); - pushOnAstStack(cd); - cd.sourceEnd = lParenPos; - cd.bodyStart = lParenPos+1; - listLength = 0; // initialize listLength before reading parameters/throws - - // recovery - if (currentElement != null){ - lastCheckPoint = cd.bodyStart; - if ((currentElement instanceof RecoveredType && lastIgnoredToken != TokenNameDOT) - || cd.modifiers != 0){ - currentElement = currentElement.add(cd, 0); - lastIgnoredToken = -1; - } - } -} -protected void consumeDefaultLabel() { - // SwitchLabel ::= 'default' ':' - pushOnAstStack(new DefaultCase(intStack[intPtr--], intStack[intPtr--])); -} -protected void consumeDefaultModifiers() { - checkAnnotation(); // might update modifiers with AccDeprecated - pushOnIntStack(modifiers); // modifiers - pushOnIntStack( - modifiersSourceStart >= 0 ? modifiersSourceStart : scanner.startPosition); - resetModifiers(); -} -protected void consumeDiet() { - // Diet ::= $empty - checkAnnotation(); - pushOnIntStack(modifiersSourceStart); // push the start position of a javadoc comment if there is one - jumpOverMethodBody(); -} -protected void consumeDims() { - // Dims ::= DimsLoop - pushOnIntStack(dimensions); - dimensions = 0; -} -protected void consumeDimWithOrWithOutExpr() { - // DimWithOrWithOutExpr ::= '[' ']' - pushOnExpressionStack(null); -} -protected void consumeDimWithOrWithOutExprs() { - // DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr - concatExpressionLists(); -} -protected void consumeEmptyArgumentListopt() { - // ArgumentListopt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyArrayInitializer() { - // ArrayInitializer ::= '{' ,opt '}' - arrayInitializer(0); -} -protected void consumeEmptyArrayInitializeropt() { - // ArrayInitializeropt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyBlockStatementsopt() { - // BlockStatementsopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyCatchesopt() { - // Catchesopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyClassBodyDeclarationsopt() { - // ClassBodyDeclarationsopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyClassMemberDeclaration() { - // ClassMemberDeclaration ::= ';' - pushOnAstLengthStack(0); -} -protected void consumeEmptyDimsopt() { - // Dimsopt ::= $empty - pushOnIntStack(0); -} -protected void consumeEmptyExpression() { - // Expressionopt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyForInitopt() { - // ForInitopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyForUpdateopt() { - // ForUpdateopt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyImportDeclarationsopt() { - // ImportDeclarationsopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyInterfaceMemberDeclaration() { - // InterfaceMemberDeclaration ::= ';' - pushOnAstLengthStack(0); -} -protected void consumeEmptyInterfaceMemberDeclarationsopt() { - // InterfaceMemberDeclarationsopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyStatement() { - // EmptyStatement ::= ';' - if (this.scanner.source[endStatementPosition] == ';') { - pushOnAstStack(new EmptyStatement(endStatementPosition, endStatementPosition)); - } else { - // we have a Unicode for the ';' (/u003B) - pushOnAstStack(new EmptyStatement(endStatementPosition - 5, endStatementPosition)); - } -} -protected void consumeEmptySwitchBlock() { - // SwitchBlock ::= '{' '}' - pushOnAstLengthStack(0); -} -protected void consumeEmptyTypeDeclaration() { - // TypeDeclaration ::= ';' - pushOnAstLengthStack(0); -} -protected void consumeEmptyTypeDeclarationsopt() { - // TypeDeclarationsopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEnterAnonymousClassBody() { - // EnterAnonymousClassBody ::= $empty - QualifiedAllocationExpression alloc; - AnonymousLocalTypeDeclaration anonymousType = - new AnonymousLocalTypeDeclaration(this.compilationUnit.compilationResult); - alloc = - anonymousType.allocation = new QualifiedAllocationExpression(anonymousType); - markCurrentMethodWithLocalType(); - pushOnAstStack(anonymousType); - - alloc.sourceEnd = rParenPos; //the position has been stored explicitly - int argumentLength; - if ((argumentLength = expressionLengthStack[expressionLengthPtr--]) != 0) { - expressionPtr -= argumentLength; - System.arraycopy( - expressionStack, - expressionPtr + 1, - alloc.arguments = new Expression[argumentLength], - 0, - argumentLength); - } - alloc.type = getTypeReference(0); - - anonymousType.sourceEnd = alloc.sourceEnd; - //position at the type while it impacts the anonymous declaration - anonymousType.sourceStart = anonymousType.declarationSourceStart = alloc.type.sourceStart; - alloc.sourceStart = intStack[intPtr--]; - pushOnExpressionStack(alloc); - - anonymousType.bodyStart = scanner.currentPosition; - listLength = 0; // will be updated when reading super-interfaces - // recovery - if (currentElement != null){ - lastCheckPoint = anonymousType.bodyStart; - // the recoveryTokenCheck will deal with the open brace - currentElement = currentElement.add(anonymousType, 0); - currentToken = 0; // opening brace already taken into account - lastIgnoredToken = -1; - } -} -protected void consumeEnterCompilationUnit() { - // EnterCompilationUnit ::= $empty - // do nothing by default -} -protected void consumeEnterVariable() { - // EnterVariable ::= $empty - // do nothing by default - - char[] name = identifierStack[identifierPtr]; - long namePosition = identifierPositionStack[identifierPtr]; - int extendedDimension = intStack[intPtr--]; - AbstractVariableDeclaration declaration; - // create the ast node - boolean isLocalDeclaration = nestedMethod[nestedType] != 0; - if (isLocalDeclaration) { - // create the local variable declarations - declaration = - this.createLocalDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition); - } else { - // create the field declaration - declaration = - this.createFieldDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition); - } - - identifierPtr--; - identifierLengthPtr--; - TypeReference type; - int variableIndex = variablesCounter[nestedType]; - int typeDim = 0; - if (variableIndex == 0) { - // first variable of the declaration (FieldDeclaration or LocalDeclaration) - if (isLocalDeclaration) { - declaration.declarationSourceStart = intStack[intPtr--]; - declaration.modifiers = intStack[intPtr--]; - type = getTypeReference(typeDim = intStack[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 = intStack[intPtr--]); // type dimension - pushOnAstStack(type); - declaration.declarationSourceStart = intStack[intPtr--]; - declaration.modifiers = intStack[intPtr--]; - } - } else { - type = (TypeReference) astStack[astPtr - variableIndex]; - typeDim = type.dimensions(); - AbstractVariableDeclaration previousVariable = - (AbstractVariableDeclaration) astStack[astPtr]; - declaration.declarationSourceStart = previousVariable.declarationSourceStart; - declaration.modifiers = previousVariable.modifiers; - } - - if (extendedDimension == 0) { - declaration.type = type; - } else { - int dimension = typeDim + extendedDimension; - //on the identifierLengthStack there is the information about the type.... - int baseType; - if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { - //it was a baseType - int typeSourceStart = type.sourceStart; - int typeSourceEnd = type.sourceEnd; - type = TypeReference.baseTypeReference(-baseType, dimension); - type.sourceStart = typeSourceStart; - type.sourceEnd = typeSourceEnd; - declaration.type = type; - } else { - declaration.type = this.copyDims(type, dimension); - } - } - variablesCounter[nestedType]++; - pushOnAstStack(declaration); - // recovery - if (currentElement != null) { - if (!(currentElement instanceof RecoveredType) - && (currentToken == TokenNameDOT - //|| declaration.modifiers != 0 - || (scanner.getLineNumber(declaration.type.sourceStart) - != scanner.getLineNumber((int) (namePosition >>> 32))))){ - lastCheckPoint = (int) (namePosition >>> 32); - restartRecovery = true; - return; - } - if (isLocalDeclaration){ - LocalDeclaration localDecl = (LocalDeclaration) astStack[astPtr]; - lastCheckPoint = localDecl.sourceEnd + 1; - currentElement = currentElement.add(localDecl, 0); - } else { - FieldDeclaration fieldDecl = (FieldDeclaration) astStack[astPtr]; - lastCheckPoint = fieldDecl.sourceEnd + 1; - currentElement = currentElement.add(fieldDecl, 0); - } - lastIgnoredToken = -1; - } -} -protected void consumeEqualityExpression(int op) { - // EqualityExpression ::= EqualityExpression '==' RelationalExpression - // EqualityExpression ::= EqualityExpression '!=' RelationalExpression - - //optimize the push/pop - - expressionPtr--; - expressionLengthPtr--; - expressionStack[expressionPtr] = - new EqualExpression( - expressionStack[expressionPtr], - expressionStack[expressionPtr + 1], - op); -} -protected void consumeExitVariableWithInitialization() { - // ExitVariableWithInitialization ::= $empty - // do nothing by default - expressionLengthPtr--; - AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) astStack[astPtr]; - variableDecl.initialization = expressionStack[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; -} -protected void consumeExitVariableWithoutInitialization() { - // ExitVariableWithoutInitialization ::= $empty - // do nothing by default -} -protected void consumeExplicitConstructorInvocation(int flag, int recFlag) { - - /* flag allows to distinguish 3 cases : - (0) : - ExplicitConstructorInvocation ::= 'this' '(' ArgumentListopt ')' ';' - ExplicitConstructorInvocation ::= 'super' '(' ArgumentListopt ')' ';' - (1) : - ExplicitConstructorInvocation ::= Primary '.' 'super' '(' ArgumentListopt ')' ';' - ExplicitConstructorInvocation ::= Primary '.' 'this' '(' ArgumentListopt ')' ';' - (2) : - ExplicitConstructorInvocation ::= Name '.' 'super' '(' ArgumentListopt ')' ';' - ExplicitConstructorInvocation ::= Name '.' 'this' '(' ArgumentListopt ')' ';' - */ - int startPosition = intStack[intPtr--]; - ExplicitConstructorCall ecc = new ExplicitConstructorCall(recFlag); - int length; - if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { - expressionPtr -= length; - System.arraycopy(expressionStack, expressionPtr + 1, ecc.arguments = new Expression[length], 0, length); - } - switch (flag) { - case 0 : - ecc.sourceStart = startPosition; - break; - case 1 : - expressionLengthPtr--; - ecc.sourceStart = (ecc.qualification = expressionStack[expressionPtr--]).sourceStart; - break; - case 2 : - ecc.sourceStart = (ecc.qualification = getUnspecifiedReferenceOptimized()).sourceStart; - break; - }; - pushOnAstStack(ecc); - ecc.sourceEnd = endPosition; -} -protected void consumeExpressionStatement() { - // ExpressionStatement ::= StatementExpression ';' - expressionLengthPtr--; - pushOnAstStack(expressionStack[expressionPtr--]); -} -protected void consumeFieldAccess(boolean isSuperAccess) { - // FieldAccess ::= Primary '.' 'Identifier' - // FieldAccess ::= 'super' '.' 'Identifier' - - FieldReference fr = - new FieldReference( - identifierStack[identifierPtr], - identifierPositionStack[identifierPtr--]); - identifierLengthPtr--; - if (isSuperAccess) { - //considerates the fieldReference beginning at the 'super' .... - fr.sourceStart = intStack[intPtr--]; - fr.receiver = new SuperReference(fr.sourceStart, endPosition); - pushOnExpressionStack(fr); - } else { - //optimize push/pop - if ((fr.receiver = expressionStack[expressionPtr]).isThis()) { - //fieldreference begins at the this - fr.sourceStart = fr.receiver.sourceStart; - } - expressionStack[expressionPtr] = fr; - } -} -protected void consumeFieldDeclaration() { - // See consumeLocalVariableDeclarationDefaultModifier() in case of change: duplicated code - // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' - - /* - astStack : - expressionStack: Expression Expression ...... Expression - identifierStack : type identifier identifier ...... identifier - intStack : typeDim dim dim dim - ==> - astStack : FieldDeclaration FieldDeclaration ...... FieldDeclaration - expressionStack : - identifierStack : - intStack : - - */ - int variableDeclaratorsCounter = astLengthStack[astLengthPtr]; - - for (int i = variableDeclaratorsCounter - 1; i >= 0; i--) { - FieldDeclaration fieldDeclaration = (FieldDeclaration) astStack[astPtr - i]; - fieldDeclaration.declarationSourceEnd = endStatementPosition; - fieldDeclaration.declarationEnd = endStatementPosition; // semi-colon included - } - updateSourceDeclarationParts(variableDeclaratorsCounter); - int endPos = flushAnnotationsDefinedPriorTo(endStatementPosition); - if (endPos != endStatementPosition) { - for (int i = 0; i < variableDeclaratorsCounter; i++) { - FieldDeclaration fieldDeclaration = (FieldDeclaration) astStack[astPtr - i]; - fieldDeclaration.declarationSourceEnd = endPos; - } - } - // update the astStack, astPtr and astLengthStack - int startIndex = astPtr - variablesCounter[nestedType] + 1; - System.arraycopy( - astStack, - startIndex, - astStack, - startIndex - 1, - variableDeclaratorsCounter); - astPtr--; // remove the type reference - astLengthStack[--astLengthPtr] = variableDeclaratorsCounter; - - // recovery - if (currentElement != null) { - lastCheckPoint = endPos + 1; - if (currentElement.parent != null && currentElement instanceof RecoveredField){ - currentElement = currentElement.parent; - } - restartRecovery = true; - } - variablesCounter[nestedType] = 0; -} -protected void consumeForceNoDiet() { - // ForceNoDiet ::= $empty - dietInt++; -} -protected void consumeForInit() { - // ForInit ::= StatementExpressionList - pushOnAstLengthStack(-1); -} -protected void consumeFormalParameter() { - // FormalParameter ::= Type VariableDeclaratorId ==> false - // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true - /* - astStack : - identifierStack : type identifier - intStack : dim dim - ==> - astStack : Argument - identifierStack : - intStack : - */ - - identifierLengthPtr--; - char[] name = identifierStack[identifierPtr]; - long namePositions = identifierPositionStack[identifierPtr--]; - TypeReference type = getTypeReference(intStack[intPtr--] + intStack[intPtr--]); - int modifierPositions = intStack[intPtr--]; - intPtr--; - Argument arg = - new Argument( - name, - namePositions, - type, - intStack[intPtr + 1] & ~AccDeprecated); // modifiers - arg.declarationSourceStart = modifierPositions; - pushOnAstStack(arg); - - /* if incomplete method header, listLength counter will not have been reset, - indicating that some arguments are available on the stack */ - listLength++; -} -protected void consumeFormalParameterList() { - // FormalParameterList ::= FormalParameterList ',' FormalParameter - optimizedConcatNodeLists(); -} -protected void consumeFormalParameterListopt() { - // FormalParameterListopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeImportDeclarations() { - // ImportDeclarations ::= ImportDeclarations ImportDeclaration - optimizedConcatNodeLists(); -} -protected void consumeImportDeclarationsopt() { - // ImportDeclarationsopt ::= ImportDeclarations - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - astPtr -= length; - System.arraycopy( - astStack, - astPtr + 1, - compilationUnit.imports = new ImportReference[length], - 0, - length); - } -} -protected void consumeInstanceOfExpression(int op) { - // RelationalExpression ::= RelationalExpression 'instanceof' ReferenceType - //optimize the push/pop - - //by construction, no base type may be used in getTypeReference - Expression exp; - expressionStack[expressionPtr] = exp = - new InstanceOfExpression( - expressionStack[expressionPtr], - getTypeReference(intStack[intPtr--]), - op); - if (exp.sourceEnd == 0) { - //array on base type.... - exp.sourceEnd = scanner.startPosition - 1; - } - //the scanner is on the next token already.... -} -protected void consumeInterfaceDeclaration() { - // see consumeClassDeclaration in case of changes: duplicated code - // InterfaceDeclaration ::= InterfaceHeader InterfaceBody - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - //there are length declarations - //dispatch.....according to the type of the declarations - dispatchDeclarationInto(length); - } - - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - - // mark fields and initializer with local type mark if needed - markFieldsWithLocalType(typeDecl); - - //convert constructor that do not have the type's name into methods - typeDecl.checkConstructors(this); - - //always add (will be remove at code gen time if empty) - if (this.scanner.containsAssertKeyword) { - typeDecl.bits |= AstNode.AddAssertionMASK; - } - typeDecl.addClinit(); - typeDecl.bodyEnd = endStatementPosition; - typeDecl.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); -} -protected void consumeInterfaceHeader() { - // InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt - - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - if (currentToken == TokenNameLBRACE){ - typeDecl.bodyStart = scanner.currentPosition; - } - if (currentElement != null){ - restartRecovery = true; // used to avoid branching back into the regular automaton - } - // flush the comments related to the interface header - scanner.commentPtr = -1; -} -protected void consumeInterfaceHeaderExtends() { - // InterfaceHeaderExtends ::= 'extends' InterfaceTypeList - int length = astLengthStack[astLengthPtr--]; - //super interfaces - astPtr -= length; - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - System.arraycopy( - astStack, - astPtr + 1, - typeDecl.superInterfaces = new TypeReference[length], - 0, - length); - typeDecl.bodyStart = typeDecl.superInterfaces[length-1].sourceEnd + 1; - listLength = 0; // reset after having read super-interfaces - // recovery - if (currentElement != null) { - lastCheckPoint = typeDecl.bodyStart; - } -} -protected void consumeInterfaceHeaderName() { - // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier' - TypeDeclaration typeDecl; - if (nestedMethod[nestedType] == 0) { - if (nestedType != 0) { - typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult); - } else { - typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult); - } - } else { - // Record that the block has a declaration for local types - typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult); - markCurrentMethodWithLocalType(); - blockReal(); - } - - //highlight the name of the type - long pos = identifierPositionStack[identifierPtr]; - typeDecl.sourceEnd = (int) pos; - typeDecl.sourceStart = (int) (pos >>> 32); - typeDecl.name = identifierStack[identifierPtr--]; - identifierLengthPtr--; - - //compute the declaration source too - // 'class' and 'interface' push two int positions: the beginning of the class token and its end. - // we want to keep the beginning position but get rid of the end position - // it is only used for the ClassLiteralAccess positions. - typeDecl.declarationSourceStart = intStack[intPtr--]; - intPtr--; // remove the end position of the class token - typeDecl.modifiersSourceStart = intStack[intPtr--]; - typeDecl.modifiers = intStack[intPtr--]; - if (typeDecl.modifiersSourceStart >= 0) { - typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart; - } - typeDecl.bodyStart = typeDecl.sourceEnd + 1; - pushOnAstStack(typeDecl); - listLength = 0; // will be updated when reading super-interfaces - // recovery - if (currentElement != null){ // is recovering - lastCheckPoint = typeDecl.bodyStart; - currentElement = currentElement.add(typeDecl, 0); - lastIgnoredToken = -1; - } -} -protected void consumeInterfaceMemberDeclarations() { - // InterfaceMemberDeclarations ::= InterfaceMemberDeclarations InterfaceMemberDeclaration - concatNodeLists(); -} -protected void consumeInterfaceMemberDeclarationsopt() { - // InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations - nestedType--; -} -protected void consumeInterfaceType() { - // InterfaceType ::= ClassOrInterfaceType - pushOnAstStack(getTypeReference(0)); - /* if incomplete type header, listLength counter will not have been reset, - indicating that some interfaces are available on the stack */ - listLength++; -} -protected void consumeInterfaceTypeList() { - // InterfaceTypeList ::= InterfaceTypeList ',' InterfaceType - optimizedConcatNodeLists(); -} -protected void consumeLeftHandSide() { - // LeftHandSide ::= Name + case 133 : // System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); + // set to true to consume a method with a body + consumeMethodDeclaration(true); + break; + + case 134 : // System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); + // set to false to consume a method without body + consumeMethodDeclaration(false); + break; + + case 135 : // System.out.println("MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims"); + consumeMethodHeader(); + break; + + case 136 : // System.out.println("MethodPushModifiersHeader ::= MethodPushModifiersHeaderName MethodHeaderParameters"); + consumeMethodHeader(); + break; + + case 137 : // System.out.println("MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers Identifier LPAREN"); + consumeMethodPushModifiersHeaderName(); + break; + + case 138 : // System.out.println("MethodPushModifiersHeaderName ::= Type PushModifiers Identifier LPAREN"); + consumeMethodPushModifiersHeaderName(); + break; + + case 139 : // System.out.println("MethodHeaderName ::= Modifiersopt Type Identifier LPAREN"); + consumeMethodHeaderName(); + break; + + case 140 : // System.out.println("MethodHeaderParameters ::= FormalParameterListopt RPAREN"); + consumeMethodHeaderParameters(); + break; + + case 141 : // System.out.println("MethodHeaderExtendedDims ::= Dimsopt"); + consumeMethodHeaderExtendedDims(); + break; + + case 142 : // System.out.println("MethodHeaderThrowsClause ::= throws ClassTypeList"); + consumeMethodHeaderThrowsClause(); + break; + + case 143 : // System.out.println("ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters..."); + consumeConstructorHeader(); + break; + + case 144 : // System.out.println("ConstructorHeaderName ::= Modifiersopt Identifier LPAREN"); + consumeConstructorHeaderName(); + break; + + case 146 : // System.out.println("FormalParameterList ::= FormalParameterList COMMA FormalParameter"); + consumeFormalParameterList(); + break; + + case 147 : // System.out.println("FormalParameter ::= Modifiersopt Type VariableDeclaratorId"); + // the boolean is used to know if the modifiers should be reset + consumeFormalParameter(); + break; - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumeLeftParen() { - // PushLPAREN ::= '(' - pushOnIntStack(lParenPos); -} -protected void consumeLocalVariableDeclaration() { - // LocalVariableDeclaration ::= Modifiers Type VariableDeclarators ';' - - /* - astStack : - expressionStack: Expression Expression ...... Expression - identifierStack : type identifier identifier ...... identifier - intStack : typeDim dim dim dim - ==> - astStack : FieldDeclaration FieldDeclaration ...... FieldDeclaration - expressionStack : - identifierStack : - intStack : - - */ - int variableDeclaratorsCounter = astLengthStack[astLengthPtr]; - - // update the astStack, astPtr and astLengthStack - int startIndex = astPtr - variablesCounter[nestedType] + 1; - System.arraycopy( - astStack, - startIndex, - astStack, - startIndex - 1, - variableDeclaratorsCounter); - astPtr--; // remove the type reference - astLengthStack[--astLengthPtr] = variableDeclaratorsCounter; - variablesCounter[nestedType] = 0; -} -protected void consumeLocalVariableDeclarationStatement() { - // LocalVariableDeclarationStatement ::= LocalVariableDeclaration ';' - // see blockReal in case of change: duplicated code - // increment the amount of declared variables for this block - realBlockStack[realBlockPtr]++; -} -protected void consumeMethodBody() { - // MethodBody ::= NestedMethod '{' BlockStatementsopt '}' - nestedMethod[nestedType] --; -} -protected void consumeMethodDeclaration(boolean isNotAbstract) { - // MethodDeclaration ::= MethodHeader MethodBody - // AbstractMethodDeclaration ::= MethodHeader ';' - - /* - astStack : modifiers arguments throws statements - identifierStack : type name - intStack : dim dim dim - ==> - astStack : MethodDeclaration - identifierStack : - intStack : - */ - - int length; - if (isNotAbstract) { - // pop the position of the { (body of the method) pushed in block decl - intPtr--; - } - - int explicitDeclarations = 0; - Statement[] statements = null; - if (isNotAbstract) { - //statements - explicitDeclarations = realBlockStack[realBlockPtr--]; - if ((length = astLengthStack[astLengthPtr--]) != 0) - System.arraycopy( - astStack, - (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) astStack[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 |= AccSemicolonBody; - } - // store the endPosition (position just before the '}') in case there is - // a trailing comment behind the end of the method - md.bodyEnd = endPosition; - md.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); -} -protected void consumeMethodHeader() { - // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt - // retrieve end position of method declarator - AbstractMethodDeclaration method = (AbstractMethodDeclaration)astStack[astPtr]; - - if (currentToken == TokenNameLBRACE){ - method.bodyStart = scanner.currentPosition; - } - // recovery - if (currentElement != null){ - if (currentToken == TokenNameSEMICOLON){ - method.modifiers |= AccSemicolonBody; - method.declarationSourceEnd = scanner.currentPosition-1; - method.bodyEnd = scanner.currentPosition-1; - if (currentElement.parent != null){ - currentElement = currentElement.parent; - } - } - restartRecovery = true; // used to avoid branching back into the regular automaton - } -} -protected void consumeMethodHeaderExtendedDims() { - // MethodHeaderExtendedDims ::= Dimsopt - // now we update the returnType of the method - MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; - int extendedDims = intStack[intPtr--]; - if (extendedDims != 0) { - TypeReference returnType = md.returnType; - md.sourceEnd = endPosition; - int dims = returnType.dimensions() + extendedDims; - int baseType; - if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) { - //it was a baseType - int sourceStart = returnType.sourceStart; - int sourceEnd = returnType.sourceEnd; - returnType = TypeReference.baseTypeReference(-baseType, dims); - returnType.sourceStart = sourceStart; - returnType.sourceEnd = sourceEnd; - md.returnType = returnType; - } else { - md.returnType = this.copyDims(md.returnType, dims); - } - if (currentToken == TokenNameLBRACE){ - md.bodyStart = endPosition + 1; - } - // recovery - if (currentElement != null){ - lastCheckPoint = md.bodyStart; - } - } -} -protected void consumeMethodHeaderName() { - // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' - MethodDeclaration md = new MethodDeclaration(this.compilationUnit.compilationResult); - - //name - md.selector = identifierStack[identifierPtr]; - long selectorSource = identifierPositionStack[identifierPtr--]; - identifierLengthPtr--; - //type - md.returnType = getTypeReference(intStack[intPtr--]); - //modifiers - md.declarationSourceStart = intStack[intPtr--]; - md.modifiers = intStack[intPtr--]; - - //highlight starts at selector start - md.sourceStart = (int) (selectorSource >>> 32); - pushOnAstStack(md); - md.sourceEnd = lParenPos; - md.bodyStart = lParenPos+1; - listLength = 0; // initialize listLength before reading parameters/throws - - // recovery - if (currentElement != null){ - if (currentElement instanceof RecoveredType - //|| md.modifiers != 0 - || (scanner.getLineNumber(md.returnType.sourceStart) - == scanner.getLineNumber(md.sourceStart))){ - lastCheckPoint = md.bodyStart; - currentElement = currentElement.add(md, 0); - lastIgnoredToken = -1; - } else { - lastCheckPoint = md.sourceStart; - restartRecovery = true; - } - } -} -protected void consumeMethodHeaderParameters() { - // MethodHeaderParameters ::= FormalParameterListopt ')' - int length = astLengthStack[astLengthPtr--]; - astPtr -= length; - AbstractMethodDeclaration md = (AbstractMethodDeclaration) astStack[astPtr]; - md.sourceEnd = rParenPos; - //arguments - if (length != 0) { - System.arraycopy( - astStack, - astPtr + 1, - md.arguments = new Argument[length], - 0, - length); - } - md.bodyStart = rParenPos+1; - listLength = 0; // reset listLength after having read all parameters - // recovery - if (currentElement != null){ - lastCheckPoint = md.bodyStart; - if (currentElement.parseTree() == md) return; - - // might not have been attached yet - in some constructor scenarii - if (md.isConstructor()){ - if ((length != 0) - || (currentToken == TokenNameLBRACE) - // || (currentToken == TokenNamethrows) - ){ - currentElement = currentElement.add(md, 0); - lastIgnoredToken = -1; - } - } - } -} -protected void consumeMethodHeaderThrowsClause() { - // MethodHeaderThrowsClause ::= 'throws' ClassTypeList - int length = astLengthStack[astLengthPtr--]; - astPtr -= length; - AbstractMethodDeclaration md = (AbstractMethodDeclaration) astStack[astPtr]; - System.arraycopy( - astStack, - astPtr + 1, - md.thrownExceptions = new TypeReference[length], - 0, - length); - md.sourceEnd = md.thrownExceptions[length-1].sourceEnd; - md.bodyStart = md.thrownExceptions[length-1].sourceEnd + 1; - listLength = 0; // reset listLength after having read all thrown exceptions - // recovery - if (currentElement != null){ - lastCheckPoint = md.bodyStart; - } -} -protected void consumeMethodInvocationName() { - // MethodInvocation ::= Name '(' ArgumentListopt ')' - - // when the name is only an identifier...we have a message send to "this" (implicit) - - MessageSend m = newMessageSend(); - m.sourceEnd = rParenPos; - m.sourceStart = - (int) ((m.nameSourcePosition = identifierPositionStack[identifierPtr]) >>> 32); - m.selector = identifierStack[identifierPtr--]; - if (identifierLengthStack[identifierLengthPtr] == 1) { - m.receiver = ThisReference.ThisImplicit; - identifierLengthPtr--; - } else { - identifierLengthStack[identifierLengthPtr]--; - m.receiver = getUnspecifiedReference(); - m.sourceStart = m.receiver.sourceStart; - } - pushOnExpressionStack(m); -} -protected void consumeMethodInvocationPrimary() { - //optimize the push/pop - //MethodInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' - - MessageSend m = newMessageSend(); - m.sourceStart = - (int) ((m.nameSourcePosition = identifierPositionStack[identifierPtr]) >>> 32); - m.selector = identifierStack[identifierPtr--]; - identifierLengthPtr--; - m.receiver = expressionStack[expressionPtr]; - m.sourceStart = m.receiver.sourceStart; - m.sourceEnd = rParenPos; - expressionStack[expressionPtr] = m; -} -protected void consumeMethodInvocationSuper() { - // MethodInvocation ::= 'super' '.' 'Identifier' '(' ArgumentListopt ')' - - MessageSend m = newMessageSend(); - m.sourceStart = intStack[intPtr--]; - m.sourceEnd = rParenPos; - m.nameSourcePosition = identifierPositionStack[identifierPtr]; - m.selector = identifierStack[identifierPtr--]; - identifierLengthPtr--; - m.receiver = new SuperReference(m.sourceStart, endPosition); - pushOnExpressionStack(m); -} -protected void consumeMethodPushModifiersHeaderName() { - // MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers 'Identifier' '(' - // MethodPushModifiersHeaderName ::= Type PushModifiers 'Identifier' '(' - MethodDeclaration md = new MethodDeclaration(this.compilationUnit.compilationResult); - - //name - md.selector = identifierStack[identifierPtr]; - long selectorSource = identifierPositionStack[identifierPtr--]; - identifierLengthPtr--; - - //modifiers - md.declarationSourceStart = intStack[intPtr--]; - md.modifiers = intStack[intPtr--]; - - //type - md.returnType = getTypeReference(intStack[intPtr--]); - - //highlight starts at selector start - md.sourceStart = (int) (selectorSource >>> 32); - pushOnAstStack(md); - md.sourceEnd = lParenPos; - md.bodyStart = lParenPos + 1; - listLength = 0; // initialize listLength before reading parameters/throws - - // recovery - if (currentElement != null) { - lastCheckPoint = md.bodyStart; - currentElement = currentElement.add(md, 0); - lastIgnoredToken = -1; - } -} -protected void consumeModifiers() { - int savedModifiersSourceStart = modifiersSourceStart; - checkAnnotation(); // might update modifiers with AccDeprecated - pushOnIntStack(modifiers); // modifiers - if (modifiersSourceStart >= savedModifiersSourceStart) { - modifiersSourceStart = savedModifiersSourceStart; - } - pushOnIntStack(modifiersSourceStart); - resetModifiers(); -} -protected void consumeNestedMethod() { - // NestedMethod ::= $empty - jumpOverMethodBody(); - nestedMethod[nestedType] ++; - consumeOpenBlock(); -} -protected void consumeNestedType() { - // NestedType ::= $empty - nestedType++; - try { - nestedMethod[nestedType] = 0; - } catch (IndexOutOfBoundsException e) { - //except in test's cases, it should never raise - int oldL = nestedMethod.length; - System.arraycopy(nestedMethod , 0, (nestedMethod = new int[oldL + 30]), 0, oldL); - nestedMethod[nestedType] = 0; - // increase the size of the fieldsCounter as well. It has to be consistent with the size of the nestedMethod collection - System.arraycopy(variablesCounter, 0, (variablesCounter = new int[oldL + 30]), 0, oldL); - } - variablesCounter[nestedType] = 0; -} -protected void consumeOneDimLoop() { - // OneDimLoop ::= '[' ']' - dimensions++; -} -protected void consumeOnlySynchronized() { - // OnlySynchronized ::= 'synchronized' - pushOnIntStack(this.synchronizedBlockSourceStart); - resetModifiers(); -} -protected void consumeOpenBlock() { - // OpenBlock ::= $empty - - pushOnIntStack(scanner.startPosition); - try { - realBlockStack[++realBlockPtr] = 0; - } catch (IndexOutOfBoundsException e) { - //realBlockPtr is correct - int oldStackLength = realBlockStack.length; - int oldStack[] = realBlockStack; - realBlockStack = new int[oldStackLength + StackIncrement]; - System.arraycopy(oldStack, 0, realBlockStack, 0, oldStackLength); - realBlockStack[realBlockPtr] = 0; - } -} -protected void consumePackageDeclaration() { - // PackageDeclaration ::= 'package' Name ';' - /* build an ImportRef build from the last name - stored in the identifier stack. */ - - ImportReference impt = compilationUnit.currentPackage; - // flush annotations defined prior to import statements - impt.declarationEnd = endStatementPosition; - impt.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(impt.declarationSourceEnd); -} -protected void consumePackageDeclarationName() { - // PackageDeclarationName ::= 'package' Name - /* build an ImportRef build from the last name - stored in the identifier stack. */ - - ImportReference impt; - int length; - char[][] tokens = - new char[length = identifierLengthStack[identifierLengthPtr--]][]; - identifierPtr -= length; - long[] positions = new long[length]; - System.arraycopy(identifierStack, ++identifierPtr, tokens, 0, length); - System.arraycopy( - identifierPositionStack, - identifierPtr--, - positions, - 0, - length); - compilationUnit.currentPackage = - impt = new ImportReference(tokens, positions, true); - - if (currentToken == TokenNameSEMICOLON){ - impt.declarationSourceEnd = scanner.currentPosition - 1; - } else { - impt.declarationSourceEnd = impt.sourceEnd; - } - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = intStack[intPtr--]; - - // recovery - if (currentElement != null){ - lastCheckPoint = impt.declarationSourceEnd+1; - restartRecovery = true; // used to avoid branching back into the regular automaton - } -} -protected void consumePostfixExpression() { - // PostfixExpression ::= Name - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumePrimaryNoNewArray() { - // PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN - updateSourcePosition(expressionStack[expressionPtr]); -} -protected void consumePrimaryNoNewArrayArrayType() { - // PrimaryNoNewArray ::= ArrayType '.' 'class' - intPtr--; - pushOnExpressionStack( - new ClassLiteralAccess(intStack[intPtr--], - getTypeReference(intStack[intPtr--]))); -} -protected void consumePrimaryNoNewArrayName() { - // PrimaryNoNewArray ::= Name '.' 'class' - intPtr--; - pushOnExpressionStack( - new ClassLiteralAccess(intStack[intPtr--], - getTypeReference(0))); -} -protected void consumePrimaryNoNewArrayNameSuper() { - // PrimaryNoNewArray ::= Name '.' 'super' - pushOnExpressionStack( - new QualifiedSuperReference( - getTypeReference(0), - intStack[intPtr--], - endPosition)); -} -protected void consumePrimaryNoNewArrayNameThis() { - // PrimaryNoNewArray ::= Name '.' 'this' - pushOnExpressionStack( - new QualifiedThisReference( - getTypeReference(0), - intStack[intPtr--], - endPosition)); -} -protected void consumePrimaryNoNewArrayPrimitiveType() { - // PrimaryNoNewArray ::= PrimitiveType '.' 'class' - intPtr--; - pushOnExpressionStack( - new ClassLiteralAccess(intStack[intPtr--], - getTypeReference(0))); -} -protected void consumePrimaryNoNewArrayThis() { - // PrimaryNoNewArray ::= 'this' - pushOnExpressionStack(new ThisReference(intStack[intPtr--], endPosition)); -} -protected void consumePrimitiveType() { - // Type ::= PrimitiveType - pushOnIntStack(0); -} -protected void consumePushModifiers() { - if ((modifiers & AccSynchronized) != 0) { - /* remove the starting position of the synchronized keyword - * we don't need it when synchronized is part of the modifiers - */ - intPtr--; - } - pushOnIntStack(modifiers); // modifiers - pushOnIntStack(modifiersSourceStart); - resetModifiers(); -} -protected void consumePushPosition() { - // for source managment purpose - // PushPosition ::= $empty - pushOnIntStack(endPosition); -} -protected void consumeQualifiedName() { - // QualifiedName ::= Name '.' SimpleName - /*back from the recursive loop of QualifiedName. - Updates identifier length into the length stack*/ + case 149 : // System.out.println("ClassTypeList ::= ClassTypeList COMMA ClassTypeElt"); + consumeClassTypeList(); + break; - identifierLengthStack[--identifierLengthPtr]++; -} -protected void consumeReferenceType() { - // ReferenceType ::= ClassOrInterfaceType - pushOnIntStack(0); -} -protected void consumeRestoreDiet() { - // RestoreDiet ::= $empty - dietInt--; -} -protected void consumeRightParen() { - // PushRPAREN ::= ')' - pushOnIntStack(rParenPos); -} - // This method is part of an automatic generation : do NOT edit-modify - // This method is part of an automatic generation : do NOT edit-modify - protected void consumeRule(int act) { - switch ( act ) { - case 29 : // System.out.println("Type ::= PrimitiveType"); - consumePrimitiveType(); - break ; - - case 43 : // System.out.println("ReferenceType ::= ClassOrInterfaceType"); - consumeReferenceType(); - break ; - - case 52 : // System.out.println("QualifiedName ::= Name DOT SimpleName"); - consumeQualifiedName(); - break ; - - case 53 : // System.out.println("CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt"); - consumeCompilationUnit(); - break ; - - case 54 : // System.out.println("EnterCompilationUnit ::="); - consumeEnterCompilationUnit(); - break ; - - case 66 : // System.out.println("CatchHeader ::= catch LPAREN FormalParameter RPAREN LBRACE"); - consumeCatchHeader(); - break ; - - case 68 : // System.out.println("ImportDeclarations ::= ImportDeclarations ImportDeclaration"); - consumeImportDeclarations(); - break ; - - case 70 : // System.out.println("TypeDeclarations ::= TypeDeclarations TypeDeclaration"); - consumeTypeDeclarations(); - break ; - - case 71 : // System.out.println("PackageDeclaration ::= PackageDeclarationName SEMICOLON"); - consumePackageDeclaration(); - break ; - - case 72 : // System.out.println("PackageDeclarationName ::= package Name"); - consumePackageDeclarationName(); - break ; - - case 75 : // System.out.println("SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName SEMICOLON"); - consumeSingleTypeImportDeclaration(); - break ; - - case 76 : // System.out.println("SingleTypeImportDeclarationName ::= import Name"); - consumeSingleTypeImportDeclarationName(); - break ; - - case 77 : // System.out.println("TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName SEMICOLON"); - consumeTypeImportOnDemandDeclaration(); - break ; - - case 78 : // System.out.println("TypeImportOnDemandDeclarationName ::= import Name DOT MULTIPLY"); - consumeTypeImportOnDemandDeclarationName(); - break ; - - case 81 : // System.out.println("TypeDeclaration ::= SEMICOLON"); - consumeEmptyTypeDeclaration(); - break ; - - case 95 : // System.out.println("ClassDeclaration ::= ClassHeader ClassBody"); - consumeClassDeclaration(); - break ; - - case 96 : // System.out.println("ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt"); - consumeClassHeader(); - break ; - - case 97 : // System.out.println("ClassHeaderName ::= Modifiersopt class Identifier"); - consumeClassHeaderName(); - break ; - - case 98 : // System.out.println("ClassHeaderExtends ::= extends ClassType"); - consumeClassHeaderExtends(); - break ; - - case 99 : // System.out.println("ClassHeaderImplements ::= implements InterfaceTypeList"); - consumeClassHeaderImplements(); - break ; - - case 101 : // System.out.println("InterfaceTypeList ::= InterfaceTypeList COMMA InterfaceType"); - consumeInterfaceTypeList(); - break ; - - case 102 : // System.out.println("InterfaceType ::= ClassOrInterfaceType"); - consumeInterfaceType(); - break ; - - case 105 : // System.out.println("ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration"); - consumeClassBodyDeclarations(); - break ; - - case 109 : // System.out.println("ClassBodyDeclaration ::= Diet NestedMethod Block"); - consumeClassBodyDeclaration(); - break ; - - case 110 : // System.out.println("Diet ::="); - consumeDiet(); - break ; - - case 111 : // System.out.println("Initializer ::= Diet NestedMethod Block"); - consumeClassBodyDeclaration(); - break ; - - case 118 : // System.out.println("ClassMemberDeclaration ::= SEMICOLON"); - consumeEmptyClassMemberDeclaration(); - break ; - - case 119 : // System.out.println("FieldDeclaration ::= Modifiersopt Type VariableDeclarators SEMICOLON"); - consumeFieldDeclaration(); - break ; - - case 121 : // System.out.println("VariableDeclarators ::= VariableDeclarators COMMA VariableDeclarator"); - consumeVariableDeclarators(); - break ; - - case 124 : // System.out.println("EnterVariable ::="); - consumeEnterVariable(); - break ; - - case 125 : // System.out.println("ExitVariableWithInitialization ::="); - consumeExitVariableWithInitialization(); - break ; - - case 126 : // System.out.println("ExitVariableWithoutInitialization ::="); - consumeExitVariableWithoutInitialization(); - break ; - - case 127 : // System.out.println("ForceNoDiet ::="); - consumeForceNoDiet(); - break ; - - case 128 : // System.out.println("RestoreDiet ::="); - consumeRestoreDiet(); - break ; - - case 133 : // System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); - // set to true to consume a method with a body - consumeMethodDeclaration(true); - break ; - - case 134 : // System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); - // set to false to consume a method without body - consumeMethodDeclaration(false); - break ; - - case 135 : // System.out.println("MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims"); - consumeMethodHeader(); - break ; - - case 136 : // System.out.println("MethodPushModifiersHeader ::= MethodPushModifiersHeaderName MethodHeaderParameters"); - consumeMethodHeader(); - break ; - - case 137 : // System.out.println("MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers Identifier LPAREN"); - consumeMethodPushModifiersHeaderName(); - break ; - - case 138 : // System.out.println("MethodPushModifiersHeaderName ::= Type PushModifiers Identifier LPAREN"); - consumeMethodPushModifiersHeaderName(); - break ; - - case 139 : // System.out.println("MethodHeaderName ::= Modifiersopt Type Identifier LPAREN"); - consumeMethodHeaderName(); - break ; - - case 140 : // System.out.println("MethodHeaderParameters ::= FormalParameterListopt RPAREN"); - consumeMethodHeaderParameters(); - break ; - - case 141 : // System.out.println("MethodHeaderExtendedDims ::= Dimsopt"); - consumeMethodHeaderExtendedDims(); - break ; - - case 142 : // System.out.println("MethodHeaderThrowsClause ::= throws ClassTypeList"); - consumeMethodHeaderThrowsClause(); - break ; - - case 143 : // System.out.println("ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters..."); - consumeConstructorHeader(); - break ; - - case 144 : // System.out.println("ConstructorHeaderName ::= Modifiersopt Identifier LPAREN"); - consumeConstructorHeaderName(); - break ; - - case 146 : // System.out.println("FormalParameterList ::= FormalParameterList COMMA FormalParameter"); - consumeFormalParameterList(); - break ; - - case 147 : // System.out.println("FormalParameter ::= Modifiersopt Type VariableDeclaratorId"); - // the boolean is used to know if the modifiers should be reset - consumeFormalParameter(); - break ; - - case 149 : // System.out.println("ClassTypeList ::= ClassTypeList COMMA ClassTypeElt"); - consumeClassTypeList(); - break ; - - case 150 : // System.out.println("ClassTypeElt ::= ClassType"); - consumeClassTypeElt(); - break ; - - case 151 : // System.out.println("MethodBody ::= NestedMethod LBRACE BlockStatementsopt RBRACE"); - consumeMethodBody(); - break ; - - case 152 : // System.out.println("NestedMethod ::="); - consumeNestedMethod(); - break ; - - case 153 : // System.out.println("StaticInitializer ::= StaticOnly Block"); - consumeStaticInitializer(); - break ; - - case 154 : // System.out.println("StaticOnly ::= static"); - consumeStaticOnly(); - break ; - - case 155 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader ConstructorBody"); - consumeConstructorDeclaration() ; - break ; - - case 156 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader SEMICOLON"); - consumeInvalidConstructorDeclaration() ; - break ; - - case 157 : // System.out.println("ConstructorBody ::= NestedMethod LBRACE ConstructorBlockStatementsopt RBRACE"); - consumeConstructorBody(); - break ; - - case 160 : // System.out.println("ConstructorBlockStatementsopt ::= ExplicitConstructorInvocation BlockStatements"); - consumeConstructorBlockStatements(); - break ; - - case 161 : // System.out.println("ExplicitConstructorInvocation ::= this LPAREN ArgumentListopt RPAREN SEMICOLON"); - consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.This); - break ; - - case 162 : // System.out.println("ExplicitConstructorInvocation ::= super LPAREN ArgumentListopt RPAREN SEMICOLON"); - consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.Super); - break ; - - case 163 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT super LPAREN ArgumentListopt RPAREN"); - consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.Super); - break ; - - case 164 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT super LPAREN ArgumentListopt RPAREN..."); - consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.Super); - break ; - - case 165 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT this LPAREN ArgumentListopt RPAREN..."); - consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.This); - break ; - - case 166 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT this LPAREN ArgumentListopt RPAREN..."); - consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.This); - break ; - - case 167 : // System.out.println("InterfaceDeclaration ::= InterfaceHeader InterfaceBody"); - consumeInterfaceDeclaration(); - break ; - - case 168 : // System.out.println("InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt"); - consumeInterfaceHeader(); - break ; - - case 169 : // System.out.println("InterfaceHeaderName ::= Modifiersopt interface Identifier"); - consumeInterfaceHeaderName(); - break ; - - case 171 : // System.out.println("InterfaceHeaderExtends ::= extends InterfaceTypeList"); - consumeInterfaceHeaderExtends(); - break ; - - case 174 : // System.out.println("InterfaceMemberDeclarations ::= InterfaceMemberDeclarations..."); - consumeInterfaceMemberDeclarations(); - break ; - - case 175 : // System.out.println("InterfaceMemberDeclaration ::= SEMICOLON"); - consumeEmptyInterfaceMemberDeclaration(); - break ; - - case 178 : // System.out.println("InterfaceMemberDeclaration ::= InvalidMethodDeclaration"); - ignoreMethodBody(); - break ; - - case 179 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody"); - ignoreInvalidConstructorDeclaration(true); - break ; - - case 180 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader SEMICOLON"); - ignoreInvalidConstructorDeclaration(false); - break ; - - case 186 : // System.out.println("ArrayInitializer ::= LBRACE ,opt RBRACE"); - consumeEmptyArrayInitializer(); - break ; - - case 187 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers RBRACE"); - consumeArrayInitializer(); - break ; - - case 188 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers COMMA RBRACE"); - consumeArrayInitializer(); - break ; - - case 190 : // System.out.println("VariableInitializers ::= VariableInitializers COMMA VariableInitializer"); - consumeVariableInitializers(); - break ; - - case 191 : // System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); - consumeBlock(); - break ; - - case 192 : // System.out.println("OpenBlock ::="); - consumeOpenBlock() ; - break ; - - case 194 : // System.out.println("BlockStatements ::= BlockStatements BlockStatement"); - consumeBlockStatements() ; - break ; - - case 198 : // System.out.println("BlockStatement ::= InvalidInterfaceDeclaration"); - ignoreInterfaceDeclaration(); - break ; - - case 199 : // System.out.println("LocalVariableDeclarationStatement ::= LocalVariableDeclaration SEMICOLON"); - consumeLocalVariableDeclarationStatement(); - break ; - - case 200 : // System.out.println("LocalVariableDeclaration ::= Type PushModifiers VariableDeclarators"); - consumeLocalVariableDeclaration(); - break ; - - case 201 : // System.out.println("LocalVariableDeclaration ::= Modifiers Type PushModifiers VariableDeclarators"); - consumeLocalVariableDeclaration(); - break ; - - case 202 : // System.out.println("PushModifiers ::="); - consumePushModifiers(); - break ; - - case 226 : // System.out.println("EmptyStatement ::= SEMICOLON"); - consumeEmptyStatement(); - break ; - - case 227 : // System.out.println("LabeledStatement ::= Identifier COLON Statement"); - consumeStatementLabel() ; - break ; - - case 228 : // System.out.println("LabeledStatementNoShortIf ::= Identifier COLON StatementNoShortIf"); - consumeStatementLabel() ; - break ; - - case 229 : // System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); - consumeExpressionStatement(); - break ; - - case 237 : // System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN Statement"); - consumeStatementIfNoElse(); - break ; - - case 238 : // System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN StatementNoShortIf else..."); - consumeStatementIfWithElse(); - break ; - - case 239 : // System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression RPAREN StatementNoShortIf..."); - consumeStatementIfWithElse(); - break ; - - case 240 : // System.out.println("SwitchStatement ::= switch OpenBlock LPAREN Expression RPAREN SwitchBlock"); - consumeStatementSwitch() ; - break ; - - case 241 : // System.out.println("SwitchBlock ::= LBRACE RBRACE"); - consumeEmptySwitchBlock() ; - break ; - - case 244 : // System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements SwitchLabels RBRACE"); - consumeSwitchBlock() ; - break ; - - case 246 : // System.out.println("SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement"); - consumeSwitchBlockStatements() ; - break ; - - case 247 : // System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); - consumeSwitchBlockStatement() ; - break ; - - case 249 : // System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); - consumeSwitchLabels() ; - break ; - - case 250 : // System.out.println("SwitchLabel ::= case ConstantExpression COLON"); - consumeCaseLabel(); - break ; - - case 251 : // System.out.println("SwitchLabel ::= default COLON"); - consumeDefaultLabel(); - break ; - - case 252 : // System.out.println("WhileStatement ::= while LPAREN Expression RPAREN Statement"); - consumeStatementWhile() ; - break ; - - case 253 : // System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression RPAREN StatementNoShortIf"); - consumeStatementWhile() ; - break ; - - case 254 : // System.out.println("DoStatement ::= do Statement while LPAREN Expression RPAREN SEMICOLON"); - consumeStatementDo() ; - break ; - - case 255 : // System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON Expressionopt SEMICOLON..."); - consumeStatementFor() ; - break ; - - case 256 : // System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt SEMICOLON Expressionopt SEMICOLON"); - consumeStatementFor() ; - break ; - - case 257 : // System.out.println("ForInit ::= StatementExpressionList"); - consumeForInit() ; - break ; - - case 261 : // System.out.println("StatementExpressionList ::= StatementExpressionList COMMA StatementExpression"); - consumeStatementExpressionList() ; - break ; - - case 262 : // System.out.println("AssertStatement ::= assert Expression SEMICOLON"); - consumeSimpleAssertStatement() ; - break ; - - case 263 : // System.out.println("AssertStatement ::= assert Expression COLON Expression SEMICOLON"); - consumeAssertStatement() ; - break ; - - case 264 : // System.out.println("BreakStatement ::= break SEMICOLON"); - consumeStatementBreak() ; - break ; - - case 265 : // System.out.println("BreakStatement ::= break Identifier SEMICOLON"); - consumeStatementBreakWithLabel() ; - break ; - - case 266 : // System.out.println("ContinueStatement ::= continue SEMICOLON"); - consumeStatementContinue() ; - break ; - - case 267 : // System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); - consumeStatementContinueWithLabel() ; - break ; - - case 268 : // System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); - consumeStatementReturn() ; - break ; - - case 269 : // System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); - consumeStatementThrow(); - - break ; - - case 270 : // System.out.println("SynchronizedStatement ::= OnlySynchronized LPAREN Expression RPAREN Block"); - consumeStatementSynchronized(); - break ; - - case 271 : // System.out.println("OnlySynchronized ::= synchronized"); - consumeOnlySynchronized(); - break ; - - case 272 : // System.out.println("TryStatement ::= try Block Catches"); - consumeStatementTry(false); - break ; - - case 273 : // System.out.println("TryStatement ::= try Block Catchesopt Finally"); - consumeStatementTry(true); - break ; - - case 275 : // System.out.println("Catches ::= Catches CatchClause"); - consumeCatches(); - break ; - - case 276 : // System.out.println("CatchClause ::= catch LPAREN FormalParameter RPAREN Block"); - consumeStatementCatch() ; - break ; - - case 278 : // System.out.println("PushLPAREN ::= LPAREN"); - consumeLeftParen(); - break ; - - case 279 : // System.out.println("PushRPAREN ::= RPAREN"); - consumeRightParen(); - break ; - - case 283 : // System.out.println("PrimaryNoNewArray ::= this"); - consumePrimaryNoNewArrayThis(); - break ; - - case 284 : // System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN"); - consumePrimaryNoNewArray(); - break ; - - case 287 : // System.out.println("PrimaryNoNewArray ::= Name DOT this"); - consumePrimaryNoNewArrayNameThis(); - break ; - - case 288 : // System.out.println("PrimaryNoNewArray ::= Name DOT super"); - consumePrimaryNoNewArrayNameSuper(); - break ; - - case 289 : // System.out.println("PrimaryNoNewArray ::= Name DOT class"); - consumePrimaryNoNewArrayName(); - break ; - - case 290 : // System.out.println("PrimaryNoNewArray ::= ArrayType DOT class"); - consumePrimaryNoNewArrayArrayType(); - break ; - - case 291 : // System.out.println("PrimaryNoNewArray ::= PrimitiveType DOT class"); - consumePrimaryNoNewArrayPrimitiveType(); - break ; - - case 294 : // System.out.println("AllocationHeader ::= new ClassType LPAREN ArgumentListopt RPAREN"); - consumeAllocationHeader(); - break ; - - case 295 : // System.out.println("ClassInstanceCreationExpression ::= new ClassType LPAREN ArgumentListopt RPAREN..."); - consumeClassInstanceCreationExpression(); - break ; - - case 296 : // System.out.println("ClassInstanceCreationExpression ::= Primary DOT new SimpleName LPAREN..."); - consumeClassInstanceCreationExpressionQualified() ; - break ; - - case 297 : // System.out.println("ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName new..."); - consumeClassInstanceCreationExpressionQualified() ; - break ; - - case 298 : // System.out.println("ClassInstanceCreationExpressionName ::= Name DOT"); - consumeClassInstanceCreationExpressionName() ; - break ; - - case 299 : // System.out.println("ClassBodyopt ::="); - consumeClassBodyopt(); - break ; - - case 301 : // System.out.println("EnterAnonymousClassBody ::="); - consumeEnterAnonymousClassBody(); - break ; - - case 303 : // System.out.println("ArgumentList ::= ArgumentList COMMA Expression"); - consumeArgumentList(); - break ; - - case 304 : // System.out.println("ArrayCreationExpression ::= new PrimitiveType DimWithOrWithOutExprs..."); - consumeArrayCreationExpression(); - break ; - - case 305 : // System.out.println("ArrayCreationExpression ::= new ClassOrInterfaceType DimWithOrWithOutExprs..."); - consumeArrayCreationExpression(); - break ; - - case 307 : // System.out.println("DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr"); - consumeDimWithOrWithOutExprs(); - break ; - - case 309 : // System.out.println("DimWithOrWithOutExpr ::= LBRACKET RBRACKET"); - consumeDimWithOrWithOutExpr(); - break ; - - case 310 : // System.out.println("Dims ::= DimsLoop"); - consumeDims(); - break ; - - case 313 : // System.out.println("OneDimLoop ::= LBRACKET RBRACKET"); - consumeOneDimLoop(); - break ; - - case 314 : // System.out.println("FieldAccess ::= Primary DOT Identifier"); - consumeFieldAccess(false); - break ; - - case 315 : // System.out.println("FieldAccess ::= super DOT Identifier"); - consumeFieldAccess(true); - break ; - - case 316 : // System.out.println("MethodInvocation ::= Name LPAREN ArgumentListopt RPAREN"); - consumeMethodInvocationName(); - break ; - - case 317 : // System.out.println("MethodInvocation ::= Primary DOT Identifier LPAREN ArgumentListopt RPAREN"); - consumeMethodInvocationPrimary(); - break ; - - case 318 : // System.out.println("MethodInvocation ::= super DOT Identifier LPAREN ArgumentListopt RPAREN"); - consumeMethodInvocationSuper(); - break ; - - case 319 : // System.out.println("ArrayAccess ::= Name LBRACKET Expression RBRACKET"); - consumeArrayAccess(true); - break ; - - case 320 : // System.out.println("ArrayAccess ::= PrimaryNoNewArray LBRACKET Expression RBRACKET"); - consumeArrayAccess(false); - break ; - - case 322 : // System.out.println("PostfixExpression ::= Name"); - consumePostfixExpression(); - break ; - - case 325 : // System.out.println("PostIncrementExpression ::= PostfixExpression PLUS_PLUS"); - consumeUnaryExpression(OperatorExpression.PLUS,true); - break ; - - case 326 : // System.out.println("PostDecrementExpression ::= PostfixExpression MINUS_MINUS"); - consumeUnaryExpression(OperatorExpression.MINUS,true); - break ; - - case 327 : // System.out.println("PushPosition ::="); - consumePushPosition(); - break ; - - case 330 : // System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); - consumeUnaryExpression(OperatorExpression.PLUS); - break ; - - case 331 : // System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); - consumeUnaryExpression(OperatorExpression.MINUS); - break ; - - case 333 : // System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition UnaryExpression"); - consumeUnaryExpression(OperatorExpression.PLUS,false); - break ; - - case 334 : // System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition UnaryExpression"); - consumeUnaryExpression(OperatorExpression.MINUS,false); - break ; - - case 336 : // System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition UnaryExpression"); - consumeUnaryExpression(OperatorExpression.TWIDDLE); - break ; - - case 337 : // System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition UnaryExpression"); - consumeUnaryExpression(OperatorExpression.NOT); - break ; - - case 339 : // System.out.println("CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN UnaryExpression"); - consumeCastExpression(); - break ; - - case 340 : // System.out.println("CastExpression ::= PushLPAREN Name Dims PushRPAREN UnaryExpressionNotPlusMinus"); - consumeCastExpression(); - break ; - - case 341 : // System.out.println("CastExpression ::= PushLPAREN Expression PushRPAREN UnaryExpressionNotPlusMinus"); - consumeCastExpressionLL1(); - break ; - - case 343 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression MULTIPLY UnaryExpression"); - consumeBinaryExpression(OperatorExpression.MULTIPLY); - break ; - - case 344 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression DIVIDE UnaryExpression"); - consumeBinaryExpression(OperatorExpression.DIVIDE); - break ; - - case 345 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression REMAINDER UnaryExpression"); - consumeBinaryExpression(OperatorExpression.REMAINDER); - break ; - - case 347 : // System.out.println("AdditiveExpression ::= AdditiveExpression PLUS MultiplicativeExpression"); - consumeBinaryExpression(OperatorExpression.PLUS); - break ; - - case 348 : // System.out.println("AdditiveExpression ::= AdditiveExpression MINUS MultiplicativeExpression"); - consumeBinaryExpression(OperatorExpression.MINUS); - break ; - - case 350 : // System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT AdditiveExpression"); - consumeBinaryExpression(OperatorExpression.LEFT_SHIFT); - break ; - - case 351 : // System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT AdditiveExpression"); - consumeBinaryExpression(OperatorExpression.RIGHT_SHIFT); - break ; - - case 352 : // System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT AdditiveExpression"); - consumeBinaryExpression(OperatorExpression.UNSIGNED_RIGHT_SHIFT); - break ; - - case 354 : // System.out.println("RelationalExpression ::= RelationalExpression LESS ShiftExpression"); - consumeBinaryExpression(OperatorExpression.LESS); - break ; - - case 355 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER ShiftExpression"); - consumeBinaryExpression(OperatorExpression.GREATER); - break ; - - case 356 : // System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL ShiftExpression"); - consumeBinaryExpression(OperatorExpression.LESS_EQUAL); - break ; - - case 357 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER_EQUAL ShiftExpression"); - consumeBinaryExpression(OperatorExpression.GREATER_EQUAL); - break ; - - case 358 : // System.out.println("RelationalExpression ::= RelationalExpression instanceof ReferenceType"); - consumeInstanceOfExpression(OperatorExpression.INSTANCEOF); - break ; - - case 360 : // System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL RelationalExpression"); - consumeEqualityExpression(OperatorExpression.EQUAL_EQUAL); - break ; - - case 361 : // System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL RelationalExpression"); - consumeEqualityExpression(OperatorExpression.NOT_EQUAL); - break ; - - case 363 : // System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); - consumeBinaryExpression(OperatorExpression.AND); - break ; - - case 365 : // System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR AndExpression"); - consumeBinaryExpression(OperatorExpression.XOR); - break ; - - case 367 : // System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR ExclusiveOrExpression"); - consumeBinaryExpression(OperatorExpression.OR); - break ; - - case 369 : // System.out.println("ConditionalAndExpression ::= ConditionalAndExpression AND_AND InclusiveOrExpression"); - consumeBinaryExpression(OperatorExpression.AND_AND); - break ; - - case 371 : // System.out.println("ConditionalOrExpression ::= ConditionalOrExpression OR_OR ConditionalAndExpression"); - consumeBinaryExpression(OperatorExpression.OR_OR); - break ; - - case 373 : // System.out.println("ConditionalExpression ::= ConditionalOrExpression QUESTION Expression COLON..."); - consumeConditionalExpression(OperatorExpression.QUESTIONCOLON) ; - break ; - - case 376 : // System.out.println("Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression"); - consumeAssignment(); - break ; - - case 378 : // System.out.println("Assignment ::= InvalidArrayInitializerAssignement"); - ignoreExpressionAssignment(); - break ; - - case 379 : // System.out.println("LeftHandSide ::= Name"); - consumeLeftHandSide(); - break ; - - case 382 : // System.out.println("AssignmentOperator ::= EQUAL"); - consumeAssignmentOperator(EQUAL); - break ; - - case 383 : // System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); - consumeAssignmentOperator(MULTIPLY); - break ; - - case 384 : // System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); - consumeAssignmentOperator(DIVIDE); - break ; - - case 385 : // System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); - consumeAssignmentOperator(REMAINDER); - break ; - - case 386 : // System.out.println("AssignmentOperator ::= PLUS_EQUAL"); - consumeAssignmentOperator(PLUS); - break ; - - case 387 : // System.out.println("AssignmentOperator ::= MINUS_EQUAL"); - consumeAssignmentOperator(MINUS); - break ; - - case 388 : // System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); - consumeAssignmentOperator(LEFT_SHIFT); - break ; - - case 389 : // System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); - consumeAssignmentOperator(RIGHT_SHIFT); - break ; - - case 390 : // System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); - consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT); - break ; - - case 391 : // System.out.println("AssignmentOperator ::= AND_EQUAL"); - consumeAssignmentOperator(AND); - break ; - - case 392 : // System.out.println("AssignmentOperator ::= XOR_EQUAL"); - consumeAssignmentOperator(XOR); - break ; - - case 393 : // System.out.println("AssignmentOperator ::= OR_EQUAL"); - consumeAssignmentOperator(OR); - break ; - - case 400 : // System.out.println("Expressionopt ::="); - consumeEmptyExpression(); - break ; - - case 404 : // System.out.println("ImportDeclarationsopt ::="); - consumeEmptyImportDeclarationsopt(); - break ; - - case 405 : // System.out.println("ImportDeclarationsopt ::= ImportDeclarations"); - consumeImportDeclarationsopt(); - break ; - - case 406 : // System.out.println("TypeDeclarationsopt ::="); - consumeEmptyTypeDeclarationsopt(); - break ; - - case 407 : // System.out.println("TypeDeclarationsopt ::= TypeDeclarations"); - consumeTypeDeclarationsopt(); - break ; - - case 408 : // System.out.println("ClassBodyDeclarationsopt ::="); - consumeEmptyClassBodyDeclarationsopt(); - break ; - - case 409 : // System.out.println("ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations"); - consumeClassBodyDeclarationsopt(); - break ; - - case 410 : // System.out.println("Modifiersopt ::="); - consumeDefaultModifiers(); - break ; - - case 411 : // System.out.println("Modifiersopt ::= Modifiers"); - consumeModifiers(); - break ; - - case 412 : // System.out.println("BlockStatementsopt ::="); - consumeEmptyBlockStatementsopt(); - break ; - - case 414 : // System.out.println("Dimsopt ::="); - consumeEmptyDimsopt(); - break ; - - case 416 : // System.out.println("ArgumentListopt ::="); - consumeEmptyArgumentListopt(); - break ; - - case 420 : // System.out.println("FormalParameterListopt ::="); - consumeFormalParameterListopt(); - break ; - - case 424 : // System.out.println("InterfaceMemberDeclarationsopt ::="); - consumeEmptyInterfaceMemberDeclarationsopt(); - break ; - - case 425 : // System.out.println("InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations"); - consumeInterfaceMemberDeclarationsopt(); - break ; - - case 426 : // System.out.println("NestedType ::="); - consumeNestedType(); - break ; - - case 427 : // System.out.println("ForInitopt ::="); - consumeEmptyForInitopt(); - break ; - - case 429 : // System.out.println("ForUpdateopt ::="); - consumeEmptyForUpdateopt(); - break ; - - case 433 : // System.out.println("Catchesopt ::="); - consumeEmptyCatchesopt(); - break ; - - case 435 : // System.out.println("ArrayInitializeropt ::="); - consumeEmptyArrayInitializeropt(); - break ; - - } - } - - -protected void consumeSimpleAssertStatement() { - // AssertStatement ::= 'assert' Expression ';' - expressionLengthPtr--; - pushOnAstStack(new AssertStatement(expressionStack[expressionPtr--], intStack[intPtr--])); -} - -protected void consumeSingleTypeImportDeclaration() { - // SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName ';' - - ImportReference impt = (ImportReference) astStack[astPtr]; - // flush annotations defined prior to import statements - impt.declarationEnd = endStatementPosition; - impt.declarationSourceEnd = - this.flushAnnotationsDefinedPriorTo(impt.declarationSourceEnd); - - // recovery - if (currentElement != null) { - lastCheckPoint = impt.declarationSourceEnd + 1; - currentElement = currentElement.add(impt, 0); - lastIgnoredToken = -1; - restartRecovery = true; - // used to avoid branching back into the regular automaton - } -} -protected void consumeSingleTypeImportDeclarationName() { - // SingleTypeImportDeclarationName ::= 'import' Name - /* push an ImportRef build from the last name - stored in the identifier stack. */ - - ImportReference impt; - int length; - char[][] tokens = new char[length = identifierLengthStack[identifierLengthPtr--]][]; - identifierPtr -= length; - long[] positions = new long[length]; - System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - System.arraycopy(identifierPositionStack, identifierPtr + 1, positions, 0, length); - pushOnAstStack(impt = new ImportReference(tokens, positions, false)); - - if (currentToken == TokenNameSEMICOLON){ - impt.declarationSourceEnd = scanner.currentPosition - 1; - } else { - impt.declarationSourceEnd = impt.sourceEnd; - } - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = intStack[intPtr--]; - - // recovery - if (currentElement != null){ - lastCheckPoint = impt.declarationSourceEnd+1; - currentElement = currentElement.add(impt, 0); - lastIgnoredToken = -1; - restartRecovery = true; // used to avoid branching back into the regular automaton - } -} -protected void consumeStatementBreak() { - // BreakStatement ::= 'break' ';' - // break pushs a position on intStack in case there is no label + case 150 : // System.out.println("ClassTypeElt ::= ClassType"); + consumeClassTypeElt(); + break; - pushOnAstStack(new Break(null, intStack[intPtr--], endPosition)); -} -protected void consumeStatementBreakWithLabel() { - // BreakStatement ::= 'break' Identifier ';' - // break pushs a position on intStack in case there is no label - - pushOnAstStack( - new Break( - identifierStack[identifierPtr--], - intStack[intPtr--], - endPosition)); - identifierLengthPtr--; -} -protected void consumeStatementCatch() { - // CatchClause ::= 'catch' '(' FormalParameter ')' Block + case 151 : // System.out.println("MethodBody ::= NestedMethod LBRACE BlockStatementsopt RBRACE"); + consumeMethodBody(); + break; - //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 + case 152 : // System.out.println("NestedMethod ::="); + consumeNestedMethod(); + break; - astLengthPtr--; - listLength = 0; // reset formalParameter counter (incremented for catch variable) -} -protected void consumeStatementContinue() { - // ContinueStatement ::= 'continue' ';' - // continue pushs a position on intStack in case there is no label - - pushOnAstStack( - new Continue( - null, - intStack[intPtr--], - endPosition)); -} -protected void consumeStatementContinueWithLabel() { - // ContinueStatement ::= 'continue' Identifier ';' - // continue pushs a position on intStack in case there is no label - - pushOnAstStack( - new Continue( - identifierStack[identifierPtr--], - intStack[intPtr--], - endPosition)); - identifierLengthPtr--; -} -protected void consumeStatementDo() { - // DoStatement ::= 'do' Statement 'while' '(' Expression ')' ';' - - //the 'while' pushes a value on intStack that we need to remove - intPtr--; - - //optimize the push/pop - Statement action = (Statement) astStack[astPtr]; - if (action instanceof EmptyStatement - && problemReporter.options.complianceLevel <= CompilerOptions.JDK1_3) { - expressionLengthPtr--; - astStack[astPtr] = - new DoStatement( - expressionStack[expressionPtr--], - null, - intStack[intPtr--], - endPosition); - } else { - expressionLengthPtr--; - astStack[astPtr] = - new DoStatement( - expressionStack[expressionPtr--], - action, - intStack[intPtr--], - endPosition); - } -} -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; - Statement action; - boolean scope = true; - - //statements - astLengthPtr--; // we need to consume it - action = (Statement) astStack[astPtr--]; - if (action instanceof EmptyStatement - && problemReporter.options.complianceLevel <= CompilerOptions.JDK1_3) { - action = null; - } - - //updates are on the expresion stack - if ((length = expressionLengthStack[expressionLengthPtr--]) == 0) { - updates = null; - } else { - expressionPtr -= length; - System.arraycopy( - expressionStack, - expressionPtr + 1, - updates = new Statement[length], - 0, - length); - } - - if (expressionLengthStack[expressionLengthPtr--] != 0) - cond = expressionStack[expressionPtr--]; - - //inits may be on two different stacks - if ((length = astLengthStack[astLengthPtr--]) == 0) { - inits = null; - scope = false; - } else { - if (length == -1) { //on expressionStack - scope = false; - length = expressionLengthStack[expressionLengthPtr--]; - expressionPtr -= length; - System.arraycopy( - expressionStack, - expressionPtr + 1, - inits = new Statement[length], - 0, - length); - } else { //on astStack - astPtr -= length; - System.arraycopy( - astStack, - astPtr + 1, - inits = new Statement[length], - 0, - length); - } - }; - if (action instanceof Block) { - pushOnAstStack( - new ForStatement( - inits, - cond, - updates, - action, - scope, - intStack[intPtr--], - endStatementPosition)); - } else { - pushOnAstStack( - new ForStatement( - inits, - cond, - updates, - action, - scope, - intStack[intPtr--], - endPosition)); - } -} -protected void consumeStatementIfNoElse() { - // IfThenStatement ::= 'if' '(' Expression ')' Statement - - //optimize the push/pop - expressionLengthPtr--; - Statement thenStatement = (Statement) astStack[astPtr]; - if (thenStatement instanceof Block) { - astStack[astPtr] = - new IfStatement( - expressionStack[expressionPtr--], - thenStatement, - intStack[intPtr--], - endStatementPosition); - } else if (thenStatement instanceof EmptyStatement) { - astStack[astPtr] = - new IfStatement( - expressionStack[expressionPtr--], - Block.None, - intStack[intPtr--], - endStatementPosition); - } else { - astStack[astPtr] = - new IfStatement( - expressionStack[expressionPtr--], - thenStatement, - intStack[intPtr--], - endStatementPosition); - } -} -protected void consumeStatementIfWithElse() { - // IfThenElseStatement ::= 'if' '(' Expression ')' StatementNoShortIf 'else' Statement - // IfThenElseStatementNoShortIf ::= 'if' '(' Expression ')' StatementNoShortIf 'else' StatementNoShortIf - - astLengthPtr--; // optimized {..., Then, Else } ==> {..., If } - expressionLengthPtr--; - //optimize the push/pop - Statement elseStatement = (Statement) astStack[astPtr--]; - Statement thenStatement = (Statement) astStack[astPtr]; - if (elseStatement instanceof EmptyStatement) { - elseStatement = Block.None; - } - if (thenStatement instanceof EmptyStatement) { - thenStatement = Block.None; - } - if (elseStatement instanceof Block) { - astStack[astPtr] = - new IfStatement( - expressionStack[expressionPtr--], - thenStatement, - elseStatement, - intStack[intPtr--], - endStatementPosition); - } else { - astStack[astPtr] = - new IfStatement( - expressionStack[expressionPtr--], - thenStatement, - elseStatement, - intStack[intPtr--], - endStatementPosition); - } -} -protected void consumeStatementLabel() { - // LabeledStatement ::= 'Identifier' ':' Statement - // LabeledStatementNoShortIf ::= 'Identifier' ':' StatementNoShortIf - - //optimize push/pop - - Statement stmt = (Statement) astStack[astPtr]; - if (stmt instanceof EmptyStatement) { - astStack[astPtr] = - new LabeledStatement( - identifierStack[identifierPtr], - Block.None, - (int) (identifierPositionStack[identifierPtr--] >>> 32), - endStatementPosition); - } else { - astStack[astPtr] = - new LabeledStatement( - identifierStack[identifierPtr], - stmt, - (int) (identifierPositionStack[identifierPtr--] >>> 32), - endStatementPosition); - } - identifierLengthPtr--; -} -protected void consumeStatementReturn() { - // ReturnStatement ::= 'return' Expressionopt ';' - // return pushs a position on intStack in case there is no expression - - if (expressionLengthStack[expressionLengthPtr--] != 0) { - pushOnAstStack( - new ReturnStatement( - expressionStack[expressionPtr--], - intStack[intPtr--], - endPosition) - ); - } else { - pushOnAstStack(new ReturnStatement(null, intStack[intPtr--], endPosition)); - } -} -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 s = new SwitchStatement(); - expressionLengthPtr--; - s.testExpression = expressionStack[expressionPtr--]; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - astPtr -= length; - System.arraycopy( - astStack, - astPtr + 1, - s.statements = new Statement[length], - 0, - length); - } - s.explicitDeclarations = realBlockStack[realBlockPtr--]; - pushOnAstStack(s); - intPtr--; // because of OpenBlock - s.sourceStart = intStack[intPtr--]; - s.sourceEnd = endStatementPosition; -} -protected void consumeStatementSynchronized() { - // SynchronizedStatement ::= OnlySynchronized '(' Expression ')' Block - //optimize the push/pop - - if (astLengthStack[astLengthPtr] == 0) { - astLengthStack[astLengthPtr] = 1; - expressionLengthPtr--; - astStack[++astPtr] = - new SynchronizedStatement( - expressionStack[expressionPtr--], - Block.None, - intStack[intPtr--], - endStatementPosition); - } else { - expressionLengthPtr--; - astStack[astPtr] = - new SynchronizedStatement( - expressionStack[expressionPtr--], - (Block) astStack[astPtr], - intStack[intPtr--], - endStatementPosition); - } - resetModifiers(); -} -protected void consumeStatementThrow() { - // ThrowStatement ::= 'throw' Expression ';' - expressionLengthPtr--; - pushOnAstStack(new ThrowStatement(expressionStack[expressionPtr--], intStack[intPtr--])); -} -protected void consumeStatementTry(boolean withFinally) { - //TryStatement ::= 'try' Block Catches - //TryStatement ::= 'try' Block Catchesopt Finally - - int length; - TryStatement tryStmt = new TryStatement(); - //finally - if (withFinally) { - astLengthPtr--; - tryStmt.finallyBlock = (Block) astStack[astPtr--]; - } - //catches are handle by two [see statementCatch] - if ((length = astLengthStack[astLengthPtr--]) != 0) { - if (length == 1) { - tryStmt.catchBlocks = new Block[] {(Block) astStack[astPtr--]}; - tryStmt.catchArguments = new Argument[] {(Argument) astStack[astPtr--]}; - } else { - Block[] bks = (tryStmt.catchBlocks = new Block[length]); - Argument[] args = (tryStmt.catchArguments = new Argument[length]); - while (length-- > 0) { - bks[length] = (Block) astStack[astPtr--]; - args[length] = (Argument) astStack[astPtr--]; - } - } - } - //try - astLengthPtr--; - tryStmt.tryBlock = (Block) astStack[astPtr--]; - - //positions - tryStmt.sourceEnd = endStatementPosition; - tryStmt.sourceStart = intStack[intPtr--]; - pushOnAstStack(tryStmt); -} -protected void consumeStatementWhile() { - // WhileStatement ::= 'while' '(' Expression ')' Statement - // WhileStatementNoShortIf ::= 'while' '(' Expression ')' StatementNoShortIf - - Statement action = (Statement) astStack[astPtr]; - expressionLengthPtr--; - if (action instanceof Block) { - astStack[astPtr] = - new WhileStatement( - expressionStack[expressionPtr--], - action, - intStack[intPtr--], - endStatementPosition); - } else { - if (action instanceof EmptyStatement - && problemReporter.options.complianceLevel <= CompilerOptions.JDK1_3) { - astStack[astPtr] = - new WhileStatement( - expressionStack[expressionPtr--], - null, - intStack[intPtr--], - endPosition); - } else { - astStack[astPtr] = - new WhileStatement( - expressionStack[expressionPtr--], - action, - intStack[intPtr--], - endPosition); - } - } -} -protected void consumeStaticInitializer() { - // StaticInitializer ::= StaticOnly Block - //push an Initializer - //optimize the push/pop - Initializer initializer = new Initializer((Block) astStack[astPtr], AccStatic); - astStack[astPtr] = initializer; - initializer.sourceEnd = endStatementPosition; - initializer.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); - nestedMethod[nestedType] --; - initializer.declarationSourceStart = intStack[intPtr--]; - - // recovery - if (currentElement != null){ - lastCheckPoint = initializer.declarationSourceEnd; - currentElement = currentElement.add(initializer, 0); - lastIgnoredToken = -1; - } -} -protected void consumeStaticOnly() { - // StaticOnly ::= 'static' - int savedModifiersSourceStart = modifiersSourceStart; - checkAnnotation(); // might update declaration source start - if (modifiersSourceStart >= savedModifiersSourceStart) { - modifiersSourceStart = savedModifiersSourceStart; - } - pushOnIntStack( - modifiersSourceStart >= 0 ? modifiersSourceStart : scanner.startPosition); - jumpOverMethodBody(); - nestedMethod[nestedType]++; - resetModifiers(); - - // recovery - if (currentElement != null){ - recoveredStaticInitializerStart = intStack[intPtr]; // remember start position only for static initializers - } -} -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 */ - if (scanner.wasNonExternalizedStringLiteral) { - StringLiteral[] literals = this.scanner.nonNLSStrings; - // could not reproduce, but this is the only NPE - // added preventive null check see PR 9035 - if (literals != null) { - for (int i = 0, max = literals.length; i < max; i++) { - problemReporter().nonExternalizedStringLiteral(literals[i]); - } - } - scanner.currentLine = null; - scanner.wasNonExternalizedStringLiteral = false; - } - // 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: - scanner.commentPtr = -1; - } - //System.out.println(scanner.toStringAction(type)); - switch (type) { - case TokenNameIdentifier : - pushIdentifier(); - if (scanner.useAssertAsAnIndentifier) { - long positions = identifierPositionStack[identifierPtr]; - problemReporter().useAssertAsAnIdentifier((int) (positions >>> 32), (int) positions); - } - scanner.commentPtr = -1; - break; -// case TokenNameinterface : -// adjustInterfaceModifiers(); -// //'class' is pushing two int (positions) on the stack ==> 'interface' needs to do it too.... -// pushOnIntStack(scanner.startPosition); -// pushOnIntStack(scanner.currentPosition - 1); -// scanner.commentPtr = -1; -// break; -// case TokenNameabstract : -// checkAndSetModifiers(AccAbstract); -// break; -// case TokenNamestrictfp : -// checkAndSetModifiers(AccStrictfp); -// break; -// case TokenNamefinal : -// checkAndSetModifiers(AccFinal); -// break; -// case TokenNamenative : -// checkAndSetModifiers(AccNative); -// break; -// case TokenNameprivate : -// checkAndSetModifiers(AccPrivate); -// break; -// case TokenNameprotected : -// checkAndSetModifiers(AccProtected); -// break; -// case TokenNamepublic : -// checkAndSetModifiers(AccPublic); -// break; -// case TokenNametransient : -// checkAndSetModifiers(AccTransient); -// break; -// case TokenNamevolatile : -// checkAndSetModifiers(AccVolatile); -// break; - case TokenNamestatic : - checkAndSetModifiers(AccStatic); - break; -// case TokenNamesynchronized : -// this.synchronizedBlockSourceStart = scanner.startPosition; -// checkAndSetModifiers(AccSynchronized); -// break; -// //============================== -// case TokenNamevoid : -// pushIdentifier(-T_void); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// 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 intStack -// case TokenNameboolean : -// pushIdentifier(-T_boolean); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNamebyte : -// pushIdentifier(-T_byte); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNamechar : -// pushIdentifier(-T_char); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNamedouble : -// pushIdentifier(-T_double); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNamefloat : -// pushIdentifier(-T_float); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNameint : -// pushIdentifier(-T_int); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNamelong : -// pushIdentifier(-T_long); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; -// case TokenNameshort : -// pushIdentifier(-T_short); -// pushOnIntStack(scanner.currentPosition - 1); -// pushOnIntStack(scanner.startPosition); -// scanner.commentPtr = -1; -// break; - //============================== - case TokenNameIntegerLiteral : - pushOnExpressionStack( - new IntLiteral( - scanner.getCurrentTokenSource(), - scanner.startPosition, - scanner.currentPosition - 1)); - scanner.commentPtr = -1; - break; - case TokenNameLongLiteral : - pushOnExpressionStack( - new LongLiteral( - scanner.getCurrentTokenSource(), - scanner.startPosition, - scanner.currentPosition - 1)); - scanner.commentPtr = -1; - break; - case TokenNameFloatingPointLiteral : - pushOnExpressionStack( - new FloatLiteral( - scanner.getCurrentTokenSource(), - scanner.startPosition, - scanner.currentPosition - 1)); - scanner.commentPtr = -1; - break; - case TokenNameDoubleLiteral : - pushOnExpressionStack( - new DoubleLiteral( - scanner.getCurrentTokenSource(), - scanner.startPosition, - scanner.currentPosition - 1)); - scanner.commentPtr = -1; - break; - case TokenNameCharacterLiteral : - pushOnExpressionStack( - new CharLiteral( - scanner.getCurrentTokenSource(), - scanner.startPosition, - scanner.currentPosition - 1)); - scanner.commentPtr = -1; - break; - case TokenNameStringLiteral : - StringLiteral stringLiteral = new StringLiteral( - scanner.getCurrentTokenSourceString(), - scanner.startPosition, - scanner.currentPosition - 1); - pushOnExpressionStack(stringLiteral); - scanner.commentPtr = -1; - break; - case TokenNamefalse : - pushOnExpressionStack( - new FalseLiteral(scanner.startPosition, scanner.currentPosition - 1)); - scanner.commentPtr = -1; - break; - case TokenNametrue : - pushOnExpressionStack( - new TrueLiteral(scanner.startPosition, scanner.currentPosition - 1)); - break; - case TokenNamenull : - pushOnExpressionStack( - new NullLiteral(scanner.startPosition, scanner.currentPosition - 1)); - break; - //============================ -// case TokenNamesuper : -// case TokenNamethis : -// endPosition = scanner.currentPosition - 1; -// pushOnIntStack(scanner.startPosition); -// break; -// case TokenNameassert : -// case TokenNameimport : -// case TokenNamepackage : -// case TokenNamethrow : - case TokenNamenew : - case TokenNamedo : - case TokenNameif : - case TokenNamefor : - case TokenNameswitch : -// case TokenNametry : - case TokenNamewhile : - case TokenNamebreak : - case TokenNamecontinue : - case TokenNamereturn : - case TokenNamecase : - pushOnIntStack(scanner.startPosition); - break; - case TokenNameclass : - pushOnIntStack(scanner.currentPosition - 1); - pushOnIntStack(scanner.startPosition); - break; - case TokenNamedefault : - pushOnIntStack(scanner.startPosition); - pushOnIntStack(scanner.currentPosition - 1); - break; - //let extra semantic action decide when to push - case TokenNameRBRACKET : - case TokenNamePLUS : - case TokenNameMINUS : - case TokenNameNOT : - case TokenNameTWIDDLE : - endPosition = scanner.startPosition; - break; - case TokenNamePLUS_PLUS : - case TokenNameMINUS_MINUS : - endPosition = scanner.startPosition; - endStatementPosition = scanner.currentPosition - 1; - break; - case TokenNameRBRACE: - case TokenNameSEMICOLON : - endStatementPosition = scanner.currentPosition - 1; - endPosition = scanner.startPosition - 1; - //the item is not part of the potential futur expression/statement - break; - // in order to handle ( expression) ////// (cast)expression///// foo(x) - case TokenNameRPAREN : - rParenPos = scanner.currentPosition - 1; // position of the end of right parenthesis (in case of unicode \u0029) lex00101 - break; - case TokenNameLPAREN : - lParenPos = scanner.startPosition; - break; - // case TokenNameQUESTION : - // 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 : - // case TokenNameLESS : - } -} -protected void consumeTypeDeclarations() { - // TypeDeclarations ::= TypeDeclarations TypeDeclaration - concatNodeLists(); -} -protected void consumeTypeDeclarationsopt() { - // TypeDeclarationsopt ::= TypeDeclarations - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - astPtr -= length; - System.arraycopy(astStack, astPtr + 1, compilationUnit.types = new TypeDeclaration[length], 0, length); - } -} -protected void consumeTypeImportOnDemandDeclaration() { - // TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName ';' - - ImportReference impt = (ImportReference) astStack[astPtr]; - // flush annotations defined prior to import statements - impt.declarationEnd = endStatementPosition; - impt.declarationSourceEnd = - this.flushAnnotationsDefinedPriorTo(impt.declarationSourceEnd); - - // recovery - if (currentElement != null) { - lastCheckPoint = impt.declarationSourceEnd + 1; - currentElement = currentElement.add(impt, 0); - restartRecovery = true; - lastIgnoredToken = -1; - // used to avoid branching back into the regular automaton - } -} -protected void consumeTypeImportOnDemandDeclarationName() { - // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' - /* push an ImportRef build from the last name - stored in the identifier stack. */ - - ImportReference impt; - int length; - char[][] tokens = new char[length = identifierLengthStack[identifierLengthPtr--]][]; - identifierPtr -= length; - long[] positions = new long[length]; - System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - System.arraycopy(identifierPositionStack, identifierPtr + 1, positions, 0, length); - pushOnAstStack(impt = new ImportReference(tokens, positions, true)); - - if (currentToken == TokenNameSEMICOLON){ - impt.declarationSourceEnd = scanner.currentPosition - 1; - } else { - impt.declarationSourceEnd = impt.sourceEnd; - } - impt.declarationEnd = impt.declarationSourceEnd; - //endPosition is just before the ; - impt.declarationSourceStart = intStack[intPtr--]; - - // recovery - if (currentElement != null){ - lastCheckPoint = impt.declarationSourceEnd+1; - currentElement = currentElement.add(impt, 0); - lastIgnoredToken = -1; - restartRecovery = true; // used to avoid branching back into the regular automaton - } -} -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 ............ - - //intStack have the position of the operator - - Expression r, exp = expressionStack[expressionPtr]; - if (op == MINUS) { - if ((exp instanceof IntLiteral) && (((IntLiteral) exp).mayRepresentMIN_VALUE())) { - r = expressionStack[expressionPtr] = new IntLiteralMinValue(); - } else { - if ((exp instanceof LongLiteral) && (((LongLiteral) exp).mayRepresentMIN_VALUE())) { - r = expressionStack[expressionPtr] = new LongLiteralMinValue(); - } else { - r = expressionStack[expressionPtr] = new UnaryExpression(exp, op); - } - } - } else { - r = expressionStack[expressionPtr] = new UnaryExpression(exp, op); - } - r.sourceStart = intStack[intPtr--]; - r.sourceEnd = exp.sourceEnd; -} -protected void consumeUnaryExpression(int op, boolean post) { - // PreIncrementExpression ::= '++' PushPosition UnaryExpression - // PreDecrementExpression ::= '--' PushPosition UnaryExpression - - // ++ and -- operators - //optimize the push/pop - - //intStack has the position of the operator when prefix - - Expression leftHandSide = expressionStack[expressionPtr]; - if (leftHandSide instanceof Reference) { - // ++foo()++ is unvalid - if (post) { - expressionStack[expressionPtr] = - new PostfixExpression( - leftHandSide, - IntLiteral.One, - op, - endStatementPosition); - } else { - expressionStack[expressionPtr] = - new PrefixExpression( - leftHandSide, - IntLiteral.One, - op, - intStack[intPtr--]); - } - } else { - //the ++ or the -- is NOT taken into account if code gen proceeds - if (!post) { - intPtr--; - } - problemReporter().invalidUnaryExpression(leftHandSide); - } -} -protected void consumeVariableDeclarators() { - // VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator - optimizedConcatNodeLists(); -} -protected void consumeVariableInitializers() { - // VariableInitializers ::= VariableInitializers ',' VariableInitializer - concatExpressionLists(); -} -protected TypeReference copyDims(TypeReference typeRef, int dim) { - return typeRef.copyDims(dim); -} -protected FieldDeclaration createFieldDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { - return new FieldDeclaration(null, name, sourceStart, sourceEnd); -} + case 153 : // System.out.println("StaticInitializer ::= StaticOnly Block"); + consumeStaticInitializer(); + break; -protected LocalDeclaration createLocalDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { - return new LocalDeclaration(null, name, sourceStart, sourceEnd); -} + case 154 : // System.out.println("StaticOnly ::= static"); + consumeStaticOnly(); + break; -public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) { - - CompilationUnitDeclaration parsedUnit; - boolean old = diet; - try { - diet = true; - parsedUnit = parse(sourceUnit, compilationResult); - } - finally { - diet = old; - } - return parsedUnit; -} -protected void dispatchDeclarationInto(int length) { - /* they are length on astStack that should go into - methods fields constructors lists of the typeDecl - - Return if there is a constructor declaration in the methods declaration */ - - - // Looks for the size of each array . - - if (length == 0) - return; - int[] flag = new int[length + 1]; //plus one -- see - int size1 = 0, size2 = 0, size3 = 0; - for (int i = length - 1; i >= 0; i--) { - AstNode astNode = astStack[astPtr--]; - if (astNode instanceof AbstractMethodDeclaration) { - //methods and constructors have been regrouped into one single list - flag[i] = 3; - size2++; - } else { - if (astNode instanceof TypeDeclaration) { - flag[i] = 4; - size3++; - } else { - //field - flag[i] = 1; - size1++; - } - } - } - - //arrays creation - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - if (size1 != 0) - typeDecl.fields = new FieldDeclaration[size1]; - if (size2 != 0) - typeDecl.methods = new AbstractMethodDeclaration[size2]; - if (size3 != 0) - typeDecl.memberTypes = new MemberTypeDeclaration[size3]; - - //arrays fill up - size1 = size2 = size3 = 0; - int flagI = flag[0], start = 0; - int length2; - for (int end = 0; end <= length; end++) // the plus one allows to - { - if (flagI != flag[end]) //treat the last element as a ended flag..... - { //array copy - switch (flagI) { - case 1 : - size1 += (length2 = end - start); - System.arraycopy( - astStack, - astPtr + start + 1, - typeDecl.fields, - size1 - length2, - length2); - break; - case 3 : - size2 += (length2 = end - start); - System.arraycopy( - astStack, - astPtr + start + 1, - typeDecl.methods, - size2 - length2, - length2); - break; - case 4 : - size3 += (length2 = end - start); - System.arraycopy( - astStack, - 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 CompilationUnitDeclaration endParse(int act) { - - this.lastAct = act; - - if (currentElement != null){ - currentElement.topElement().updateParseTree(); - if (VERBOSE_RECOVERY){ - System.out.print(Util.bind("parser.syntaxRecovery")); //$NON-NLS-1$ - System.out.println("--------------------------"); //$NON-NLS-1$ - System.out.println(compilationUnit); - System.out.println("----------------------------------"); //$NON-NLS-1$ - } - } else { - if (diet & VERBOSE_RECOVERY){ - System.out.print(Util.bind("parser.regularParse")); //$NON-NLS-1$ - System.out.println("--------------------------"); //$NON-NLS-1$ - System.out.println(compilationUnit); - System.out.println("----------------------------------"); //$NON-NLS-1$ - } - } - if (scanner.recordLineSeparator) { - compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); - } - return compilationUnit; -} -/* - * Flush annotations defined prior to a given positions. - * - * Note: annotations are stacked in syntactical order - * - * Either answer given , or the end position of a comment line - * immediately following the (same line) - * - * e.g. - * void foo(){ - * } // end of method foo - */ - -public int flushAnnotationsDefinedPriorTo(int position) { - - int lastAnnotationIndex = scanner.commentPtr; - if (lastAnnotationIndex < 0) return position; // no comment - - // compute the index of the first obsolete comment - int index = lastAnnotationIndex; - int validCount = 0; - while (index >= 0){ - int commentEnd = scanner.commentStops[index]; - if (commentEnd < 0) commentEnd = -commentEnd; // negative end position for non-javadoc comments - if (commentEnd <= position){ - break; - } - index--; - validCount++; - } - // if the source at is immediately followed by a line comment, then - // flush this comment and shift to the comment end. - if (validCount > 0){ - int immediateCommentEnd = -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 (scanner.getLineNumber(position) == scanner.getLineNumber(immediateCommentEnd)){ - position = immediateCommentEnd; - validCount--; // flush this comment - index++; - } - } - } - // position can be located in the middle of a line break - // this is a bug on Windows platform only. - // http://dev.eclipse.org/bugs/show_bug.cgi?id=10557 - char[] source = scanner.source; - - if ((position < source.length) - && (source[position] == '\r') - && ((position + 1) < source.length) - && (source[position + 1] == '\n')) { - position++; - } - if (index < 0) return position; // no obsolete comment - - if (validCount > 0){ // move valid comment infos, overriding obsolete comment infos - System.arraycopy(scanner.commentStarts, index + 1, scanner.commentStarts, 0, validCount); - System.arraycopy(scanner.commentStops, index + 1, scanner.commentStops, 0, validCount); - } - scanner.commentPtr = validCount - 1; - return position; -} -public final 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 ::= '++' CompilationUnit - // 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 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 = scanner.commentPtr; i <= max; i++){ - // javadoc only (non javadoc comment have negative end positions.) - if (scanner.commentStops[i] > 0){ - javadocCount++; - } - } - if (javadocCount == 0) return null; - - int[] positions = new int[2*javadocCount]; - int index = 0; - for (int i = 0, max = scanner.commentPtr; i <= max; i++){ - // javadoc only (non javadoc comment have negative end positions.) - if (scanner.commentStops[i] > 0){ - positions[index++] = scanner.commentStarts[i]; - positions[index++] = scanner.commentStops[i]-1; //stop is one over - } - } - return positions; -} - protected 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. - } - - //real parse of the method.... - this.scanner.setSource( - unit.compilationResult.compilationUnit.getContents()); - if (unit.types != null) { - for (int i = unit.types.length; --i >= 0;) - unit.types[i].parseMethod(this, unit); - } - } -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*/ - - int length; - TypeReference ref; - if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { - // single variable reference - if (dim == 0) { - ref = - new SingleTypeReference( - identifierStack[identifierPtr], - identifierPositionStack[identifierPtr--]); - } else { - ref = - new ArrayTypeReference( - identifierStack[identifierPtr], - dim, - identifierPositionStack[identifierPtr--]); - ref.sourceEnd = endPosition; - } - } else { - if (length < 0) { //flag for precompiled type reference on base types - ref = TypeReference.baseTypeReference(-length, dim); - ref.sourceStart = intStack[intPtr--]; - if (dim == 0) { - ref.sourceEnd = intStack[intPtr--]; - } else { - intPtr--; - ref.sourceEnd = endPosition; - } - } else { //Qualified variable reference - 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) { - ref = new QualifiedTypeReference(tokens, positions); - } else { - ref = new ArrayQualifiedTypeReference(tokens, dim, positions); - ref.sourceEnd = endPosition; - } - } - }; - return ref; -} -protected Expression getTypeReference(Expression exp) { - - exp.bits &= ~AstNode.RestrictiveFlagMASK; - exp.bits |= TYPE; - return exp; -} -protected NameReference getUnspecifiedReference() { - /* build a (unspecified) NameReference which may be qualified*/ - - int length; - NameReference ref; - if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) - // single variable reference - ref = - new SingleNameReference( - identifierStack[identifierPtr], - identifierPositionStack[identifierPtr--]); - else - //Qualified variable reference - { - char[][] tokens = new char[length][]; - identifierPtr -= length; - System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - ref = - new QualifiedNameReference(tokens, - (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart - (int) identifierPositionStack[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 = identifierLengthStack[identifierLengthPtr--]) == 1) { - // single variable reference - ref = - new SingleNameReference( - identifierStack[identifierPtr], - identifierPositionStack[identifierPtr--]); - ref.bits &= ~AstNode.RestrictiveFlagMASK; - ref.bits |= LOCAL | 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][]; - identifierPtr -= length; - System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); - ref = new QualifiedNameReference( - tokens, - (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart - (int) identifierPositionStack[identifierPtr + length]); // sourceEnd - ref.bits &= ~AstNode.RestrictiveFlagMASK; - ref.bits |= LOCAL | FIELD; - return ref; -} -public void goForBlockStatementsOrMethodHeaders() { - //tells the scanner to go for block statements or method headers parsing + case 155 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader ConstructorBody"); + consumeConstructorDeclaration(); + break; - firstToken = TokenNameMULTIPLY; - scanner.recordLineSeparator = false; -} -public void goForClassBodyDeclarations() { - //tells the scanner to go for any body declarations parsing + case 156 : // System.out.println("ConstructorDeclaration ::= ConstructorHeader SEMICOLON"); + consumeInvalidConstructorDeclaration(); + break; - firstToken = TokenNameAND; - scanner.recordLineSeparator = true; -} -public void goForCompilationUnit(){ - //tells the scanner to go for compilation unit parsing - - firstToken = TokenNamePLUS_PLUS ; - scanner.linePtr = -1; - scanner.recordLineSeparator = true; - scanner.currentLine= null; - scanner.lines= new ArrayList(); -} -public void goForConstructorBody(){ - //tells the scanner to go for compilation unit parsing + case 157 : // System.out.println("ConstructorBody ::= NestedMethod LBRACE ConstructorBlockStatementsopt RBRACE"); + consumeConstructorBody(); + break; - firstToken = TokenNameEQUAL_EQUAL ; - scanner.recordLineSeparator = false; -} -public void goForExpression() { - //tells the scanner to go for an expression parsing + case 160 : // System.out.println("ConstructorBlockStatementsopt ::= ExplicitConstructorInvocation BlockStatements"); + consumeConstructorBlockStatements(); + break; - firstToken = TokenNameREMAINDER; - scanner.recordLineSeparator = false; -} -public void goForFieldDeclaration(){ - //tells the scanner to go for field declaration parsing + case 161 : // System.out.println("ExplicitConstructorInvocation ::= this LPAREN ArgumentListopt RPAREN SEMICOLON"); + consumeExplicitConstructorInvocation(0, ExplicitConstructorCall.This); + break; - firstToken = TokenNameAND_AND ; - scanner.recordLineSeparator = true; -} -public void goForGenericMethodDeclaration(){ - //tells the scanner to go for generic method declarations parsing + case 162 : // System.out.println("ExplicitConstructorInvocation ::= super LPAREN ArgumentListopt RPAREN SEMICOLON"); + consumeExplicitConstructorInvocation(0, ExplicitConstructorCall.Super); + break; - firstToken = TokenNameDIVIDE; - scanner.recordLineSeparator = true; -} -public void goForHeaders(){ - //tells the scanner to go for headers only parsing + case 163 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT super LPAREN ArgumentListopt RPAREN"); + consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.Super); + break; - firstToken = TokenNameUNSIGNED_RIGHT_SHIFT; - scanner.recordLineSeparator = true; -} -public void goForImportDeclaration(){ - //tells the scanner to go for import declaration parsing + case 164 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT super LPAREN ArgumentListopt RPAREN..."); + consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.Super); + break; - firstToken = TokenNameOR_OR ; - scanner.recordLineSeparator = true; -} -public void goForInitializer(){ - //tells the scanner to go for initializer parsing + case 165 : // System.out.println("ExplicitConstructorInvocation ::= Primary DOT this LPAREN ArgumentListopt RPAREN..."); + consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.This); + break; - firstToken = TokenNameRIGHT_SHIFT ; - scanner.recordLineSeparator = false; -} -public void goForMethodBody(){ - //tells the scanner to go for method body parsing + case 166 : // System.out.println("ExplicitConstructorInvocation ::= Name DOT this LPAREN ArgumentListopt RPAREN..."); + consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.This); + break; - firstToken = TokenNameMINUS_MINUS ; - scanner.recordLineSeparator = false; -} -public void goForPackageDeclaration() { - //tells the scanner to go for package declaration parsing + case 167 : // System.out.println("InterfaceDeclaration ::= InterfaceHeader InterfaceBody"); + consumeInterfaceDeclaration(); + break; - firstToken = TokenNameQUESTION; - scanner.recordLineSeparator = true; -} -public void goForTypeDeclaration() { - //tells the scanner to go for type (interface or class) declaration parsing + case 168 : // System.out.println("InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt"); + consumeInterfaceHeader(); + break; - firstToken = TokenNamePLUS; - scanner.recordLineSeparator = true; -} -public final static void grammar(){ -/* ---main options -%options ACTION, AN=JavaAction.java, GP=java, -%options FILE-PREFIX=java, ESCAPE=$, PREFIX=TokenName, OUTPUT-SIZE=125 , -%options NOGOTO-DEFAULT, SINGLE-PRODUCTIONS, LALR=1 , TABLE=TIME , - ---error recovering options..... -%options ERROR_MAPS - ---grammar understanding options -%options first follow -%options TRACE=FULL , -%options VERBOSE - ---Usefull macros helping reading/writing semantic actions -$Define -$putCase -/. case $rule_number : // System.out.println("$rule_text"); - ./ - -$break -/. - break ; -./ - --- here it starts really ------------------------------------------ -$Terminals - - Identifier - - abstract assert boolean break byte case catch char class - continue default do double else extends false final finally float - for if implements import instanceof int - interface long native new null package private - protected public return short static strictfp super switch - synchronized this throw throws transient true try void - volatile while - - IntegerLiteral - LongLiteral - FloatingPointLiteral - DoubleLiteral - CharacterLiteral - StringLiteral - - PLUS_PLUS - MINUS_MINUS - EQUAL_EQUAL - LESS_EQUAL - GREATER_EQUAL - NOT_EQUAL - LEFT_SHIFT - RIGHT_SHIFT - UNSIGNED_RIGHT_SHIFT - PLUS_EQUAL - MINUS_EQUAL - MULTIPLY_EQUAL - DIVIDE_EQUAL - AND_EQUAL - OR_EQUAL - XOR_EQUAL - REMAINDER_EQUAL - LEFT_SHIFT_EQUAL - RIGHT_SHIFT_EQUAL - UNSIGNED_RIGHT_SHIFT_EQUAL - OR_OR - AND_AND - PLUS - MINUS - NOT - REMAINDER - XOR - AND - MULTIPLY - OR - TWIDDLE - DIVIDE - GREATER - LESS - LPAREN - RPAREN - LBRACE - RBRACE - LBRACKET - RBRACKET - SEMICOLON - QUESTION - COLON - COMMA - DOT - EQUAL - --- BodyMarker - -$Alias - - '++' ::= PLUS_PLUS - '--' ::= MINUS_MINUS - '==' ::= EQUAL_EQUAL - '<=' ::= LESS_EQUAL - '>=' ::= GREATER_EQUAL - '!=' ::= NOT_EQUAL - '<<' ::= LEFT_SHIFT - '>>' ::= RIGHT_SHIFT - '>>>' ::= UNSIGNED_RIGHT_SHIFT - '+=' ::= PLUS_EQUAL - '-=' ::= MINUS_EQUAL - '*=' ::= MULTIPLY_EQUAL - '/=' ::= DIVIDE_EQUAL - '&=' ::= AND_EQUAL - '|=' ::= OR_EQUAL - '^=' ::= XOR_EQUAL - '%=' ::= REMAINDER_EQUAL - '<<=' ::= LEFT_SHIFT_EQUAL - '>>=' ::= RIGHT_SHIFT_EQUAL - '>>>=' ::= UNSIGNED_RIGHT_SHIFT_EQUAL - '||' ::= OR_OR - '&&' ::= AND_AND - - '+' ::= PLUS - '-' ::= MINUS - '!' ::= NOT - '%' ::= REMAINDER - '^' ::= XOR - '&' ::= AND - '*' ::= MULTIPLY - '|' ::= OR - '~' ::= TWIDDLE - '/' ::= DIVIDE - '>' ::= GREATER - '<' ::= LESS - '(' ::= LPAREN - ')' ::= RPAREN - '{' ::= LBRACE - '}' ::= RBRACE - '[' ::= LBRACKET - ']' ::= RBRACKET - ';' ::= SEMICOLON - '?' ::= QUESTION - ':' ::= COLON - ',' ::= COMMA - '.' ::= DOT - '=' ::= EQUAL - -$Start - Goal - -$Rules - -/. // This method is part of an automatic generation : do NOT edit-modify -protected void consumeRule(int act) { - switch ( act ) { -./ - - - -Goal ::= '++' CompilationUnit -Goal ::= '--' MethodBody -Goal ::= '==' ConstructorBody --- Initializer -Goal ::= '>>' StaticInitializer -Goal ::= '>>' Initializer --- error recovery -Goal ::= '>>>' Headers -Goal ::= '*' BlockStatements -Goal ::= '*' MethodPushModifiersHeader -Goal ::= '*' CatchHeader --- JDOM -Goal ::= '&&' FieldDeclaration -Goal ::= '||' ImportDeclaration -Goal ::= '?' PackageDeclaration -Goal ::= '+' TypeDeclaration -Goal ::= '/' GenericMethodDeclaration -Goal ::= '&' ClassBodyDeclaration --- code snippet -Goal ::= '%' Expression --- completion parser -Goal ::= '!' ConstructorBlockStatementsopt -Goal ::= '~' BlockStatementsopt - -Literal -> IntegerLiteral -Literal -> LongLiteral -Literal -> FloatingPointLiteral -Literal -> DoubleLiteral -Literal -> CharacterLiteral -Literal -> StringLiteral -Literal -> null -Literal -> BooleanLiteral -BooleanLiteral -> true -BooleanLiteral -> false - -------------------------------------------------------------- -------------------------------------------------------------- ---a Type results in both a push of its dimension(s) and its name(s). - -Type ::= PrimitiveType - /.$putCase consumePrimitiveType(); $break ./ -Type -> ReferenceType - -PrimitiveType -> NumericType -NumericType -> IntegralType -NumericType -> FloatingPointType - -PrimitiveType -> 'boolean' -PrimitiveType -> 'void' -IntegralType -> 'byte' -IntegralType -> 'short' -IntegralType -> 'int' -IntegralType -> 'long' -IntegralType -> 'char' -FloatingPointType -> 'float' -FloatingPointType -> 'double' - -ReferenceType ::= ClassOrInterfaceType -/.$putCase consumeReferenceType(); $break ./ -ReferenceType -> ArrayType -- here a push of dimensions is done, that explains the two previous push 0 - -ClassOrInterfaceType -> Name - --- --- These rules have been rewritten to avoid some conflicts introduced --- by adding the 1.1 features --- --- ArrayType ::= PrimitiveType '[' ']' --- ArrayType ::= Name '[' ']' --- ArrayType ::= ArrayType '[' ']' --- - -ArrayType ::= PrimitiveType Dims -ArrayType ::= Name Dims - -ClassType -> ClassOrInterfaceType - - --------------------------------------------------------------- --------------------------------------------------------------- - -Name -> SimpleName -Name -> QualifiedName - -SimpleName -> 'Identifier' - -QualifiedName ::= Name '.' SimpleName -/.$putCase consumeQualifiedName(); $break ./ - -CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt TypeDeclarationsopt -/.$putCase consumeCompilationUnit(); $break ./ - -EnterCompilationUnit ::= $empty -/.$putCase consumeEnterCompilationUnit(); $break ./ - -Headers -> Header -Headers ::= Headers Header - -Header -> ImportDeclaration -Header -> PackageDeclaration -Header -> ClassHeader -Header -> InterfaceHeader -Header -> StaticInitializer -Header -> MethodHeader -Header -> ConstructorHeader -Header -> FieldDeclaration -Header -> AllocationHeader - -CatchHeader ::= 'catch' '(' FormalParameter ')' '{' -/.$putCase consumeCatchHeader(); $break ./ - -ImportDeclarations -> ImportDeclaration -ImportDeclarations ::= ImportDeclarations ImportDeclaration -/.$putCase consumeImportDeclarations(); $break ./ - -TypeDeclarations -> TypeDeclaration -TypeDeclarations ::= TypeDeclarations TypeDeclaration -/.$putCase consumeTypeDeclarations(); $break ./ - -PackageDeclaration ::= PackageDeclarationName ';' -/.$putCase consumePackageDeclaration(); $break ./ - -PackageDeclarationName ::= 'package' Name -/.$putCase consumePackageDeclarationName(); $break ./ - -ImportDeclaration -> SingleTypeImportDeclaration -ImportDeclaration -> TypeImportOnDemandDeclaration - -SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName ';' -/.$putCase consumeSingleTypeImportDeclaration(); $break ./ - -SingleTypeImportDeclarationName ::= 'import' Name -/.$putCase consumeSingleTypeImportDeclarationName(); $break ./ - -TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName ';' -/.$putCase consumeTypeImportOnDemandDeclaration(); $break ./ - -TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' -/.$putCase consumeTypeImportOnDemandDeclarationName(); $break ./ - -TypeDeclaration -> ClassDeclaration -TypeDeclaration -> InterfaceDeclaration --- this declaration in part of a list od declaration and we will --- use and optimized list length calculation process --- thus we decrement the number while it will be incremend..... -TypeDeclaration ::= ';' -/. $putCase consumeEmptyTypeDeclaration(); $break ./ - ---18.7 Only in the LALR(1) Grammar - -Modifiers ::= Modifier -Modifiers ::= Modifiers Modifier - -Modifier -> 'public' -Modifier -> 'protected' -Modifier -> 'private' -Modifier -> 'static' -Modifier -> 'abstract' -Modifier -> 'final' -Modifier -> 'native' -Modifier -> 'synchronized' -Modifier -> 'transient' -Modifier -> 'volatile' -Modifier -> 'strictfp' - ---18.8 Productions from 8: Class Declarations ---ClassModifier ::= --- 'abstract' --- | 'final' --- | 'public' ---18.8.1 Productions from 8.1: Class Declarations + case 169 : // System.out.println("InterfaceHeaderName ::= Modifiersopt interface Identifier"); + consumeInterfaceHeaderName(); + break; -ClassDeclaration ::= ClassHeader ClassBody -/.$putCase consumeClassDeclaration(); $break ./ + case 171 : // System.out.println("InterfaceHeaderExtends ::= extends InterfaceTypeList"); + consumeInterfaceHeaderExtends(); + break; -ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt -/.$putCase consumeClassHeader(); $break ./ - -ClassHeaderName ::= Modifiersopt 'class' 'Identifier' -/.$putCase consumeClassHeaderName(); $break ./ - -ClassHeaderExtends ::= 'extends' ClassType -/.$putCase consumeClassHeaderExtends(); $break ./ - -ClassHeaderImplements ::= 'implements' InterfaceTypeList -/.$putCase consumeClassHeaderImplements(); $break ./ - -InterfaceTypeList -> InterfaceType -InterfaceTypeList ::= InterfaceTypeList ',' InterfaceType -/.$putCase consumeInterfaceTypeList(); $break ./ - -InterfaceType ::= ClassOrInterfaceType -/.$putCase consumeInterfaceType(); $break ./ - -ClassBody ::= '{' ClassBodyDeclarationsopt '}' - -ClassBodyDeclarations ::= ClassBodyDeclaration -ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration -/.$putCase consumeClassBodyDeclarations(); $break ./ - -ClassBodyDeclaration -> ClassMemberDeclaration -ClassBodyDeclaration -> StaticInitializer -ClassBodyDeclaration -> ConstructorDeclaration ---1.1 feature -ClassBodyDeclaration ::= Diet NestedMethod Block -/.$putCase consumeClassBodyDeclaration(); $break ./ -Diet ::= $empty -/.$putCase consumeDiet(); $break./ - -Initializer ::= Diet NestedMethod Block -/.$putCase consumeClassBodyDeclaration(); $break ./ - -ClassMemberDeclaration -> FieldDeclaration -ClassMemberDeclaration -> MethodDeclaration ---1.1 feature -ClassMemberDeclaration -> ClassDeclaration ---1.1 feature -ClassMemberDeclaration -> InterfaceDeclaration - --- Empty declarations are not valid Java ClassMemberDeclarations. --- However, since the current (2/14/97) Java compiler accepts them --- (in fact, some of the official tests contain this erroneous --- syntax) - -GenericMethodDeclaration -> MethodDeclaration -GenericMethodDeclaration -> ConstructorDeclaration - -ClassMemberDeclaration ::= ';' -/.$putCase consumeEmptyClassMemberDeclaration(); $break./ - ---18.8.2 Productions from 8.3: Field Declarations ---VariableModifier ::= --- 'public' --- | 'protected' --- | 'private' --- | 'static' --- | 'final' --- | 'transient' --- | 'volatile' + case 174 : // System.out.println("InterfaceMemberDeclarations ::= InterfaceMemberDeclarations..."); + consumeInterfaceMemberDeclarations(); + break; -FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' -/.$putCase consumeFieldDeclaration(); $break ./ + case 175 : // System.out.println("InterfaceMemberDeclaration ::= SEMICOLON"); + consumeEmptyInterfaceMemberDeclaration(); + break; -VariableDeclarators -> VariableDeclarator -VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator -/.$putCase consumeVariableDeclarators(); $break ./ + case 178 : // System.out.println("InterfaceMemberDeclaration ::= InvalidMethodDeclaration"); + ignoreMethodBody(); + break; -VariableDeclarator ::= VariableDeclaratorId EnterVariable ExitVariableWithoutInitialization + case 179 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody"); + ignoreInvalidConstructorDeclaration(true); + break; -VariableDeclarator ::= VariableDeclaratorId EnterVariable '=' ForceNoDiet VariableInitializer RestoreDiet ExitVariableWithInitialization + case 180 : // System.out.println("InvalidConstructorDeclaration ::= ConstructorHeader SEMICOLON"); + ignoreInvalidConstructorDeclaration(false); + break; -EnterVariable ::= $empty -/.$putCase consumeEnterVariable(); $break ./ + case 186 : // System.out.println("ArrayInitializer ::= LBRACE ,opt RBRACE"); + consumeEmptyArrayInitializer(); + break; -ExitVariableWithInitialization ::= $empty -/.$putCase consumeExitVariableWithInitialization(); $break ./ + case 187 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers RBRACE"); + consumeArrayInitializer(); + break; -ExitVariableWithoutInitialization ::= $empty -/.$putCase consumeExitVariableWithoutInitialization(); $break ./ + case 188 : // System.out.println("ArrayInitializer ::= LBRACE VariableInitializers COMMA RBRACE"); + consumeArrayInitializer(); + break; -ForceNoDiet ::= $empty -/.$putCase consumeForceNoDiet(); $break ./ -RestoreDiet ::= $empty -/.$putCase consumeRestoreDiet(); $break ./ + case 190 : // System.out.println("VariableInitializers ::= VariableInitializers COMMA VariableInitializer"); + consumeVariableInitializers(); + break; -VariableDeclaratorId ::= 'Identifier' Dimsopt + case 191 : // System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); + consumeBlock(); + break; -VariableInitializer -> Expression -VariableInitializer -> ArrayInitializer + case 192 : // System.out.println("OpenBlock ::="); + consumeOpenBlock(); + break; ---18.8.3 Productions from 8.4: Method Declarations ---MethodModifier ::= --- 'public' --- | 'protected' --- | 'private' --- | 'static' --- | 'abstract' --- | 'final' --- | 'native' --- | 'synchronized' --- + case 194 : // System.out.println("BlockStatements ::= BlockStatements BlockStatement"); + consumeBlockStatements(); + break; -MethodDeclaration -> AbstractMethodDeclaration -MethodDeclaration ::= MethodHeader MethodBody -/.$putCase // set to true to consume a method with a body - consumeMethodDeclaration(true); $break ./ + case 198 : // System.out.println("BlockStatement ::= InvalidInterfaceDeclaration"); + ignoreInterfaceDeclaration(); + break; -AbstractMethodDeclaration ::= MethodHeader ';' -/.$putCase // set to false to consume a method without body - consumeMethodDeclaration(false); $break ./ + case 199 : // System.out.println("LocalVariableDeclarationStatement ::= LocalVariableDeclaration SEMICOLON"); + consumeLocalVariableDeclarationStatement(); + break; -MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims MethodHeaderThrowsClauseopt -/.$putCase consumeMethodHeader(); $break ./ + case 200 : // System.out.println("LocalVariableDeclaration ::= Type PushModifiers VariableDeclarators"); + consumeLocalVariableDeclaration(); + break; -MethodPushModifiersHeader ::= MethodPushModifiersHeaderName MethodHeaderParameters MethodHeaderExtendedDims MethodHeaderThrowsClauseopt -/.$putCase consumeMethodHeader(); $break ./ + case 201 : // System.out.println("LocalVariableDeclaration ::= Modifiers Type PushModifiers VariableDeclarators"); + consumeLocalVariableDeclaration(); + break; -MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers 'Identifier' '(' -/.$putCase consumeMethodPushModifiersHeaderName(); $break ./ + case 202 : // System.out.println("PushModifiers ::="); + consumePushModifiers(); + break; -MethodPushModifiersHeaderName ::= Type PushModifiers 'Identifier' '(' -/.$putCase consumeMethodPushModifiersHeaderName(); $break ./ + case 226 : // System.out.println("EmptyStatement ::= SEMICOLON"); + consumeEmptyStatement(); + break; -MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' -/.$putCase consumeMethodHeaderName(); $break ./ + case 227 : // System.out.println("LabeledStatement ::= Identifier COLON Statement"); + consumeStatementLabel(); + break; -MethodHeaderParameters ::= FormalParameterListopt ')' -/.$putCase consumeMethodHeaderParameters(); $break ./ + case 228 : // System.out.println("LabeledStatementNoShortIf ::= Identifier COLON StatementNoShortIf"); + consumeStatementLabel(); + break; -MethodHeaderExtendedDims ::= Dimsopt -/.$putCase consumeMethodHeaderExtendedDims(); $break ./ + case 229 : // System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); + consumeExpressionStatement(); + break; -MethodHeaderThrowsClause ::= 'throws' ClassTypeList -/.$putCase consumeMethodHeaderThrowsClause(); $break ./ + case 237 : // System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN Statement"); + consumeStatementIfNoElse(); + break; -ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters MethodHeaderThrowsClauseopt -/.$putCase consumeConstructorHeader(); $break ./ + case 238 : // System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN StatementNoShortIf else..."); + consumeStatementIfWithElse(); + break; -ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' -/.$putCase consumeConstructorHeaderName(); $break ./ + case 239 : // System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression RPAREN StatementNoShortIf..."); + consumeStatementIfWithElse(); + break; -FormalParameterList -> FormalParameter -FormalParameterList ::= FormalParameterList ',' FormalParameter -/.$putCase consumeFormalParameterList(); $break ./ + case 240 : // System.out.println("SwitchStatement ::= switch OpenBlock LPAREN Expression RPAREN SwitchBlock"); + consumeStatementSwitch(); + break; ---1.1 feature -FormalParameter ::= Modifiersopt Type VariableDeclaratorId -/.$putCase // the boolean is used to know if the modifiers should be reset - consumeFormalParameter(); $break ./ + case 241 : // System.out.println("SwitchBlock ::= LBRACE RBRACE"); + consumeEmptySwitchBlock(); + break; -ClassTypeList -> ClassTypeElt -ClassTypeList ::= ClassTypeList ',' ClassTypeElt -/.$putCase consumeClassTypeList(); $break ./ + case 244 : // System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements SwitchLabels RBRACE"); + consumeSwitchBlock(); + break; -ClassTypeElt ::= ClassType -/.$putCase consumeClassTypeElt(); $break ./ + case 246 : // System.out.println("SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement"); + consumeSwitchBlockStatements(); + break; + case 247 : // System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); + consumeSwitchBlockStatement(); + break; -MethodBody ::= NestedMethod '{' BlockStatementsopt '}' -/.$putCase consumeMethodBody(); $break ./ + case 249 : // System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); + consumeSwitchLabels(); + break; -NestedMethod ::= $empty -/.$putCase consumeNestedMethod(); $break ./ + case 250 : // System.out.println("SwitchLabel ::= case ConstantExpression COLON"); + consumeCaseLabel(); + break; ---18.8.4 Productions from 8.5: Static Initializers + case 251 : // System.out.println("SwitchLabel ::= default COLON"); + consumeDefaultLabel(); + break; -StaticInitializer ::= StaticOnly Block -/.$putCase consumeStaticInitializer(); $break./ + case 252 : // System.out.println("WhileStatement ::= while LPAREN Expression RPAREN Statement"); + consumeStatementWhile(); + break; -StaticOnly ::= 'static' -/.$putCase consumeStaticOnly(); $break ./ + case 253 : // System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression RPAREN StatementNoShortIf"); + consumeStatementWhile(); + break; ---18.8.5 Productions from 8.6: Constructor Declarations ---ConstructorModifier ::= --- 'public' --- | 'protected' --- | 'private' --- --- -ConstructorDeclaration ::= ConstructorHeader ConstructorBody -/.$putCase consumeConstructorDeclaration() ; $break ./ + case 254 : // System.out.println("DoStatement ::= do Statement while LPAREN Expression RPAREN SEMICOLON"); + consumeStatementDo(); + break; --- These rules are added to be able to parse constructors with no body -ConstructorDeclaration ::= ConstructorHeader ';' -/.$putCase consumeInvalidConstructorDeclaration() ; $break ./ + case 255 : // System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON Expressionopt SEMICOLON..."); + consumeStatementFor(); + break; --- the rules ExplicitConstructorInvocationopt has been expanded --- in the rule below in order to make the grammar lalr(1). --- ConstructorBody ::= '{' ExplicitConstructorInvocationopt BlockStatementsopt '}' --- Other inlining has occured into the next rule too.... + case 256 : // System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt SEMICOLON Expressionopt SEMICOLON"); + consumeStatementFor(); + break; -ConstructorBody ::= NestedMethod '{' ConstructorBlockStatementsopt '}' -/.$putCase consumeConstructorBody(); $break ./ + case 257 : // System.out.println("ForInit ::= StatementExpressionList"); + consumeForInit(); + break; -ConstructorBlockStatementsopt -> BlockStatementsopt + case 261 : // System.out.println("StatementExpressionList ::= StatementExpressionList COMMA StatementExpression"); + consumeStatementExpressionList(); + break; -ConstructorBlockStatementsopt -> ExplicitConstructorInvocation + case 262 : // System.out.println("AssertStatement ::= assert Expression SEMICOLON"); + consumeSimpleAssertStatement(); + break; -ConstructorBlockStatementsopt ::= ExplicitConstructorInvocation BlockStatements -/.$putCase consumeConstructorBlockStatements(); $break ./ + case 263 : // System.out.println("AssertStatement ::= assert Expression COLON Expression SEMICOLON"); + consumeAssertStatement(); + break; -ExplicitConstructorInvocation ::= 'this' '(' ArgumentListopt ')' ';' -/.$putCase consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.This); $break ./ + case 264 : // System.out.println("BreakStatement ::= break SEMICOLON"); + consumeStatementBreak(); + break; -ExplicitConstructorInvocation ::= 'super' '(' ArgumentListopt ')' ';' -/.$putCase consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.Super); $break ./ + case 265 : // System.out.println("BreakStatement ::= break Identifier SEMICOLON"); + consumeStatementBreakWithLabel(); + break; ---1.1 feature -ExplicitConstructorInvocation ::= Primary '.' 'super' '(' ArgumentListopt ')' ';' -/.$putCase consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.Super); $break ./ + case 266 : // System.out.println("ContinueStatement ::= continue SEMICOLON"); + consumeStatementContinue(); + break; ---1.1 feature -ExplicitConstructorInvocation ::= Name '.' 'super' '(' ArgumentListopt ')' ';' -/.$putCase consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.Super); $break ./ + case 267 : // System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); + consumeStatementContinueWithLabel(); + break; ---1.1 feature -ExplicitConstructorInvocation ::= Primary '.' 'this' '(' ArgumentListopt ')' ';' -/.$putCase consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.This); $break ./ + case 268 : // System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); + consumeStatementReturn(); + break; ---1.1 feature -ExplicitConstructorInvocation ::= Name '.' 'this' '(' ArgumentListopt ')' ';' -/.$putCase consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.This); $break ./ + case 269 : // System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); + consumeStatementThrow(); ---18.9 Productions from 9: Interface Declarations + break; ---18.9.1 Productions from 9.1: Interface Declarations ---InterfaceModifier ::= --- 'public' --- | 'abstract' --- -InterfaceDeclaration ::= InterfaceHeader InterfaceBody -/.$putCase consumeInterfaceDeclaration(); $break ./ + case 270 : // System.out.println("SynchronizedStatement ::= OnlySynchronized LPAREN Expression RPAREN Block"); + consumeStatementSynchronized(); + break; -InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt -/.$putCase consumeInterfaceHeader(); $break ./ + case 271 : // System.out.println("OnlySynchronized ::= synchronized"); + consumeOnlySynchronized(); + break; -InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier' -/.$putCase consumeInterfaceHeaderName(); $break ./ + case 272 : // System.out.println("TryStatement ::= try Block Catches"); + consumeStatementTry(false); + break; --- This rule will be used to accept inner local interface and then report a relevant error message -InvalidInterfaceDeclaration -> InterfaceHeader InterfaceBody + case 273 : // System.out.println("TryStatement ::= try Block Catchesopt Finally"); + consumeStatementTry(true); + break; -InterfaceHeaderExtends ::= 'extends' InterfaceTypeList -/.$putCase consumeInterfaceHeaderExtends(); $break ./ + case 275 : // System.out.println("Catches ::= Catches CatchClause"); + consumeCatches(); + break; -InterfaceBody ::= '{' InterfaceMemberDeclarationsopt '}' - -InterfaceMemberDeclarations -> InterfaceMemberDeclaration -InterfaceMemberDeclarations ::= InterfaceMemberDeclarations InterfaceMemberDeclaration -/.$putCase consumeInterfaceMemberDeclarations(); $break ./ - ---same as for class members -InterfaceMemberDeclaration ::= ';' -/.$putCase consumeEmptyInterfaceMemberDeclaration(); $break ./ + case 276 : // System.out.println("CatchClause ::= catch LPAREN FormalParameter RPAREN Block"); + consumeStatementCatch(); + break; --- This rule is added to be able to parse non abstract method inside interface and then report a relevent error message -InvalidMethodDeclaration -> MethodHeader MethodBody + case 278 : // System.out.println("PushLPAREN ::= LPAREN"); + consumeLeftParen(); + break; -InterfaceMemberDeclaration -> ConstantDeclaration -InterfaceMemberDeclaration ::= InvalidMethodDeclaration -/.$putCase ignoreMethodBody(); $break ./ - --- These rules are added to be able to parse constructors inside interface and then report a relevent error message -InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody -/.$putCase ignoreInvalidConstructorDeclaration(true); $break ./ - -InvalidConstructorDeclaration ::= ConstructorHeader ';' -/.$putCase ignoreInvalidConstructorDeclaration(false); $break ./ - -InterfaceMemberDeclaration -> AbstractMethodDeclaration -InterfaceMemberDeclaration -> InvalidConstructorDeclaration - ---1.1 feature -InterfaceMemberDeclaration -> ClassDeclaration ---1.1 feature -InterfaceMemberDeclaration -> InterfaceDeclaration - -ConstantDeclaration -> FieldDeclaration - -ArrayInitializer ::= '{' ,opt '}' -/.$putCase consumeEmptyArrayInitializer(); $break ./ -ArrayInitializer ::= '{' VariableInitializers '}' -/.$putCase consumeArrayInitializer(); $break ./ -ArrayInitializer ::= '{' VariableInitializers , '}' -/.$putCase consumeArrayInitializer(); $break ./ + case 279 : // System.out.println("PushRPAREN ::= RPAREN"); + consumeRightParen(); + break; -VariableInitializers ::= VariableInitializer -VariableInitializers ::= VariableInitializers ',' VariableInitializer -/.$putCase consumeVariableInitializers(); $break ./ + case 283 : // System.out.println("PrimaryNoNewArray ::= this"); + consumePrimaryNoNewArrayThis(); + break; -Block ::= OpenBlock '{' BlockStatementsopt '}' -/.$putCase consumeBlock(); $break ./ -OpenBlock ::= $empty -/.$putCase consumeOpenBlock() ; $break ./ - -BlockStatements -> BlockStatement -BlockStatements ::= BlockStatements BlockStatement -/.$putCase consumeBlockStatements() ; $break ./ - -BlockStatement -> LocalVariableDeclarationStatement -BlockStatement -> Statement ---1.1 feature -BlockStatement -> ClassDeclaration -BlockStatement ::= InvalidInterfaceDeclaration -/.$putCase ignoreInterfaceDeclaration(); $break ./ - -LocalVariableDeclarationStatement ::= LocalVariableDeclaration ';' -/.$putCase consumeLocalVariableDeclarationStatement(); $break ./ - -LocalVariableDeclaration ::= Type PushModifiers VariableDeclarators -/.$putCase consumeLocalVariableDeclaration(); $break ./ - --- 1.1 feature --- The modifiers part of this rule makes the grammar more permissive. --- The only modifier here is final. We put Modifiers to allow multiple modifiers --- This will require to check the validity of the modifier - -LocalVariableDeclaration ::= Modifiers Type PushModifiers VariableDeclarators -/.$putCase consumeLocalVariableDeclaration(); $break ./ - -PushModifiers ::= $empty -/.$putCase consumePushModifiers(); $break ./ - -Statement -> StatementWithoutTrailingSubstatement -Statement -> LabeledStatement -Statement -> IfThenStatement -Statement -> IfThenElseStatement -Statement -> WhileStatement -Statement -> ForStatement - -StatementNoShortIf -> StatementWithoutTrailingSubstatement -StatementNoShortIf -> LabeledStatementNoShortIf -StatementNoShortIf -> IfThenElseStatementNoShortIf -StatementNoShortIf -> WhileStatementNoShortIf -StatementNoShortIf -> ForStatementNoShortIf + case 284 : // System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN"); + consumePrimaryNoNewArray(); + break; -StatementWithoutTrailingSubstatement -> AssertStatement -StatementWithoutTrailingSubstatement -> Block -StatementWithoutTrailingSubstatement -> EmptyStatement -StatementWithoutTrailingSubstatement -> ExpressionStatement -StatementWithoutTrailingSubstatement -> SwitchStatement -StatementWithoutTrailingSubstatement -> DoStatement -StatementWithoutTrailingSubstatement -> BreakStatement -StatementWithoutTrailingSubstatement -> ContinueStatement -StatementWithoutTrailingSubstatement -> ReturnStatement -StatementWithoutTrailingSubstatement -> SynchronizedStatement -StatementWithoutTrailingSubstatement -> ThrowStatement -StatementWithoutTrailingSubstatement -> TryStatement - -EmptyStatement ::= ';' -/.$putCase consumeEmptyStatement(); $break ./ - -LabeledStatement ::= 'Identifier' ':' Statement -/.$putCase consumeStatementLabel() ; $break ./ - -LabeledStatementNoShortIf ::= 'Identifier' ':' StatementNoShortIf -/.$putCase consumeStatementLabel() ; $break ./ - -ExpressionStatement ::= StatementExpression ';' -/. $putCase consumeExpressionStatement(); $break ./ - -StatementExpression ::= Assignment -StatementExpression ::= PreIncrementExpression -StatementExpression ::= PreDecrementExpression -StatementExpression ::= PostIncrementExpression -StatementExpression ::= PostDecrementExpression -StatementExpression ::= MethodInvocation -StatementExpression ::= ClassInstanceCreationExpression - -IfThenStatement ::= 'if' '(' Expression ')' Statement -/.$putCase consumeStatementIfNoElse(); $break ./ - -IfThenElseStatement ::= 'if' '(' Expression ')' StatementNoShortIf 'else' Statement -/.$putCase consumeStatementIfWithElse(); $break ./ + case 287 : // System.out.println("PrimaryNoNewArray ::= Name DOT this"); + consumePrimaryNoNewArrayNameThis(); + break; -IfThenElseStatementNoShortIf ::= 'if' '(' Expression ')' StatementNoShortIf 'else' StatementNoShortIf -/.$putCase consumeStatementIfWithElse(); $break ./ + case 288 : // System.out.println("PrimaryNoNewArray ::= Name DOT super"); + consumePrimaryNoNewArrayNameSuper(); + break; -SwitchStatement ::= 'switch' OpenBlock '(' Expression ')' SwitchBlock -/.$putCase consumeStatementSwitch() ; $break ./ + case 289 : // System.out.println("PrimaryNoNewArray ::= Name DOT class"); + consumePrimaryNoNewArrayName(); + break; -SwitchBlock ::= '{' '}' -/.$putCase consumeEmptySwitchBlock() ; $break ./ + case 290 : // System.out.println("PrimaryNoNewArray ::= ArrayType DOT class"); + consumePrimaryNoNewArrayArrayType(); + break; -SwitchBlock ::= '{' SwitchBlockStatements '}' -SwitchBlock ::= '{' SwitchLabels '}' -SwitchBlock ::= '{' SwitchBlockStatements SwitchLabels '}' -/.$putCase consumeSwitchBlock() ; $break ./ + case 291 : // System.out.println("PrimaryNoNewArray ::= PrimitiveType DOT class"); + consumePrimaryNoNewArrayPrimitiveType(); + break; -SwitchBlockStatements -> SwitchBlockStatement -SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement -/.$putCase consumeSwitchBlockStatements() ; $break ./ + case 294 : // System.out.println("AllocationHeader ::= new ClassType LPAREN ArgumentListopt RPAREN"); + consumeAllocationHeader(); + break; -SwitchBlockStatement ::= SwitchLabels BlockStatements -/.$putCase consumeSwitchBlockStatement() ; $break ./ + case 295 : // System.out.println("ClassInstanceCreationExpression ::= new ClassType LPAREN ArgumentListopt RPAREN..."); + consumeClassInstanceCreationExpression(); + break; -SwitchLabels -> SwitchLabel -SwitchLabels ::= SwitchLabels SwitchLabel -/.$putCase consumeSwitchLabels() ; $break ./ + case 296 : // System.out.println("ClassInstanceCreationExpression ::= Primary DOT new SimpleName LPAREN..."); + consumeClassInstanceCreationExpressionQualified(); + break; -SwitchLabel ::= 'case' ConstantExpression ':' -/. $putCase consumeCaseLabel(); $break ./ + case 297 : // System.out.println("ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName new..."); + consumeClassInstanceCreationExpressionQualified(); + break; -SwitchLabel ::= 'default' ':' -/. $putCase consumeDefaultLabel(); $break ./ + case 298 : // System.out.println("ClassInstanceCreationExpressionName ::= Name DOT"); + consumeClassInstanceCreationExpressionName(); + break; -WhileStatement ::= 'while' '(' Expression ')' Statement -/.$putCase consumeStatementWhile() ; $break ./ + case 299 : // System.out.println("ClassBodyopt ::="); + consumeClassBodyopt(); + break; -WhileStatementNoShortIf ::= 'while' '(' Expression ')' StatementNoShortIf -/.$putCase consumeStatementWhile() ; $break ./ + case 301 : // System.out.println("EnterAnonymousClassBody ::="); + consumeEnterAnonymousClassBody(); + break; -DoStatement ::= 'do' Statement 'while' '(' Expression ')' ';' -/.$putCase consumeStatementDo() ; $break ./ + case 303 : // System.out.println("ArgumentList ::= ArgumentList COMMA Expression"); + consumeArgumentList(); + break; -ForStatement ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' Statement -/.$putCase consumeStatementFor() ; $break ./ -ForStatementNoShortIf ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' StatementNoShortIf -/.$putCase consumeStatementFor() ; $break ./ + case 304 : // System.out.println("ArrayCreationExpression ::= new PrimitiveType DimWithOrWithOutExprs..."); + consumeArrayCreationExpression(); + break; ---the minus one allows to avoid a stack-to-stack transfer -ForInit ::= StatementExpressionList -/.$putCase consumeForInit() ; $break ./ -ForInit -> LocalVariableDeclaration + case 305 : // System.out.println("ArrayCreationExpression ::= new ClassOrInterfaceType DimWithOrWithOutExprs..."); + consumeArrayCreationExpression(); + break; -ForUpdate -> StatementExpressionList + case 307 : // System.out.println("DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr"); + consumeDimWithOrWithOutExprs(); + break; -StatementExpressionList -> StatementExpression -StatementExpressionList ::= StatementExpressionList ',' StatementExpression -/.$putCase consumeStatementExpressionList() ; $break ./ + case 309 : // System.out.println("DimWithOrWithOutExpr ::= LBRACKET RBRACKET"); + consumeDimWithOrWithOutExpr(); + break; --- 1.4 feature -AssertStatement ::= 'assert' Expression ';' -/.$putCase consumeSimpleAssertStatement() ; $break ./ + case 310 : // System.out.println("Dims ::= DimsLoop"); + consumeDims(); + break; -AssertStatement ::= 'assert' Expression ':' Expression ';' -/.$putCase consumeAssertStatement() ; $break ./ - -BreakStatement ::= 'break' ';' -/.$putCase consumeStatementBreak() ; $break ./ + case 313 : // System.out.println("OneDimLoop ::= LBRACKET RBRACKET"); + consumeOneDimLoop(); + break; -BreakStatement ::= 'break' Identifier ';' -/.$putCase consumeStatementBreakWithLabel() ; $break ./ + case 314 : // System.out.println("FieldAccess ::= Primary DOT Identifier"); + consumeFieldAccess(false); + break; -ContinueStatement ::= 'continue' ';' -/.$putCase consumeStatementContinue() ; $break ./ + case 315 : // System.out.println("FieldAccess ::= super DOT Identifier"); + consumeFieldAccess(true); + break; -ContinueStatement ::= 'continue' Identifier ';' -/.$putCase consumeStatementContinueWithLabel() ; $break ./ + case 316 : // System.out.println("MethodInvocation ::= Name LPAREN ArgumentListopt RPAREN"); + consumeMethodInvocationName(); + break; -ReturnStatement ::= 'return' Expressionopt ';' -/.$putCase consumeStatementReturn() ; $break ./ + case 317 : // System.out.println("MethodInvocation ::= Primary DOT Identifier LPAREN ArgumentListopt RPAREN"); + consumeMethodInvocationPrimary(); + break; -ThrowStatement ::= 'throw' Expression ';' -/.$putCase consumeStatementThrow(); -$break ./ + case 318 : // System.out.println("MethodInvocation ::= super DOT Identifier LPAREN ArgumentListopt RPAREN"); + consumeMethodInvocationSuper(); + break; -SynchronizedStatement ::= OnlySynchronized '(' Expression ')' Block -/.$putCase consumeStatementSynchronized(); $break ./ -OnlySynchronized ::= 'synchronized' -/.$putCase consumeOnlySynchronized(); $break ./ + case 319 : // System.out.println("ArrayAccess ::= Name LBRACKET Expression RBRACKET"); + consumeArrayAccess(true); + break; + case 320 : // System.out.println("ArrayAccess ::= PrimaryNoNewArray LBRACKET Expression RBRACKET"); + consumeArrayAccess(false); + break; -TryStatement ::= 'try' Block Catches -/.$putCase consumeStatementTry(false); $break ./ -TryStatement ::= 'try' Block Catchesopt Finally -/.$putCase consumeStatementTry(true); $break ./ + case 322 : // System.out.println("PostfixExpression ::= Name"); + consumePostfixExpression(); + break; -Catches -> CatchClause -Catches ::= Catches CatchClause -/.$putCase consumeCatches(); $break ./ + case 325 : // System.out.println("PostIncrementExpression ::= PostfixExpression PLUS_PLUS"); + consumeUnaryExpression(OperatorExpression.PLUS, true); + break; -CatchClause ::= 'catch' '(' FormalParameter ')' Block -/.$putCase consumeStatementCatch() ; $break ./ + case 326 : // System.out.println("PostDecrementExpression ::= PostfixExpression MINUS_MINUS"); + consumeUnaryExpression(OperatorExpression.MINUS, true); + break; -Finally ::= 'finally' Block + case 327 : // System.out.println("PushPosition ::="); + consumePushPosition(); + break; ---18.12 Productions from 14: Expressions + case 330 : // System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); + consumeUnaryExpression(OperatorExpression.PLUS); + break; ---for source positionning purpose -PushLPAREN ::= '(' -/.$putCase consumeLeftParen(); $break ./ -PushRPAREN ::= ')' -/.$putCase consumeRightParen(); $break ./ + case 331 : // System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); + consumeUnaryExpression(OperatorExpression.MINUS); + break; -Primary -> PrimaryNoNewArray -Primary -> ArrayCreationExpression + case 333 : // System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition UnaryExpression"); + consumeUnaryExpression(OperatorExpression.PLUS, false); + break; -PrimaryNoNewArray -> Literal -PrimaryNoNewArray ::= 'this' -/.$putCase consumePrimaryNoNewArrayThis(); $break ./ + case 334 : // System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition UnaryExpression"); + consumeUnaryExpression(OperatorExpression.MINUS, false); + break; -PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN -/.$putCase consumePrimaryNoNewArray(); $break ./ + case 336 : // System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition UnaryExpression"); + consumeUnaryExpression(OperatorExpression.TWIDDLE); + break; -PrimaryNoNewArray -> ClassInstanceCreationExpression -PrimaryNoNewArray -> FieldAccess ---1.1 feature -PrimaryNoNewArray ::= Name '.' 'this' -/.$putCase consumePrimaryNoNewArrayNameThis(); $break ./ -PrimaryNoNewArray ::= Name '.' 'super' -/.$putCase consumePrimaryNoNewArrayNameSuper(); $break ./ + case 337 : // System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition UnaryExpression"); + consumeUnaryExpression(OperatorExpression.NOT); + break; ---1.1 feature ---PrimaryNoNewArray ::= Type '.' 'class' ---inline Type in the previous rule in order to make the grammar LL1 instead --- of LL2. The result is the 3 next rules. -PrimaryNoNewArray ::= Name '.' 'class' -/.$putCase consumePrimaryNoNewArrayName(); $break ./ + case 339 : // System.out.println("CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN UnaryExpression"); + consumeCastExpression(); + break; -PrimaryNoNewArray ::= ArrayType '.' 'class' -/.$putCase consumePrimaryNoNewArrayArrayType(); $break ./ + case 340 : // System.out.println("CastExpression ::= PushLPAREN Name Dims PushRPAREN UnaryExpressionNotPlusMinus"); + consumeCastExpression(); + break; -PrimaryNoNewArray ::= PrimitiveType '.' 'class' -/.$putCase consumePrimaryNoNewArrayPrimitiveType(); $break ./ + case 341 : // System.out.println("CastExpression ::= PushLPAREN Expression PushRPAREN UnaryExpressionNotPlusMinus"); + consumeCastExpressionLL1(); + break; -PrimaryNoNewArray -> MethodInvocation -PrimaryNoNewArray -> ArrayAccess + case 343 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression MULTIPLY UnaryExpression"); + consumeBinaryExpression(OperatorExpression.MULTIPLY); + break; ---1.1 feature --- --- In Java 1.0 a ClassBody could not appear at all in a --- ClassInstanceCreationExpression. --- + case 344 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression DIVIDE UnaryExpression"); + consumeBinaryExpression(OperatorExpression.DIVIDE); + break; -AllocationHeader ::= 'new' ClassType '(' ArgumentListopt ')' -/.$putCase consumeAllocationHeader(); $break ./ + case 345 : // System.out.println("MultiplicativeExpression ::= MultiplicativeExpression REMAINDER UnaryExpression"); + consumeBinaryExpression(OperatorExpression.REMAINDER); + break; -ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt -/.$putCase consumeClassInstanceCreationExpression(); $break ./ ---1.1 feature + case 347 : // System.out.println("AdditiveExpression ::= AdditiveExpression PLUS MultiplicativeExpression"); + consumeBinaryExpression(OperatorExpression.PLUS); + break; -ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt -/.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./ + case 348 : // System.out.println("AdditiveExpression ::= AdditiveExpression MINUS MultiplicativeExpression"); + consumeBinaryExpression(OperatorExpression.MINUS); + break; ---1.1 feature -ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt -/.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./ + case 350 : // System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT AdditiveExpression"); + consumeBinaryExpression(OperatorExpression.LEFT_SHIFT); + break; -ClassInstanceCreationExpressionName ::= Name '.' -/.$putCase consumeClassInstanceCreationExpressionName() ; $break ./ - -ClassBodyopt ::= $empty --test made using null as contents -/.$putCase consumeClassBodyopt(); $break ./ -ClassBodyopt ::= EnterAnonymousClassBody ClassBody - -EnterAnonymousClassBody ::= $empty -/.$putCase consumeEnterAnonymousClassBody(); $break ./ - -ArgumentList ::= Expression -ArgumentList ::= ArgumentList ',' Expression -/.$putCase consumeArgumentList(); $break ./ - ---Thess rules are re-written in order to be ll1 ---ArrayCreationExpression ::= 'new' ArrayType ArrayInitializer ---ArrayCreationExpression ::= 'new' PrimitiveType DimExprs Dimsopt ---ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimExprs Dimsopt ---DimExprs ::= DimExpr ---DimExprs ::= DimExprs DimExpr - -ArrayCreationExpression ::= 'new' PrimitiveType DimWithOrWithOutExprs ArrayInitializeropt -/.$putCase consumeArrayCreationExpression(); $break ./ -ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimWithOrWithOutExprs ArrayInitializeropt -/.$putCase consumeArrayCreationExpression(); $break ./ - -DimWithOrWithOutExprs ::= DimWithOrWithOutExpr -DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr -/.$putCase consumeDimWithOrWithOutExprs(); $break ./ - -DimWithOrWithOutExpr ::= '[' Expression ']' -DimWithOrWithOutExpr ::= '[' ']' -/. $putCase consumeDimWithOrWithOutExpr(); $break ./ --- ----------------------------------------------- - -Dims ::= DimsLoop -/. $putCase consumeDims(); $break ./ -DimsLoop -> OneDimLoop -DimsLoop ::= DimsLoop OneDimLoop -OneDimLoop ::= '[' ']' -/. $putCase consumeOneDimLoop(); $break ./ - -FieldAccess ::= Primary '.' 'Identifier' -/.$putCase consumeFieldAccess(false); $break ./ - -FieldAccess ::= 'super' '.' 'Identifier' -/.$putCase consumeFieldAccess(true); $break ./ - -MethodInvocation ::= Name '(' ArgumentListopt ')' -/.$putCase consumeMethodInvocationName(); $break ./ - -MethodInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' -/.$putCase consumeMethodInvocationPrimary(); $break ./ - -MethodInvocation ::= 'super' '.' 'Identifier' '(' ArgumentListopt ')' -/.$putCase consumeMethodInvocationSuper(); $break ./ - -ArrayAccess ::= Name '[' Expression ']' -/.$putCase consumeArrayAccess(true); $break ./ -ArrayAccess ::= PrimaryNoNewArray '[' Expression ']' -/.$putCase consumeArrayAccess(false); $break ./ - -PostfixExpression -> Primary -PostfixExpression ::= Name -/.$putCase consumePostfixExpression(); $break ./ -PostfixExpression -> PostIncrementExpression -PostfixExpression -> PostDecrementExpression - -PostIncrementExpression ::= PostfixExpression '++' -/.$putCase consumeUnaryExpression(OperatorExpression.PLUS,true); $break ./ - -PostDecrementExpression ::= PostfixExpression '--' -/.$putCase consumeUnaryExpression(OperatorExpression.MINUS,true); $break ./ - ---for source managment purpose -PushPosition ::= $empty - /.$putCase consumePushPosition(); $break ./ - -UnaryExpression -> PreIncrementExpression -UnaryExpression -> PreDecrementExpression -UnaryExpression ::= '+' PushPosition UnaryExpression -/.$putCase consumeUnaryExpression(OperatorExpression.PLUS); $break ./ -UnaryExpression ::= '-' PushPosition UnaryExpression -/.$putCase consumeUnaryExpression(OperatorExpression.MINUS); $break ./ -UnaryExpression -> UnaryExpressionNotPlusMinus - -PreIncrementExpression ::= '++' PushPosition UnaryExpression -/.$putCase consumeUnaryExpression(OperatorExpression.PLUS,false); $break ./ - -PreDecrementExpression ::= '--' PushPosition UnaryExpression -/.$putCase consumeUnaryExpression(OperatorExpression.MINUS,false); $break ./ - -UnaryExpressionNotPlusMinus -> PostfixExpression -UnaryExpressionNotPlusMinus ::= '~' PushPosition UnaryExpression -/.$putCase consumeUnaryExpression(OperatorExpression.TWIDDLE); $break ./ -UnaryExpressionNotPlusMinus ::= '!' PushPosition UnaryExpression -/.$putCase consumeUnaryExpression(OperatorExpression.NOT); $break ./ -UnaryExpressionNotPlusMinus -> CastExpression - -CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN UnaryExpression -/.$putCase consumeCastExpression(); $break ./ - CastExpression ::= PushLPAREN Name Dims PushRPAREN UnaryExpressionNotPlusMinus -/.$putCase consumeCastExpression(); $break ./ --- Expression is here only in order to make the grammar LL1 -CastExpression ::= PushLPAREN Expression PushRPAREN UnaryExpressionNotPlusMinus -/.$putCase consumeCastExpressionLL1(); $break ./ - -MultiplicativeExpression -> UnaryExpression -MultiplicativeExpression ::= MultiplicativeExpression '*' UnaryExpression -/.$putCase consumeBinaryExpression(OperatorExpression.MULTIPLY); $break ./ -MultiplicativeExpression ::= MultiplicativeExpression '/' UnaryExpression -/.$putCase consumeBinaryExpression(OperatorExpression.DIVIDE); $break ./ -MultiplicativeExpression ::= MultiplicativeExpression '%' UnaryExpression -/.$putCase consumeBinaryExpression(OperatorExpression.REMAINDER); $break ./ - -AdditiveExpression -> MultiplicativeExpression -AdditiveExpression ::= AdditiveExpression '+' MultiplicativeExpression -/.$putCase consumeBinaryExpression(OperatorExpression.PLUS); $break ./ -AdditiveExpression ::= AdditiveExpression '-' MultiplicativeExpression -/.$putCase consumeBinaryExpression(OperatorExpression.MINUS); $break ./ - -ShiftExpression -> AdditiveExpression -ShiftExpression ::= ShiftExpression '<<' AdditiveExpression -/.$putCase consumeBinaryExpression(OperatorExpression.LEFT_SHIFT); $break ./ -ShiftExpression ::= ShiftExpression '>>' AdditiveExpression -/.$putCase consumeBinaryExpression(OperatorExpression.RIGHT_SHIFT); $break ./ -ShiftExpression ::= ShiftExpression '>>>' AdditiveExpression -/.$putCase consumeBinaryExpression(OperatorExpression.UNSIGNED_RIGHT_SHIFT); $break ./ - -RelationalExpression -> ShiftExpression -RelationalExpression ::= RelationalExpression '<' ShiftExpression -/.$putCase consumeBinaryExpression(OperatorExpression.LESS); $break ./ -RelationalExpression ::= RelationalExpression '>' ShiftExpression -/.$putCase consumeBinaryExpression(OperatorExpression.GREATER); $break ./ -RelationalExpression ::= RelationalExpression '<=' ShiftExpression -/.$putCase consumeBinaryExpression(OperatorExpression.LESS_EQUAL); $break ./ -RelationalExpression ::= RelationalExpression '>=' ShiftExpression -/.$putCase consumeBinaryExpression(OperatorExpression.GREATER_EQUAL); $break ./ -RelationalExpression ::= RelationalExpression 'instanceof' ReferenceType -/.$putCase consumeInstanceOfExpression(OperatorExpression.INSTANCEOF); $break ./ - -EqualityExpression -> RelationalExpression -EqualityExpression ::= EqualityExpression '==' RelationalExpression -/.$putCase consumeEqualityExpression(OperatorExpression.EQUAL_EQUAL); $break ./ -EqualityExpression ::= EqualityExpression '!=' RelationalExpression -/.$putCase consumeEqualityExpression(OperatorExpression.NOT_EQUAL); $break ./ - -AndExpression -> EqualityExpression -AndExpression ::= AndExpression '&' EqualityExpression -/.$putCase consumeBinaryExpression(OperatorExpression.AND); $break ./ - -ExclusiveOrExpression -> AndExpression -ExclusiveOrExpression ::= ExclusiveOrExpression '^' AndExpression -/.$putCase consumeBinaryExpression(OperatorExpression.XOR); $break ./ - -InclusiveOrExpression -> ExclusiveOrExpression -InclusiveOrExpression ::= InclusiveOrExpression '|' ExclusiveOrExpression -/.$putCase consumeBinaryExpression(OperatorExpression.OR); $break ./ - -ConditionalAndExpression -> InclusiveOrExpression -ConditionalAndExpression ::= ConditionalAndExpression '&&' InclusiveOrExpression -/.$putCase consumeBinaryExpression(OperatorExpression.AND_AND); $break ./ - -ConditionalOrExpression -> ConditionalAndExpression -ConditionalOrExpression ::= ConditionalOrExpression '||' ConditionalAndExpression -/.$putCase consumeBinaryExpression(OperatorExpression.OR_OR); $break ./ - -ConditionalExpression -> ConditionalOrExpression -ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression -/.$putCase consumeConditionalExpression(OperatorExpression.QUESTIONCOLON) ; $break ./ - -AssignmentExpression -> ConditionalExpression -AssignmentExpression -> Assignment - -Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression -/.$putCase consumeAssignment(); $break ./ - --- this rule is added to parse an array initializer in a assigment and then report a syntax error knowing the exact senario -InvalidArrayInitializerAssignement ::= LeftHandSide AssignmentOperator ArrayInitializer -Assignment ::= InvalidArrayInitializerAssignement -/.$putcase ignoreExpressionAssignment();$break ./ - -LeftHandSide ::= Name -/.$putCase consumeLeftHandSide(); $break ./ -LeftHandSide -> FieldAccess -LeftHandSide -> ArrayAccess - -AssignmentOperator ::= '=' -/.$putCase consumeAssignmentOperator(EQUAL); $break ./ -AssignmentOperator ::= '*=' -/.$putCase consumeAssignmentOperator(MULTIPLY); $break ./ -AssignmentOperator ::= '/=' -/.$putCase consumeAssignmentOperator(DIVIDE); $break ./ -AssignmentOperator ::= '%=' -/.$putCase consumeAssignmentOperator(REMAINDER); $break ./ -AssignmentOperator ::= '+=' -/.$putCase consumeAssignmentOperator(PLUS); $break ./ -AssignmentOperator ::= '-=' -/.$putCase consumeAssignmentOperator(MINUS); $break ./ -AssignmentOperator ::= '<<=' -/.$putCase consumeAssignmentOperator(LEFT_SHIFT); $break ./ -AssignmentOperator ::= '>>=' -/.$putCase consumeAssignmentOperator(RIGHT_SHIFT); $break ./ -AssignmentOperator ::= '>>>=' -/.$putCase consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT); $break ./ -AssignmentOperator ::= '&=' -/.$putCase consumeAssignmentOperator(AND); $break ./ -AssignmentOperator ::= '^=' -/.$putCase consumeAssignmentOperator(XOR); $break ./ -AssignmentOperator ::= '|=' -/.$putCase consumeAssignmentOperator(OR); $break ./ - -Expression -> AssignmentExpression - -ConstantExpression -> Expression - --- The following rules are for optional nonterminals. --- - -PackageDeclarationopt -> $empty -PackageDeclarationopt -> PackageDeclaration - -ClassHeaderExtendsopt ::= $empty -ClassHeaderExtendsopt -> ClassHeaderExtends - -Expressionopt ::= $empty -/.$putCase consumeEmptyExpression(); $break ./ -Expressionopt -> Expression - - ---------------------------------------------------------------------------------------- --- --- The rules below are for optional terminal symbols. An optional comma, --- is only used in the context of an array initializer - It is a --- "syntactic sugar" that otherwise serves no other purpose. By contrast, --- an optional identifier is used in the definition of a break and --- continue statement. When the identifier does not appear, a NULL --- is produced. When the identifier is present, the user should use the --- corresponding TOKEN(i) method. See break statement as an example. --- ---------------------------------------------------------------------------------------- - -,opt -> $empty -,opt -> , - -ImportDeclarationsopt ::= $empty -/.$putCase consumeEmptyImportDeclarationsopt(); $break ./ -ImportDeclarationsopt ::= ImportDeclarations -/.$putCase consumeImportDeclarationsopt(); $break ./ - - -TypeDeclarationsopt ::= $empty -/.$putCase consumeEmptyTypeDeclarationsopt(); $break ./ -TypeDeclarationsopt ::= TypeDeclarations -/.$putCase consumeTypeDeclarationsopt(); $break ./ - -ClassBodyDeclarationsopt ::= $empty -/.$putCase consumeEmptyClassBodyDeclarationsopt(); $break ./ -ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations -/.$putCase consumeClassBodyDeclarationsopt(); $break ./ - -Modifiersopt ::= $empty -/. $putCase consumeDefaultModifiers(); $break ./ -Modifiersopt ::= Modifiers -/.$putCase consumeModifiers(); $break ./ - -BlockStatementsopt ::= $empty -/.$putCase consumeEmptyBlockStatementsopt(); $break ./ -BlockStatementsopt -> BlockStatements - -Dimsopt ::= $empty -/. $putCase consumeEmptyDimsopt(); $break ./ -Dimsopt -> Dims - -ArgumentListopt ::= $empty -/. $putCase consumeEmptyArgumentListopt(); $break ./ -ArgumentListopt -> ArgumentList - -MethodHeaderThrowsClauseopt ::= $empty -MethodHeaderThrowsClauseopt -> MethodHeaderThrowsClause - -FormalParameterListopt ::= $empty -/.$putcase consumeFormalParameterListopt(); $break ./ -FormalParameterListopt -> FormalParameterList - -ClassHeaderImplementsopt ::= $empty -ClassHeaderImplementsopt -> ClassHeaderImplements - -InterfaceMemberDeclarationsopt ::= $empty -/. $putCase consumeEmptyInterfaceMemberDeclarationsopt(); $break ./ -InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations -/. $putCase consumeInterfaceMemberDeclarationsopt(); $break ./ - -NestedType ::= $empty -/.$putCase consumeNestedType(); $break./ - -ForInitopt ::= $empty -/. $putCase consumeEmptyForInitopt(); $break ./ -ForInitopt -> ForInit - -ForUpdateopt ::= $empty -/. $putCase consumeEmptyForUpdateopt(); $break ./ - ForUpdateopt -> ForUpdate - -InterfaceHeaderExtendsopt ::= $empty -InterfaceHeaderExtendsopt -> InterfaceHeaderExtends - -Catchesopt ::= $empty -/. $putCase consumeEmptyCatchesopt(); $break ./ -Catchesopt -> Catches - -ArrayInitializeropt ::= $empty -/. $putCase consumeEmptyArrayInitializeropt(); $break ./ -ArrayInitializeropt -> ArrayInitializer - -/. } -} ./ - ---------------------------------------------------------------------------------------- - -$names - --- BodyMarker ::= '"class Identifier { ... MethodHeader "' - --- void ::= 'void' - -PLUS_PLUS ::= '++' -MINUS_MINUS ::= '--' -EQUAL_EQUAL ::= '==' -LESS_EQUAL ::= '<=' -GREATER_EQUAL ::= '>=' -NOT_EQUAL ::= '!=' -LEFT_SHIFT ::= '<<' -RIGHT_SHIFT ::= '>>' -UNSIGNED_RIGHT_SHIFT ::= '>>>' -PLUS_EQUAL ::= '+=' -MINUS_EQUAL ::= '-=' -MULTIPLY_EQUAL ::= '*=' -DIVIDE_EQUAL ::= '/=' -AND_EQUAL ::= '&=' -OR_EQUAL ::= '|=' -XOR_EQUAL ::= '^=' -REMAINDER_EQUAL ::= '%=' -LEFT_SHIFT_EQUAL ::= '<<=' -RIGHT_SHIFT_EQUAL ::= '>>=' -UNSIGNED_RIGHT_SHIFT_EQUAL ::= '>>>=' -OR_OR ::= '||' -AND_AND ::= '&&' - -PLUS ::= '+' -MINUS ::= '-' -NOT ::= '!' -REMAINDER ::= '%' -XOR ::= '^' -AND ::= '&' -MULTIPLY ::= '*' -OR ::= '|' -TWIDDLE ::= '~' -DIVIDE ::= '/' -GREATER ::= '>' -LESS ::= '<' -LPAREN ::= '(' -RPAREN ::= ')' -LBRACE ::= '{' -RBRACE ::= '}' -LBRACKET ::= '[' -RBRACKET ::= ']' -SEMICOLON ::= ';' -QUESTION ::= '?' -COLON ::= ':' -COMMA ::= ',' -DOT ::= '.' -EQUAL ::= '=' - -$end --- need a carriage return after the $end -*/ -} -protected void ignoreExpressionAssignment() { - // Assignment ::= InvalidArrayInitializerAssignement - // encoded operator would be: intStack[intPtr] - intPtr--; - ArrayInitializer arrayInitializer = (ArrayInitializer) expressionStack[expressionPtr--]; - expressionLengthPtr -- ; - // report a syntax error and abort parsing - problemReporter().arrayConstantsOnlyInArrayInitializers(arrayInitializer.sourceStart, arrayInitializer.sourceEnd); -} -protected void ignoreInterfaceDeclaration() { - // BlockStatement ::= InvalidInterfaceDeclaration - //InterfaceDeclaration ::= Modifiersopt 'interface' 'Identifier' ExtendsInterfacesopt InterfaceHeader InterfaceBody - - // length declarations - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - //there are length declarations - //dispatch according to the type of the declarations - dispatchDeclarationInto(length); - } - - flushAnnotationsDefinedPriorTo(endStatementPosition); - - // report the problem and continue parsing - TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; - typeDecl.bodyEnd = endStatementPosition; - problemReporter().cannotDeclareLocalInterface(typeDecl.name, typeDecl.sourceStart, typeDecl.sourceEnd); - - // mark fields and initializer with local type mark if needed - markFieldsWithLocalType(typeDecl); - - // remove the ast node created in interface header - astPtr--; - // Don't create an astnode for this inner interface, but have to push - // a 0 on the astLengthStack to be consistent with the reduction made - // at the end of the method: - // public void parse(MethodDeclaration md, CompilationUnitDeclaration unit) - pushOnAstLengthStack(0); -} -protected void ignoreInvalidConstructorDeclaration(boolean hasBody) { - // InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody ==> true - // InvalidConstructorDeclaration ::= ConstructorHeader ';' ==> false - - /* - astStack : modifiers arguments throws statements - identifierStack : name - ==> - astStack : MethodDeclaration - identifierStack : - */ - - //must provide a default constructor call when needed - - if (hasBody) { - // pop the position of the { (body of the method) pushed in block decl - intPtr--; - } - - //statements - if (hasBody) { - realBlockPtr--; - } - - int length; - if (hasBody && ((length = astLengthStack[astLengthPtr--]) != 0)) { - astPtr -= length; - } -} -protected void ignoreMethodBody() { - // InterfaceMemberDeclaration ::= InvalidMethodDeclaration - - /* - astStack : modifiers arguments throws statements - identifierStack : type name - intStack : dim dim dim - ==> - astStack : MethodDeclaration - identifierStack : - intStack : - */ - - // pop the position of the { (body of the method) pushed in block decl - intPtr--; - // retrieve end position of method declarator - - //statements - realBlockPtr--; - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - astPtr -= length; - } - - //watch for } that could be given as a unicode ! ( u007D is '}' ) - MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; - md.bodyEnd = endPosition; - md.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); - - // report the problem and continue the parsing - narrowing the problem onto the method - problemReporter().abstractMethodNeedingNoBody(md); -} -public void initialize() { - //positionning the parser for a new compilation unit - //avoiding stack reallocation and all that.... - astPtr = -1; - astLengthPtr = -1; - expressionPtr = -1; - expressionLengthPtr = -1; - identifierPtr = -1; - identifierLengthPtr = -1; - intPtr = -1; - nestedMethod[nestedType = 0] = 0; // need to reset for further reuse - variablesCounter[nestedType] = 0; - dimensions = 0 ; - realBlockPtr = -1; - compilationUnit = null; - referenceContext = null; - endStatementPosition = 0; - - //remove objects from stack too, while the same parser/compiler couple is - //re-used between two compilations .... - - int astLength = astStack.length; - if (noAstNodes.length < astLength){ - noAstNodes = new AstNode[astLength]; - //System.out.println("Resized AST stacks : "+ astLength); - - } - System.arraycopy(noAstNodes, 0, astStack, 0, astLength); - - int expressionLength = expressionStack.length; - if (noExpressions.length < expressionLength){ - noExpressions = new Expression[expressionLength]; - //System.out.println("Resized EXPR stacks : "+ expressionLength); - } - System.arraycopy(noExpressions, 0, expressionStack, 0, expressionLength); - - // reset scanner state - scanner.commentPtr = -1; - scanner.eofPosition = Integer.MAX_VALUE; - - resetModifiers(); - - // recovery - lastCheckPoint = -1; - currentElement = null; - restartRecovery = false; - hasReportedError = false; - recoveredStaticInitializerStart = 0; - lastIgnoredToken = -1; - lastErrorEndPosition = -1; - listLength = 0; -} -public void initializeScanner(){ - this.scanner = new Scanner(false, false, this.problemReporter.options.getNonExternalizedStringLiteralSeverity() != ProblemSeverities.Ignore , this.assertMode); -} -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$ - symbol_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - action = lhs; -} -public final void jumpOverMethodBody() { - //on diet parsing.....do not buffer method statements + case 351 : // System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT AdditiveExpression"); + consumeBinaryExpression(OperatorExpression.RIGHT_SHIFT); + break; - //the scanner.diet is reinitialized to false - //automatically by the scanner once it has jumped over - //the statements + case 352 : // System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT AdditiveExpression"); + consumeBinaryExpression(OperatorExpression.UNSIGNED_RIGHT_SHIFT); + break; - if (diet && (dietInt == 0)) - scanner.diet = true; -} -protected void markCurrentMethodWithLocalType() { - 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 TypeDeclaration) { // mark type for now: all fields will be marked when added to this type - node.bits |= AstNode.HasLocalTypeMASK; - return; - } - } - // default to reference context (case of parse method body) - if (this.referenceContext instanceof AbstractMethodDeclaration - || this.referenceContext instanceof TypeDeclaration) { - ((AstNode)this.referenceContext).bits |= AstNode.HasLocalTypeMASK; - } -} -protected void markFieldsWithLocalType(TypeDeclaration type) { - if (type.fields == null || (type.bits & AstNode.HasLocalTypeMASK) == 0) return; - for (int i = 0, length = type.fields.length; i < length; i++) { - type.fields[i].bits |= AstNode.HasLocalTypeMASK; - } -} -/* - * Move checkpoint location (current implementation is moving it by one token) - * - * Answers true if successfully moved checkpoint (i.e. did not attempt to move it - * beyond end of file). - */ -protected boolean moveRecoveryCheckpoint() { - - int pos = lastCheckPoint; - /* reset scanner, and move checkpoint by one token */ - scanner.startPosition = pos; - scanner.currentPosition = pos; - scanner.diet = false; // quit jumping over method bodies - - /* if about to restart, then no need to shift token */ - if (restartRecovery){ - lastIgnoredToken = -1; - return true; - } - - /* protect against shifting on an invalid token */ - lastIgnoredToken = nextIgnoredToken; - nextIgnoredToken = -1; - do { - try { - nextIgnoredToken = scanner.getNextToken(); - if(scanner.currentPosition == scanner.startPosition){ - scanner.currentPosition++; // on fake completion identifier - nextIgnoredToken = -1; - } - - } catch(InvalidInputException e){ - pos = scanner.currentPosition; - } - } while (nextIgnoredToken < 0); - - if (nextIgnoredToken == TokenNameEOF) { // no more recovery after this point - if (currentToken == TokenNameEOF) { // already tried one iteration on EOF - return false; - } - } - lastCheckPoint = scanner.currentPosition; - - /* reset scanner again to previous checkpoint location*/ - scanner.startPosition = pos; - scanner.currentPosition = pos; - scanner.commentPtr = -1; - - return true; - -/* - The following implementation moves the checkpoint location by one line: - - int pos = lastCheckPoint; - // reset scanner, and move checkpoint by one token - scanner.startPosition = pos; - scanner.currentPosition = pos; - scanner.diet = false; // quit jumping over method bodies - - // if about to restart, then no need to shift token - if (restartRecovery){ - lastIgnoredToken = -1; - return true; - } - - // protect against shifting on an invalid token - lastIgnoredToken = nextIgnoredToken; - nextIgnoredToken = -1; - - boolean wasTokenizingWhiteSpace = scanner.tokenizeWhiteSpace; - scanner.tokenizeWhiteSpace = true; - checkpointMove: - do { - try { - nextIgnoredToken = scanner.getNextToken(); - switch(nextIgnoredToken){ - case Scanner.TokenNameWHITESPACE : - if(scanner.getLineNumber(scanner.startPosition) - == scanner.getLineNumber(scanner.currentPosition)){ - nextIgnoredToken = -1; - } - break; - case TokenNameSEMICOLON : - case TokenNameLBRACE : - case TokenNameRBRACE : - break; - case TokenNameIdentifier : - if(scanner.currentPosition == scanner.startPosition){ - scanner.currentPosition++; // on fake completion identifier - } - default: - nextIgnoredToken = -1; - break; - case TokenNameEOF : - break checkpointMove; - } - } catch(InvalidInputException e){ - pos = scanner.currentPosition; - } - } while (nextIgnoredToken < 0); - scanner.tokenizeWhiteSpace = wasTokenizingWhiteSpace; - - if (nextIgnoredToken == TokenNameEOF) { // no more recovery after this point - if (currentToken == TokenNameEOF) { // already tried one iteration on EOF - return false; - } - } - lastCheckPoint = scanner.currentPosition; - - // reset scanner again to previous checkpoint location - scanner.startPosition = pos; - scanner.currentPosition = pos; - scanner.commentPtr = -1; - - return true; -*/ -} -protected MessageSend newMessageSend() { - // '(' ArgumentListopt ')' - // the arguments are on the expression stack - - MessageSend m = new MessageSend(); - int length; - if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { - expressionPtr -= length; - System.arraycopy( - expressionStack, - expressionPtr + 1, - m.arguments = new Expression[length], - 0, - length); - }; - return m; -} -protected static int ntAction(int state, int sym) { - return action[state + sym]; -} -private final void optimizedConcatNodeLists() { - /*back from a recursive loop. Virtualy group the - astNode into an array using astLengthStack*/ - - /* - * This is a case where you have two sublists into the astStack that you want - * to merge in one list. There is no action required on the 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 astStack. - * Look at the InterfaceMemberDeclarations for an example. - * This case optimizes the fact that p == 1. - */ - - astLengthStack[--astLengthPtr]++; -} -protected static int original_state(int state) { - return -check(state); -} -/*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() { - - hasReportedError = false; - int act = START_STATE; - stateStackTop = -1; - currentToken = getFirstToken(); - ProcessTerminals : for (;;) { - try { - stack[++stateStackTop] = act; - } catch (IndexOutOfBoundsException e) { - int oldStackLength = stack.length; - int oldStack[] = stack; - stack = new int[oldStackLength + StackIncrement]; - System.arraycopy(oldStack, 0, stack, 0, oldStackLength); - stack[stateStackTop] = act; - }; - - act = tAction(act, currentToken); - - if (act == ERROR_ACTION || restartRecovery) { - int errorPos = scanner.currentPosition; - if (!hasReportedError){ - this.reportSyntaxError(ERROR_ACTION, currentToken, stateStackTop); - hasReportedError = true; - } - if (resumeOnSyntaxError()) { - if (act == ERROR_ACTION) lastErrorEndPosition = errorPos; - act = START_STATE; - stateStackTop = -1; - currentToken = getFirstToken(); - continue ProcessTerminals; - } else { - act = ERROR_ACTION; - } break ProcessTerminals; - } - if (act <= NUM_RULES) - stateStackTop--; - else - if (act > ERROR_ACTION) { /* shift-reduce */ - consumeToken(currentToken); - if (currentElement != null) this.recoveryTokenCheck(); - try{ - currentToken = scanner.getNextToken(); - } catch(InvalidInputException e){ - if (!hasReportedError){ - this.problemReporter().scannerError(this, e.getMessage()); - hasReportedError = true; - } - lastCheckPoint = scanner.currentPosition; - restartRecovery = true; - } - act -= ERROR_ACTION; - } else - if (act < ACCEPT_ACTION) { /* shift */ - consumeToken(currentToken); - if (currentElement != null) this.recoveryTokenCheck(); - try{ - currentToken = scanner.getNextToken(); - } catch(InvalidInputException e){ - if (!hasReportedError){ - this.problemReporter().scannerError(this, e.getMessage()); - hasReportedError = true; - } - lastCheckPoint = scanner.currentPosition; - restartRecovery = true; - } - continue ProcessTerminals; - } else - break ProcessTerminals; - - ProcessNonTerminals : do { /* reduce */ - consumeRule(act); - stateStackTop -= (rhs[act] - 1); - act = ntAction(stack[stateStackTop], lhs[act]); - } while (act <= NUM_RULES); - } - endParse(act); -} -// A P I - -public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { - //only parse the method body of cd - //fill out its statements - - //convert bugs into parse error - - initialize(); - goForConstructorBody(); - nestedMethod[nestedType]++; - - referenceContext = cd; - compilationUnit = unit; - - scanner.resetTo(cd.sourceEnd + 1, cd.declarationSourceEnd); - try { - parse(); - } catch (AbortCompilation ex) { - lastAct = ERROR_ACTION; - } finally { - nestedMethod[nestedType]--; - } - - if (lastAct == ERROR_ACTION) { - initialize(); - return; - } - - //statements - cd.explicitDeclarations = realBlockStack[realBlockPtr--]; - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) { - astPtr -= length; - if (astStack[astPtr + 1] instanceof ExplicitConstructorCall) - //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? - { - System.arraycopy( - astStack, - astPtr + 2, - cd.statements = new Statement[length - 1], - 0, - length - 1); - cd.constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1]; - } else { //need to add explicitly the super(); - System.arraycopy( - astStack, - astPtr + 1, - cd.statements = new Statement[length], - 0, - length); - cd.constructorCall = SuperReference.implicitSuperConstructorCall(); - } - } else { - cd.constructorCall = SuperReference.implicitSuperConstructorCall(); - } - - if (cd.constructorCall.sourceEnd == 0) { - cd.constructorCall.sourceEnd = cd.sourceEnd; - cd.constructorCall.sourceStart = cd.sourceStart; - } -} -// A P I - -public void parse( - Initializer ini, - TypeDeclaration type, - CompilationUnitDeclaration unit) { - //only parse the method body of md - //fill out method statements - - //convert bugs into parse error - - initialize(); - goForInitializer(); - nestedMethod[nestedType]++; - - referenceContext = type; - compilationUnit = unit; - - scanner.resetTo(ini.sourceStart, ini.sourceEnd); // just on the beginning { - try { - parse(); - } catch (AbortCompilation ex) { - lastAct = ERROR_ACTION; - } finally { - nestedMethod[nestedType]--; - } - - if (lastAct == ERROR_ACTION) { - return; - } - - ini.block = ((Initializer) astStack[astPtr]).block; - - // mark initializer with local type if one was found during parsing - if ((type.bits & AstNode.HasLocalTypeMASK) != 0) { - ini.bits |= AstNode.HasLocalTypeMASK; - } -} -// 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.isNative()) - return; - if ((md.modifiers & AccSemicolonBody) != 0) - return; - - initialize(); - goForMethodBody(); - nestedMethod[nestedType]++; - - referenceContext = md; - compilationUnit = unit; - - scanner.resetTo(md.sourceEnd + 1, md.declarationSourceEnd); - // reset the scanner to parser from { down to } - try { - parse(); - } catch (AbortCompilation ex) { - lastAct = ERROR_ACTION; - } finally { - nestedMethod[nestedType]--; - } - - if (lastAct == ERROR_ACTION) { - return; - } - - //refill statements - md.explicitDeclarations = realBlockStack[realBlockPtr--]; - int length; - if ((length = astLengthStack[astLengthPtr--]) != 0) - System.arraycopy( - astStack, - (astPtr -= length) + 1, - md.statements = new Statement[length], - 0, - length); -} -// A P I - -public CompilationUnitDeclaration parse( - ICompilationUnit sourceUnit, - CompilationResult compilationResult) { - // parses a compilation unit and manages error handling (even bugs....) - - CompilationUnitDeclaration unit; - try { - /* automaton initialization */ - initialize(); - goForCompilationUnit(); - - /* scanner initialization */ - scanner.setSource(sourceUnit.getContents()); - - /* unit creation */ - referenceContext = - compilationUnit = - new CompilationUnitDeclaration( - problemReporter, - compilationResult, - scanner.source.length); - /* run automaton */ - parse(); - } finally { - unit = compilationUnit; - compilationUnit = null; // reset parser - } - return unit; -} -// 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(); - goForCompilationUnit(); - - /* scanner initialization */ - scanner.setSource(sourceUnit.getContents()); - scanner.resetTo(start, end); - /* unit creation */ - referenceContext = - compilationUnit = - new CompilationUnitDeclaration( - problemReporter, - compilationResult, - scanner.source.length); - /* run automaton */ - parse(); - } finally { - unit = compilationUnit; - compilationUnit = null; // reset parser - } - return unit; -} -/** - * 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. - */ -public ProblemReporter problemReporter(){ - if (scanner.recordLineSeparator) { - compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); - } - problemReporter.referenceContext = referenceContext; - return 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 */ - - try { - identifierStack[++identifierPtr] = scanner.getCurrentIdentifierSource(); - identifierPositionStack[identifierPtr] = - (((long) scanner.startPosition) << 32) + (scanner.currentPosition - 1); - } catch (IndexOutOfBoundsException e) { - /*---stack reallaocation (identifierPtr is correct)---*/ - int oldStackLength = identifierStack.length; - char[][] oldStack = identifierStack; - identifierStack = new char[oldStackLength + 20][]; - System.arraycopy(oldStack, 0, identifierStack, 0, oldStackLength); - identifierStack[identifierPtr] = scanner.getCurrentTokenSource(); - /*identifier position stack*/ - long[] oldPos = identifierPositionStack; - identifierPositionStack = new long[oldStackLength + 20]; - System.arraycopy(oldPos, 0, identifierPositionStack, 0, oldStackLength); - identifierPositionStack[identifierPtr] = - (((long) scanner.startPosition) << 32) + (scanner.currentPosition - 1); - }; - - try { - identifierLengthStack[++identifierLengthPtr] = 1; - } catch (IndexOutOfBoundsException e) { - /*---stack reallocation (identifierLengthPtr is correct)---*/ - int oldStackLength = identifierLengthStack.length; - int oldStack[] = identifierLengthStack; - identifierLengthStack = new int[oldStackLength + 10]; - System.arraycopy(oldStack, 0, identifierLengthStack, 0, oldStackLength); - identifierLengthStack[identifierLengthPtr] = 1; - }; + case 354 : // System.out.println("RelationalExpression ::= RelationalExpression LESS ShiftExpression"); + consumeBinaryExpression(OperatorExpression.LESS); + break; -} -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 */ - - try { - identifierLengthStack[++identifierLengthPtr] = flag; - } catch (IndexOutOfBoundsException e) { - /*---stack reallaocation (identifierLengthPtr is correct)---*/ - int oldStackLength = identifierLengthStack.length; - int oldStack[] = identifierLengthStack; - identifierLengthStack = new int[oldStackLength + 10]; - System.arraycopy(oldStack, 0, identifierLengthStack, 0, oldStackLength); - identifierLengthStack[identifierLengthPtr] = flag; - }; + case 355 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER ShiftExpression"); + consumeBinaryExpression(OperatorExpression.GREATER); + break; -} -protected void pushOnAstLengthStack(int pos) { - try { - astLengthStack[++astLengthPtr] = pos; - } catch (IndexOutOfBoundsException e) { - int oldStackLength = astLengthStack.length; - int[] oldPos = astLengthStack; - astLengthStack = new int[oldStackLength + StackIncrement]; - System.arraycopy(oldPos, 0, astLengthStack, 0, oldStackLength); - astLengthStack[astLengthPtr] = pos; - } -} -protected void pushOnAstStack(AstNode node) { - /*add a new obj on top of the ast stack - astPtr points on the top*/ - - try { - astStack[++astPtr] = node; - } catch (IndexOutOfBoundsException e) { - int oldStackLength = astStack.length; - AstNode[] oldStack = astStack; - astStack = new AstNode[oldStackLength + AstStackIncrement]; - System.arraycopy(oldStack, 0, astStack, 0, oldStackLength); - astPtr = oldStackLength; - astStack[astPtr] = node; - } - - try { - astLengthStack[++astLengthPtr] = 1; - } catch (IndexOutOfBoundsException e) { - int oldStackLength = astLengthStack.length; - int[] oldPos = astLengthStack; - astLengthStack = new int[oldStackLength + AstStackIncrement]; - System.arraycopy(oldPos, 0, astLengthStack, 0, oldStackLength); - astLengthStack[astLengthPtr] = 1; - } -} -protected void pushOnExpressionStack(Expression expr) { - - try { - expressionStack[++expressionPtr] = expr; - } catch (IndexOutOfBoundsException e) { - //expressionPtr is correct - int oldStackLength = expressionStack.length; - Expression[] oldStack = expressionStack; - expressionStack = new Expression[oldStackLength + ExpressionStackIncrement]; - System.arraycopy(oldStack, 0, expressionStack, 0, oldStackLength); - expressionStack[expressionPtr] = expr; - } - - try { - expressionLengthStack[++expressionLengthPtr] = 1; - } catch (IndexOutOfBoundsException e) { - int oldStackLength = expressionLengthStack.length; - int[] oldPos = expressionLengthStack; - expressionLengthStack = new int[oldStackLength + ExpressionStackIncrement]; - System.arraycopy(oldPos, 0, expressionLengthStack, 0, oldStackLength); - expressionLengthStack[expressionLengthPtr] = 1; - } -} -protected void pushOnExpressionStackLengthStack(int pos) { - try { - expressionLengthStack[++expressionLengthPtr] = pos; - } catch (IndexOutOfBoundsException e) { - int oldStackLength = expressionLengthStack.length; - int[] oldPos = expressionLengthStack; - expressionLengthStack = new int[oldStackLength + StackIncrement]; - System.arraycopy(oldPos, 0, expressionLengthStack, 0, oldStackLength); - expressionLengthStack[expressionLengthPtr] = pos; - } -} -protected void pushOnIntStack(int pos) { - - try { - intStack[++intPtr] = pos; - } catch (IndexOutOfBoundsException e) { - //intPtr is correct - int oldStackLength = intStack.length; - int oldStack[] = intStack; - intStack = new int[oldStackLength + StackIncrement]; - System.arraycopy(oldStack, 0, intStack, 0, oldStackLength); - intStack[intPtr] = pos; - } -} -protected static char[] readTable(String filename) throws java.io.IOException { - - //files are located at Parser.class directory - - InputStream stream = new BufferedInputStream(Parser.class.getResourceAsStream(filename)); - if (stream == null) { - throw new java.io.IOException(Util.bind("parser.missingFile",filename)); //$NON-NLS-1$ - } - byte[] bytes = null; - try { - bytes = Util.getInputStreamAsByteArray(stream, -1); - } finally { - try { - stream.close(); - } catch (IOException e) { - } - } - - //minimal integrity check (even size expected) - int length = bytes.length; - if (length % 2 != 0) - throw new java.io.IOException(Util.bind("parser.corruptedFile",filename)); //$NON-NLS-1$ - - // 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; -} -/* Token check performed on every token shift once having entered - * recovery mode. - */ -public void recoveryTokenCheck() { - switch (currentToken) { - case TokenNameLBRACE : { - RecoveredElement newElement = - currentElement.updateOnOpeningBrace(scanner.currentPosition - 1); - lastCheckPoint = scanner.currentPosition; - if (newElement != null){ // null means nothing happened - restartRecovery = true; // opening brace detected - currentElement = newElement; - } - break; - } - case TokenNameRBRACE : { - endPosition = this.flushAnnotationsDefinedPriorTo(scanner.currentPosition - 1); - RecoveredElement newElement = - currentElement.updateOnClosingBrace(scanner.startPosition, scanner.currentPosition -1); - lastCheckPoint = scanner.currentPosition; - if (newElement != currentElement){ - currentElement = newElement; - } - } - } -} -protected void reportSyntaxError(int act, int currentKind, int stateStackTop) { - - /* remember current scanner position */ - int startPos = scanner.startPosition; - int currentPos = scanner.currentPosition; - - String[] expectings; - String tokenName = name[symbol_index[currentKind]]; - - //fetch all "accurate" possible terminals that could recover the error - int start, end = start = asi(stack[stateStackTop]); - while (asr[end] != 0) - end++; - int length = end - start; - expectings = new String[length]; - if (length != 0) { - char[] indexes = new char[length]; - System.arraycopy(asr, start, indexes, 0, length); - for (int i = 0; i < length; i++) { - expectings[i] = name[symbol_index[indexes[i]]]; - } - } - - //if the pb is an EOF, try to tell the user that they are some - if (tokenName.equals(UNEXPECTED_EOF)) { - if (!this.checkAndReportBracketAnomalies(problemReporter())) { - char[] tokenSource; - try { - tokenSource = this.scanner.getCurrentTokenSource(); - } catch (Exception e) { - tokenSource = new char[] {}; - } - problemReporter().parseError( - this.scanner.startPosition, - this.scanner.currentPosition - 1, - tokenSource, - tokenName, - expectings); - } - } else { //the next test is HEAVILY grammar DEPENDENT. - if ((length == 2) - && (tokenName.equals(";")) //$NON-NLS-1$ - && (expectings[0] == "++") //$NON-NLS-1$ - && (expectings[1] == "--") //$NON-NLS-1$ - && (expressionPtr > -1)) { - // the ; is not the expected token ==> it ends a statement when an expression is not ended - problemReporter().invalidExpressionAsStatement(expressionStack[expressionPtr]); - } else { - char[] tokenSource; - try { - tokenSource = this.scanner.getCurrentTokenSource(); - } catch (Exception e) { - tokenSource = new char[] {}; - } - problemReporter().parseError( - this.scanner.startPosition, - this.scanner.currentPosition - 1, - tokenSource, - tokenName, - expectings); - this.checkAndReportBracketAnomalies(problemReporter()); - } - } - /* reset scanner where it was */ - scanner.startPosition = startPos; - scanner.currentPosition = currentPos; -} -protected void resetModifiers() { - modifiers = AccDefault; - modifiersSourceStart = -1; // <-- see comment into modifiersFlag(int) - scanner.commentPtr = -1; -} -/* - * Reset context so as to resume to regular parse loop - */ -protected void resetStacks() { - - astPtr = -1; - astLengthPtr = -1; - expressionPtr = -1; - expressionLengthPtr = -1; - identifierPtr = -1; - identifierLengthPtr = -1; - intPtr = -1; - nestedMethod[nestedType = 0] = 0; // need to reset for further reuse - variablesCounter[nestedType] = 0; - dimensions = 0 ; - realBlockStack[realBlockPtr = 0] = 0; - recoveredStaticInitializerStart = 0; - listLength = 0; -} -/* - * Reset context so as to resume to regular parse loop - * If unable to reset for resuming, answers false. - * - * Move checkpoint location, reset internal stacks and - * decide which grammar goal is activated. - */ -protected boolean resumeAfterRecovery() { - - // reset internal stacks - this.resetStacks(); - - /* attempt to move checkpoint location */ - if (!this.moveRecoveryCheckpoint()) return false; - - // only look for headers - if (referenceContext instanceof CompilationUnitDeclaration){ - goForHeaders(); - diet = true; // passed this point, will not consider method bodies - return true; - } - // does not know how to restart - return false; -} -/* - * Syntax error was detected. Will attempt to perform some recovery action in order - * to resume to the regular parse loop. - */ -protected boolean resumeOnSyntaxError() { - - /* request recovery initialization */ - if (currentElement == null){ - currentElement = - this.buildInitialRecoveryState(); // build some recovered elements - } - /* do not investigate deeper in recovery when no recovered element */ - if (currentElement == null) return false; - - /* manual forced recovery restart - after headers */ - if (restartRecovery){ - 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(); -} -protected static int tAction(int state, int sym) { - return action[check(state + sym) == sym ? state + sym : state]; -} -public String toString() { - - String s = "identifierStack : char[][] = {"; //$NON-NLS-1$ - for (int i = 0; i <= identifierPtr; i++) { - s = s + "\"" + String.valueOf(identifierStack[i]) + "\","; //$NON-NLS-1$ //$NON-NLS-2$ - }; - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "identierLengthStack : int[] = {"; //$NON-NLS-1$ - for (int i = 0; i <= identifierLengthPtr; i++) { - s = s + identifierLengthStack[i] + ","; //$NON-NLS-1$ - }; - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "astLengthStack : int[] = {"; //$NON-NLS-1$ - for (int i = 0; i <= astLengthPtr; i++) { - s = s + astLengthStack[i] + ","; //$NON-NLS-1$ - }; - s = s + "}\n"; //$NON-NLS-1$ - s = s + "astPtr : int = " + String.valueOf(astPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - s = s + "intStack : int[] = {"; //$NON-NLS-1$ - for (int i = 0; i <= intPtr; i++) { - s = s + intStack[i] + ","; //$NON-NLS-1$ - }; - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "expressionLengthStack : int[] = {"; //$NON-NLS-1$ - for (int i = 0; i <= expressionLengthPtr; i++) { - s = s + expressionLengthStack[i] + ","; //$NON-NLS-1$ - }; - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "expressionPtr : int = " + String.valueOf(expressionPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - s = s + "\n\n\n----------------Scanner--------------\n" + scanner.toString(); //$NON-NLS-1$ - return s; + case 356 : // System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL ShiftExpression"); + consumeBinaryExpression(OperatorExpression.LESS_EQUAL); + break; -} -/* - * Update recovery state based on current parser/scanner state - */ -protected void updateRecoveryState() { - - /* expose parser state to recovery state */ - 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 + astStack[astPtr - variableDeclaratorsCounter + 1].sourceStart; - for (int i = 0; i < variableDeclaratorsCounter - 1; i++) { - //last one is special(see below) - field = (FieldDeclaration) astStack[astPtr - i - 1]; - field.endPart1Position = endTypeDeclarationPosition; - field.endPart2Position = -1 + astStack[astPtr - i].sourceStart; - } - //last one - (field = (FieldDeclaration) astStack[astPtr]).endPart1Position = - endTypeDeclarationPosition; - field.endPart2Position = field.declarationSourceEnd; + case 357 : // System.out.println("RelationalExpression ::= RelationalExpression GREATER_EQUAL ShiftExpression"); + consumeBinaryExpression(OperatorExpression.GREATER_EQUAL); + break; -} -protected void updateSourcePosition(Expression exp) { - //update the source Position of the expression + case 358 : // System.out.println("RelationalExpression ::= RelationalExpression instanceof ReferenceType"); + consumeInstanceOfExpression(OperatorExpression.INSTANCEOF); + break; - //intStack : int int - //--> - //intStack : + case 360 : // System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL RelationalExpression"); + consumeEqualityExpression(OperatorExpression.EQUAL_EQUAL); + break; - exp.sourceEnd = intStack[intPtr--]; - exp.sourceStart = intStack[intPtr--]; -} + case 361 : // System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL RelationalExpression"); + consumeEqualityExpression(OperatorExpression.NOT_EQUAL); + break; + + case 363 : // System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); + consumeBinaryExpression(OperatorExpression.AND); + break; + + case 365 : // System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR AndExpression"); + consumeBinaryExpression(OperatorExpression.XOR); + break; + + case 367 : // System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR ExclusiveOrExpression"); + consumeBinaryExpression(OperatorExpression.OR); + break; + + case 369 : // System.out.println("ConditionalAndExpression ::= ConditionalAndExpression AND_AND InclusiveOrExpression"); + consumeBinaryExpression(OperatorExpression.AND_AND); + break; + + case 371 : // System.out.println("ConditionalOrExpression ::= ConditionalOrExpression OR_OR ConditionalAndExpression"); + consumeBinaryExpression(OperatorExpression.OR_OR); + break; + + case 373 : // System.out.println("ConditionalExpression ::= ConditionalOrExpression QUESTION Expression COLON..."); + consumeConditionalExpression(OperatorExpression.QUESTIONCOLON); + break; + + case 376 : // System.out.println("Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression"); + consumeAssignment(); + break; + + case 378 : // System.out.println("Assignment ::= InvalidArrayInitializerAssignement"); + ignoreExpressionAssignment(); + break; + + case 379 : // System.out.println("LeftHandSide ::= Name"); + consumeLeftHandSide(); + break; + + case 382 : // System.out.println("AssignmentOperator ::= EQUAL"); + consumeAssignmentOperator(EQUAL); + break; + + case 383 : // System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); + consumeAssignmentOperator(MULTIPLY); + break; + + case 384 : // System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); + consumeAssignmentOperator(DIVIDE); + break; + + case 385 : // System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); + consumeAssignmentOperator(REMAINDER); + break; + + case 386 : // System.out.println("AssignmentOperator ::= PLUS_EQUAL"); + consumeAssignmentOperator(PLUS); + break; + + case 387 : // System.out.println("AssignmentOperator ::= MINUS_EQUAL"); + consumeAssignmentOperator(MINUS); + break; + + case 388 : // System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); + consumeAssignmentOperator(LEFT_SHIFT); + break; + + case 389 : // System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); + consumeAssignmentOperator(RIGHT_SHIFT); + break; + + case 390 : // System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); + consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT); + break; + + case 391 : // System.out.println("AssignmentOperator ::= AND_EQUAL"); + consumeAssignmentOperator(AND); + break; + + case 392 : // System.out.println("AssignmentOperator ::= XOR_EQUAL"); + consumeAssignmentOperator(XOR); + break; + + case 393 : // System.out.println("AssignmentOperator ::= OR_EQUAL"); + consumeAssignmentOperator(OR); + break; + + case 400 : // System.out.println("Expressionopt ::="); + consumeEmptyExpression(); + break; + + case 404 : // System.out.println("ImportDeclarationsopt ::="); + consumeEmptyImportDeclarationsopt(); + break; + + case 405 : // System.out.println("ImportDeclarationsopt ::= ImportDeclarations"); + consumeImportDeclarationsopt(); + break; + + case 406 : // System.out.println("TypeDeclarationsopt ::="); + consumeEmptyTypeDeclarationsopt(); + break; + + case 407 : // System.out.println("TypeDeclarationsopt ::= TypeDeclarations"); + consumeTypeDeclarationsopt(); + break; + + case 408 : // System.out.println("ClassBodyDeclarationsopt ::="); + consumeEmptyClassBodyDeclarationsopt(); + break; + + case 409 : // System.out.println("ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations"); + consumeClassBodyDeclarationsopt(); + break; + + case 410 : // System.out.println("Modifiersopt ::="); + consumeDefaultModifiers(); + break; + + case 411 : // System.out.println("Modifiersopt ::= Modifiers"); + consumeModifiers(); + break; + + case 412 : // System.out.println("BlockStatementsopt ::="); + consumeEmptyBlockStatementsopt(); + break; + + case 414 : // System.out.println("Dimsopt ::="); + consumeEmptyDimsopt(); + break; + + case 416 : // System.out.println("ArgumentListopt ::="); + consumeEmptyArgumentListopt(); + break; + + case 420 : // System.out.println("FormalParameterListopt ::="); + consumeFormalParameterListopt(); + break; + + case 424 : // System.out.println("InterfaceMemberDeclarationsopt ::="); + consumeEmptyInterfaceMemberDeclarationsopt(); + break; + + case 425 : // System.out.println("InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations"); + consumeInterfaceMemberDeclarationsopt(); + break; + + case 426 : // System.out.println("NestedType ::="); + consumeNestedType(); + break; + + case 427 : // System.out.println("ForInitopt ::="); + consumeEmptyForInitopt(); + break; + + case 429 : // System.out.println("ForUpdateopt ::="); + consumeEmptyForUpdateopt(); + break; + + case 433 : // System.out.println("Catchesopt ::="); + consumeEmptyCatchesopt(); + break; + + case 435 : // System.out.println("ArrayInitializeropt ::="); + consumeEmptyArrayInitializeropt(); + break; + + } + } + + protected void consumeSimpleAssertStatement() { + // AssertStatement ::= 'assert' Expression ';' + expressionLengthPtr--; + pushOnAstStack(new AssertStatement(expressionStack[expressionPtr--], intStack[intPtr--])); + } + + protected void consumeSingleTypeImportDeclaration() { + // SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName ';' + + ImportReference impt = (ImportReference) astStack[astPtr]; + // flush annotations defined prior to import statements + impt.declarationEnd = endStatementPosition; + impt.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(impt.declarationSourceEnd); + + // recovery + if (currentElement != null) { + lastCheckPoint = impt.declarationSourceEnd + 1; + currentElement = currentElement.add(impt, 0); + lastIgnoredToken = -1; + restartRecovery = true; + // used to avoid branching back into the regular automaton + } + } + protected void consumeSingleTypeImportDeclarationName() { + // SingleTypeImportDeclarationName ::= 'import' Name + /* push an ImportRef build from the last name + stored in the identifier stack. */ + + ImportReference impt; + int length; + char[][] tokens = new char[length = identifierLengthStack[identifierLengthPtr--]][]; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + System.arraycopy(identifierPositionStack, identifierPtr + 1, positions, 0, length); + pushOnAstStack(impt = new ImportReference(tokens, positions, false)); + + if (currentToken == TokenNameSEMICOLON) { + impt.declarationSourceEnd = scanner.currentPosition - 1; + } else { + impt.declarationSourceEnd = impt.sourceEnd; + } + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = intStack[intPtr--]; + + // recovery + if (currentElement != null) { + lastCheckPoint = impt.declarationSourceEnd + 1; + currentElement = currentElement.add(impt, 0); + lastIgnoredToken = -1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } + } + protected void consumeStatementBreak() { + // BreakStatement ::= 'break' ';' + // break pushs a position on intStack in case there is no label + + pushOnAstStack(new Break(null, intStack[intPtr--], endPosition)); + } + protected void consumeStatementBreakWithLabel() { + // BreakStatement ::= 'break' Identifier ';' + // break pushs a position on intStack in case there is no label + + pushOnAstStack(new Break(identifierStack[identifierPtr--], intStack[intPtr--], endPosition)); + 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 + + astLengthPtr--; + listLength = 0; // reset formalParameter counter (incremented for catch variable) + } + protected void consumeStatementContinue() { + // ContinueStatement ::= 'continue' ';' + // continue pushs a position on intStack in case there is no label + + pushOnAstStack(new Continue(null, intStack[intPtr--], endPosition)); + } + protected void consumeStatementContinueWithLabel() { + // ContinueStatement ::= 'continue' Identifier ';' + // continue pushs a position on intStack in case there is no label + + pushOnAstStack(new Continue(identifierStack[identifierPtr--], intStack[intPtr--], endPosition)); + identifierLengthPtr--; + } + protected void consumeStatementDo() { + // DoStatement ::= 'do' Statement 'while' '(' Expression ')' ';' + + //the 'while' pushes a value on intStack that we need to remove + intPtr--; + + //optimize the push/pop + Statement action = (Statement) astStack[astPtr]; + if (action instanceof EmptyStatement && problemReporter.options.complianceLevel <= CompilerOptions.JDK1_3) { + expressionLengthPtr--; + astStack[astPtr] = new DoStatement(expressionStack[expressionPtr--], null, intStack[intPtr--], endPosition); + } else { + expressionLengthPtr--; + astStack[astPtr] = new DoStatement(expressionStack[expressionPtr--], action, intStack[intPtr--], endPosition); + } + } + 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; + Statement action; + boolean scope = true; + + //statements + astLengthPtr--; // we need to consume it + action = (Statement) astStack[astPtr--]; + if (action instanceof EmptyStatement && problemReporter.options.complianceLevel <= CompilerOptions.JDK1_3) { + action = null; + } + + //updates are on the expresion stack + if ((length = expressionLengthStack[expressionLengthPtr--]) == 0) { + updates = null; + } else { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, updates = new Statement[length], 0, length); + } + + if (expressionLengthStack[expressionLengthPtr--] != 0) + cond = expressionStack[expressionPtr--]; + + //inits may be on two different stacks + if ((length = astLengthStack[astLengthPtr--]) == 0) { + inits = null; + scope = false; + } else { + if (length == -1) { //on expressionStack + scope = false; + length = expressionLengthStack[expressionLengthPtr--]; + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, inits = new Statement[length], 0, length); + } else { //on astStack + astPtr -= length; + System.arraycopy(astStack, astPtr + 1, inits = new Statement[length], 0, length); + } + }; + if (action instanceof Block) { + pushOnAstStack(new ForStatement(inits, cond, updates, action, scope, intStack[intPtr--], endStatementPosition)); + } else { + pushOnAstStack(new ForStatement(inits, cond, updates, action, scope, intStack[intPtr--], endPosition)); + } + } + protected void consumeStatementIfNoElse() { + // IfThenStatement ::= 'if' '(' Expression ')' Statement + + //optimize the push/pop + expressionLengthPtr--; + Statement thenStatement = (Statement) astStack[astPtr]; + if (thenStatement instanceof Block) { + astStack[astPtr] = new IfStatement(expressionStack[expressionPtr--], thenStatement, intStack[intPtr--], endStatementPosition); + } else if (thenStatement instanceof EmptyStatement) { + astStack[astPtr] = new IfStatement(expressionStack[expressionPtr--], Block.None, intStack[intPtr--], endStatementPosition); + } else { + astStack[astPtr] = new IfStatement(expressionStack[expressionPtr--], thenStatement, intStack[intPtr--], endStatementPosition); + } + } + protected void consumeStatementIfWithElse() { + // IfThenElseStatement ::= 'if' '(' Expression ')' StatementNoShortIf 'else' Statement + // IfThenElseStatementNoShortIf ::= 'if' '(' Expression ')' StatementNoShortIf 'else' StatementNoShortIf + + astLengthPtr--; // optimized {..., Then, Else } ==> {..., If } + expressionLengthPtr--; + //optimize the push/pop + Statement elseStatement = (Statement) astStack[astPtr--]; + Statement thenStatement = (Statement) astStack[astPtr]; + if (elseStatement instanceof EmptyStatement) { + elseStatement = Block.None; + } + if (thenStatement instanceof EmptyStatement) { + thenStatement = Block.None; + } + if (elseStatement instanceof Block) { + astStack[astPtr] = + new IfStatement(expressionStack[expressionPtr--], thenStatement, elseStatement, intStack[intPtr--], endStatementPosition); + } else { + astStack[astPtr] = + new IfStatement(expressionStack[expressionPtr--], thenStatement, elseStatement, intStack[intPtr--], endStatementPosition); + } + } + protected void consumeStatementLabel() { + // LabeledStatement ::= 'Identifier' ':' Statement + // LabeledStatementNoShortIf ::= 'Identifier' ':' StatementNoShortIf + + //optimize push/pop + + Statement stmt = (Statement) astStack[astPtr]; + if (stmt instanceof EmptyStatement) { + astStack[astPtr] = + new LabeledStatement( + identifierStack[identifierPtr], + Block.None, + (int) (identifierPositionStack[identifierPtr--] >>> 32), + endStatementPosition); + } else { + astStack[astPtr] = + new LabeledStatement( + identifierStack[identifierPtr], + stmt, + (int) (identifierPositionStack[identifierPtr--] >>> 32), + endStatementPosition); + } + identifierLengthPtr--; + } + protected void consumeStatementReturn() { + // ReturnStatement ::= 'return' Expressionopt ';' + // return pushs a position on intStack in case there is no expression + + if (expressionLengthStack[expressionLengthPtr--] != 0) { + pushOnAstStack(new ReturnStatement(expressionStack[expressionPtr--], intStack[intPtr--], endPosition)); + } else { + pushOnAstStack(new ReturnStatement(null, intStack[intPtr--], endPosition)); + } + } + 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 s = new SwitchStatement(); + expressionLengthPtr--; + s.testExpression = expressionStack[expressionPtr--]; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + astPtr -= length; + System.arraycopy(astStack, astPtr + 1, s.statements = new Statement[length], 0, length); + } + s.explicitDeclarations = realBlockStack[realBlockPtr--]; + pushOnAstStack(s); + intPtr--; // because of OpenBlock + s.sourceStart = intStack[intPtr--]; + s.sourceEnd = endStatementPosition; + } + protected void consumeStatementSynchronized() { + // SynchronizedStatement ::= OnlySynchronized '(' Expression ')' Block + //optimize the push/pop + + if (astLengthStack[astLengthPtr] == 0) { + astLengthStack[astLengthPtr] = 1; + expressionLengthPtr--; + astStack[++astPtr] = + new SynchronizedStatement(expressionStack[expressionPtr--], Block.None, intStack[intPtr--], endStatementPosition); + } else { + expressionLengthPtr--; + astStack[astPtr] = + new SynchronizedStatement( + expressionStack[expressionPtr--], + (Block) astStack[astPtr], + intStack[intPtr--], + endStatementPosition); + } + resetModifiers(); + } + protected void consumeStatementThrow() { + // ThrowStatement ::= 'throw' Expression ';' + expressionLengthPtr--; + pushOnAstStack(new ThrowStatement(expressionStack[expressionPtr--], intStack[intPtr--])); + } + protected void consumeStatementTry(boolean withFinally) { + //TryStatement ::= 'try' Block Catches + //TryStatement ::= 'try' Block Catchesopt Finally + + int length; + TryStatement tryStmt = new TryStatement(); + //finally + if (withFinally) { + astLengthPtr--; + tryStmt.finallyBlock = (Block) astStack[astPtr--]; + } + //catches are handle by two [see statementCatch] + if ((length = astLengthStack[astLengthPtr--]) != 0) { + if (length == 1) { + tryStmt.catchBlocks = new Block[] {(Block) astStack[astPtr--] }; + tryStmt.catchArguments = new Argument[] {(Argument) astStack[astPtr--] }; + } else { + Block[] bks = (tryStmt.catchBlocks = new Block[length]); + Argument[] args = (tryStmt.catchArguments = new Argument[length]); + while (length-- > 0) { + bks[length] = (Block) astStack[astPtr--]; + args[length] = (Argument) astStack[astPtr--]; + } + } + } + //try + astLengthPtr--; + tryStmt.tryBlock = (Block) astStack[astPtr--]; + + //positions + tryStmt.sourceEnd = endStatementPosition; + tryStmt.sourceStart = intStack[intPtr--]; + pushOnAstStack(tryStmt); + } + protected void consumeStatementWhile() { + // WhileStatement ::= 'while' '(' Expression ')' Statement + // WhileStatementNoShortIf ::= 'while' '(' Expression ')' StatementNoShortIf + + Statement action = (Statement) astStack[astPtr]; + expressionLengthPtr--; + if (action instanceof Block) { + astStack[astPtr] = new WhileStatement(expressionStack[expressionPtr--], action, intStack[intPtr--], endStatementPosition); + } else { + if (action instanceof EmptyStatement && problemReporter.options.complianceLevel <= CompilerOptions.JDK1_3) { + astStack[astPtr] = new WhileStatement(expressionStack[expressionPtr--], null, intStack[intPtr--], endPosition); + } else { + astStack[astPtr] = new WhileStatement(expressionStack[expressionPtr--], action, intStack[intPtr--], endPosition); + } + } + } + protected void consumeStaticInitializer() { + // StaticInitializer ::= StaticOnly Block + //push an Initializer + //optimize the push/pop + Initializer initializer = new Initializer((Block) astStack[astPtr], AccStatic); + astStack[astPtr] = initializer; + initializer.sourceEnd = endStatementPosition; + initializer.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + nestedMethod[nestedType]--; + initializer.declarationSourceStart = intStack[intPtr--]; + + // recovery + if (currentElement != null) { + lastCheckPoint = initializer.declarationSourceEnd; + currentElement = currentElement.add(initializer, 0); + lastIgnoredToken = -1; + } + } + protected void consumeStaticOnly() { + // StaticOnly ::= 'static' + int savedModifiersSourceStart = modifiersSourceStart; + checkAnnotation(); // might update declaration source start + if (modifiersSourceStart >= savedModifiersSourceStart) { + modifiersSourceStart = savedModifiersSourceStart; + } + pushOnIntStack(modifiersSourceStart >= 0 ? modifiersSourceStart : scanner.startPosition); + jumpOverMethodBody(); + nestedMethod[nestedType]++; + resetModifiers(); + + // recovery + if (currentElement != null) { + recoveredStaticInitializerStart = intStack[intPtr]; // remember start position only for static initializers + } + } + 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 */ + if (scanner.wasNonExternalizedStringLiteral) { + StringLiteral[] literals = this.scanner.nonNLSStrings; + // could not reproduce, but this is the only NPE + // added preventive null check see PR 9035 + if (literals != null) { + for (int i = 0, max = literals.length; i < max; i++) { + problemReporter().nonExternalizedStringLiteral(literals[i]); + } + } + scanner.currentLine = null; + scanner.wasNonExternalizedStringLiteral = false; + } + // 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 : + scanner.commentPtr = -1; + } + //System.out.println(scanner.toStringAction(type)); + switch (type) { + case TokenNameIdentifier : + pushIdentifier(); + if (scanner.useAssertAsAnIndentifier) { + long positions = identifierPositionStack[identifierPtr]; + problemReporter().useAssertAsAnIdentifier((int) (positions >>> 32), (int) positions); + } + scanner.commentPtr = -1; + break; + // case TokenNameinterface : + // adjustInterfaceModifiers(); + // //'class' is pushing two int (positions) on the stack ==> 'interface' needs to do it too.... + // pushOnIntStack(scanner.startPosition); + // pushOnIntStack(scanner.currentPosition - 1); + // scanner.commentPtr = -1; + // break; + // case TokenNameabstract : + // checkAndSetModifiers(AccAbstract); + // break; + // case TokenNamestrictfp : + // checkAndSetModifiers(AccStrictfp); + // break; + // case TokenNamefinal : + // checkAndSetModifiers(AccFinal); + // break; + // case TokenNamenative : + // checkAndSetModifiers(AccNative); + // break; + // case TokenNameprivate : + // checkAndSetModifiers(AccPrivate); + // break; + // case TokenNameprotected : + // checkAndSetModifiers(AccProtected); + // break; + // case TokenNamepublic : + // checkAndSetModifiers(AccPublic); + // break; + // case TokenNametransient : + // checkAndSetModifiers(AccTransient); + // break; + // case TokenNamevolatile : + // checkAndSetModifiers(AccVolatile); + // break; + case TokenNamestatic : + checkAndSetModifiers(AccStatic); + break; + // case TokenNamesynchronized : + // this.synchronizedBlockSourceStart = scanner.startPosition; + // checkAndSetModifiers(AccSynchronized); + // break; + // //============================== + // case TokenNamevoid : + // pushIdentifier(-T_void); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // 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 intStack + // case TokenNameboolean : + // pushIdentifier(-T_boolean); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNamebyte : + // pushIdentifier(-T_byte); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNamechar : + // pushIdentifier(-T_char); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNamedouble : + // pushIdentifier(-T_double); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNamefloat : + // pushIdentifier(-T_float); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNameint : + // pushIdentifier(-T_int); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNamelong : + // pushIdentifier(-T_long); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + // case TokenNameshort : + // pushIdentifier(-T_short); + // pushOnIntStack(scanner.currentPosition - 1); + // pushOnIntStack(scanner.startPosition); + // scanner.commentPtr = -1; + // break; + //============================== + case TokenNameIntegerLiteral : + pushOnExpressionStack(new IntLiteral(scanner.getCurrentTokenSource(), scanner.startPosition, scanner.currentPosition - 1)); + scanner.commentPtr = -1; + break; + case TokenNameLongLiteral : + pushOnExpressionStack(new LongLiteral(scanner.getCurrentTokenSource(), scanner.startPosition, scanner.currentPosition - 1)); + scanner.commentPtr = -1; + break; + case TokenNameFloatingPointLiteral : + pushOnExpressionStack( + new FloatLiteral(scanner.getCurrentTokenSource(), scanner.startPosition, scanner.currentPosition - 1)); + scanner.commentPtr = -1; + break; + case TokenNameDoubleLiteral : + pushOnExpressionStack( + new DoubleLiteral(scanner.getCurrentTokenSource(), scanner.startPosition, scanner.currentPosition - 1)); + scanner.commentPtr = -1; + break; + case TokenNameCharacterLiteral : + pushOnExpressionStack(new CharLiteral(scanner.getCurrentTokenSource(), scanner.startPosition, scanner.currentPosition - 1)); + scanner.commentPtr = -1; + break; + case TokenNameStringLiteral : + StringLiteral stringLiteral = + new StringLiteral(scanner.getCurrentTokenSourceString(), scanner.startPosition, scanner.currentPosition - 1); + pushOnExpressionStack(stringLiteral); + scanner.commentPtr = -1; + break; + case TokenNamefalse : + pushOnExpressionStack(new FalseLiteral(scanner.startPosition, scanner.currentPosition - 1)); + scanner.commentPtr = -1; + break; + case TokenNametrue : + pushOnExpressionStack(new TrueLiteral(scanner.startPosition, scanner.currentPosition - 1)); + break; + case TokenNamenull : + pushOnExpressionStack(new NullLiteral(scanner.startPosition, scanner.currentPosition - 1)); + break; + //============================ + // case TokenNamesuper : + // case TokenNamethis : + // endPosition = scanner.currentPosition - 1; + // pushOnIntStack(scanner.startPosition); + // break; + // case TokenNameassert : + // case TokenNameimport : + // case TokenNamepackage : + // case TokenNamethrow : + case TokenNamenew : + case TokenNamedo : + case TokenNameif : + case TokenNamefor : + case TokenNameswitch : + // case TokenNametry : + case TokenNamewhile : + case TokenNamebreak : + case TokenNamecontinue : + case TokenNamereturn : + case TokenNamecase : + pushOnIntStack(scanner.startPosition); + break; + case TokenNameclass : + pushOnIntStack(scanner.currentPosition - 1); + pushOnIntStack(scanner.startPosition); + break; + case TokenNamedefault : + pushOnIntStack(scanner.startPosition); + pushOnIntStack(scanner.currentPosition - 1); + break; + //let extra semantic action decide when to push + case TokenNameRBRACKET : + case TokenNamePLUS : + case TokenNameMINUS : + case TokenNameNOT : + case TokenNameTWIDDLE : + endPosition = scanner.startPosition; + break; + case TokenNamePLUS_PLUS : + case TokenNameMINUS_MINUS : + endPosition = scanner.startPosition; + endStatementPosition = scanner.currentPosition - 1; + break; + case TokenNameRBRACE : + case TokenNameSEMICOLON : + endStatementPosition = scanner.currentPosition - 1; + endPosition = scanner.startPosition - 1; + //the item is not part of the potential futur expression/statement + break; + // in order to handle ( expression) ////// (cast)expression///// foo(x) + case TokenNameRPAREN : + rParenPos = scanner.currentPosition - 1; // position of the end of right parenthesis (in case of unicode \u0029) lex00101 + break; + case TokenNameLPAREN : + lParenPos = scanner.startPosition; + break; + // case TokenNameQUESTION : + // 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 : + // case TokenNameLESS : + } + } + protected void consumeTypeDeclarations() { + // TypeDeclarations ::= TypeDeclarations TypeDeclaration + concatNodeLists(); + } + protected void consumeTypeDeclarationsopt() { + // TypeDeclarationsopt ::= TypeDeclarations + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + astPtr -= length; + System.arraycopy(astStack, astPtr + 1, compilationUnit.types = new TypeDeclaration[length], 0, length); + } + } + protected void consumeTypeImportOnDemandDeclaration() { + // TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName ';' + + ImportReference impt = (ImportReference) astStack[astPtr]; + // flush annotations defined prior to import statements + impt.declarationEnd = endStatementPosition; + impt.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(impt.declarationSourceEnd); + + // recovery + if (currentElement != null) { + lastCheckPoint = impt.declarationSourceEnd + 1; + currentElement = currentElement.add(impt, 0); + restartRecovery = true; + lastIgnoredToken = -1; + // used to avoid branching back into the regular automaton + } + } + protected void consumeTypeImportOnDemandDeclarationName() { + // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' + /* push an ImportRef build from the last name + stored in the identifier stack. */ + + ImportReference impt; + int length; + char[][] tokens = new char[length = identifierLengthStack[identifierLengthPtr--]][]; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + System.arraycopy(identifierPositionStack, identifierPtr + 1, positions, 0, length); + pushOnAstStack(impt = new ImportReference(tokens, positions, true)); + + if (currentToken == TokenNameSEMICOLON) { + impt.declarationSourceEnd = scanner.currentPosition - 1; + } else { + impt.declarationSourceEnd = impt.sourceEnd; + } + impt.declarationEnd = impt.declarationSourceEnd; + //endPosition is just before the ; + impt.declarationSourceStart = intStack[intPtr--]; + + // recovery + if (currentElement != null) { + lastCheckPoint = impt.declarationSourceEnd + 1; + currentElement = currentElement.add(impt, 0); + lastIgnoredToken = -1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } + } + 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 ............ + + //intStack have the position of the operator + + Expression r, exp = expressionStack[expressionPtr]; + if (op == MINUS) { + if ((exp instanceof IntLiteral) && (((IntLiteral) exp).mayRepresentMIN_VALUE())) { + r = expressionStack[expressionPtr] = new IntLiteralMinValue(); + } else { + if ((exp instanceof LongLiteral) && (((LongLiteral) exp).mayRepresentMIN_VALUE())) { + r = expressionStack[expressionPtr] = new LongLiteralMinValue(); + } else { + r = expressionStack[expressionPtr] = new UnaryExpression(exp, op); + } + } + } else { + r = expressionStack[expressionPtr] = new UnaryExpression(exp, op); + } + r.sourceStart = intStack[intPtr--]; + r.sourceEnd = exp.sourceEnd; + } + protected void consumeUnaryExpression(int op, boolean post) { + // PreIncrementExpression ::= '++' PushPosition UnaryExpression + // PreDecrementExpression ::= '--' PushPosition UnaryExpression + + // ++ and -- operators + //optimize the push/pop + + //intStack has the position of the operator when prefix + + Expression leftHandSide = expressionStack[expressionPtr]; + if (leftHandSide instanceof Reference) { + // ++foo()++ is unvalid + if (post) { + expressionStack[expressionPtr] = new PostfixExpression(leftHandSide, IntLiteral.One, op, endStatementPosition); + } else { + expressionStack[expressionPtr] = new PrefixExpression(leftHandSide, IntLiteral.One, op, intStack[intPtr--]); + } + } else { + //the ++ or the -- is NOT taken into account if code gen proceeds + if (!post) { + intPtr--; + } + problemReporter().invalidUnaryExpression(leftHandSide); + } + } + protected void consumeVariableDeclarators() { + // VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator + optimizedConcatNodeLists(); + } + protected void consumeVariableInitializers() { + // VariableInitializers ::= VariableInitializers ',' VariableInitializer + concatExpressionLists(); + } + protected TypeReference copyDims(TypeReference typeRef, int dim) { + return typeRef.copyDims(dim); + } + protected FieldDeclaration createFieldDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { + return new FieldDeclaration(null, name, sourceStart, sourceEnd); + } + + protected LocalDeclaration createLocalDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { + return new LocalDeclaration(null, name, sourceStart, sourceEnd); + } + + public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) { + + CompilationUnitDeclaration parsedUnit; + boolean old = diet; + try { + diet = true; + parsedUnit = parse(sourceUnit, compilationResult); + } finally { + diet = old; + } + return parsedUnit; + } + protected void dispatchDeclarationInto(int length) { + /* they are length on astStack that should go into + methods fields constructors lists of the typeDecl + + Return if there is a constructor declaration in the methods declaration */ + + // Looks for the size of each array . + + if (length == 0) + return; + int[] flag = new int[length + 1]; //plus one -- see + int size1 = 0, size2 = 0, size3 = 0; + for (int i = length - 1; i >= 0; i--) { + AstNode astNode = astStack[astPtr--]; + if (astNode instanceof AbstractMethodDeclaration) { + //methods and constructors have been regrouped into one single list + flag[i] = 3; + size2++; + } else { + if (astNode instanceof TypeDeclaration) { + flag[i] = 4; + size3++; + } else { + //field + flag[i] = 1; + size1++; + } + } + } + + //arrays creation + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + if (size1 != 0) + typeDecl.fields = new FieldDeclaration[size1]; + if (size2 != 0) + typeDecl.methods = new AbstractMethodDeclaration[size2]; + if (size3 != 0) + typeDecl.memberTypes = new MemberTypeDeclaration[size3]; + + //arrays fill up + size1 = size2 = size3 = 0; + int flagI = flag[0], start = 0; + int length2; + for (int end = 0; end <= length; end++) // the plus one allows to + { + if (flagI != flag[end]) //treat the last element as a ended flag..... + { //array copy + switch (flagI) { + case 1 : + size1 += (length2 = end - start); + System.arraycopy(astStack, astPtr + start + 1, typeDecl.fields, size1 - length2, length2); + break; + case 3 : + size2 += (length2 = end - start); + System.arraycopy(astStack, astPtr + start + 1, typeDecl.methods, size2 - length2, length2); + break; + case 4 : + size3 += (length2 = end - start); + System.arraycopy(astStack, 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 CompilationUnitDeclaration endParse(int act) { + + this.lastAct = act; + + if (currentElement != null) { + currentElement.topElement().updateParseTree(); + if (VERBOSE_RECOVERY) { + System.out.print(Util.bind("parser.syntaxRecovery")); //$NON-NLS-1$ + System.out.println("--------------------------"); //$NON-NLS-1$ + System.out.println(compilationUnit); + System.out.println("----------------------------------"); //$NON-NLS-1$ + } + } else { + if (diet & VERBOSE_RECOVERY) { + System.out.print(Util.bind("parser.regularParse")); //$NON-NLS-1$ + System.out.println("--------------------------"); //$NON-NLS-1$ + System.out.println(compilationUnit); + System.out.println("----------------------------------"); //$NON-NLS-1$ + } + } + if (scanner.recordLineSeparator) { + compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); + } + return compilationUnit; + } + /* + * Flush annotations defined prior to a given positions. + * + * Note: annotations are stacked in syntactical order + * + * Either answer given , or the end position of a comment line + * immediately following the (same line) + * + * e.g. + * void foo(){ + * } // end of method foo + */ + + public int flushAnnotationsDefinedPriorTo(int position) { + + int lastAnnotationIndex = scanner.commentPtr; + if (lastAnnotationIndex < 0) + return position; // no comment + + // compute the index of the first obsolete comment + int index = lastAnnotationIndex; + int validCount = 0; + while (index >= 0) { + int commentEnd = scanner.commentStops[index]; + if (commentEnd < 0) + commentEnd = -commentEnd; // negative end position for non-javadoc comments + if (commentEnd <= position) { + break; + } + index--; + validCount++; + } + // if the source at is immediately followed by a line comment, then + // flush this comment and shift to the comment end. + if (validCount > 0) { + int immediateCommentEnd = -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 (scanner.getLineNumber(position) == scanner.getLineNumber(immediateCommentEnd)) { + position = immediateCommentEnd; + validCount--; // flush this comment + index++; + } + } + } + // position can be located in the middle of a line break + // this is a bug on Windows platform only. + // http://dev.eclipse.org/bugs/show_bug.cgi?id=10557 + char[] source = scanner.source; + + if ((position < source.length) + && (source[position] == '\r') + && ((position + 1) < source.length) + && (source[position + 1] == '\n')) { + position++; + } + if (index < 0) + return position; // no obsolete comment + + if (validCount > 0) { // move valid comment infos, overriding obsolete comment infos + System.arraycopy(scanner.commentStarts, index + 1, scanner.commentStarts, 0, validCount); + System.arraycopy(scanner.commentStops, index + 1, scanner.commentStops, 0, validCount); + } + scanner.commentPtr = validCount - 1; + return position; + } + public final 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 ::= '++' CompilationUnit + // 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 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 = scanner.commentPtr; i <= max; i++) { + // javadoc only (non javadoc comment have negative end positions.) + if (scanner.commentStops[i] > 0) { + javadocCount++; + } + } + if (javadocCount == 0) + return null; + + int[] positions = new int[2 * javadocCount]; + int index = 0; + for (int i = 0, max = scanner.commentPtr; i <= max; i++) { + // javadoc only (non javadoc comment have negative end positions.) + if (scanner.commentStops[i] > 0) { + positions[index++] = scanner.commentStarts[i]; + positions[index++] = scanner.commentStops[i] - 1; //stop is one over + } + } + return positions; + } + protected 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. + } + + //real parse of the method.... + this.scanner.setSource(unit.compilationResult.compilationUnit.getContents()); + if (unit.types != null) { + for (int i = unit.types.length; --i >= 0;) + unit.types[i].parseMethod(this, unit); + } + } + 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*/ + + int length; + TypeReference ref; + if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) { + // single variable reference + if (dim == 0) { + ref = new SingleTypeReference(identifierStack[identifierPtr], identifierPositionStack[identifierPtr--]); + } else { + ref = new ArrayTypeReference(identifierStack[identifierPtr], dim, identifierPositionStack[identifierPtr--]); + ref.sourceEnd = endPosition; + } + } else { + if (length < 0) { //flag for precompiled type reference on base types + ref = TypeReference.baseTypeReference(-length, dim); + ref.sourceStart = intStack[intPtr--]; + if (dim == 0) { + ref.sourceEnd = intStack[intPtr--]; + } else { + intPtr--; + ref.sourceEnd = endPosition; + } + } else { //Qualified variable reference + 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) { + ref = new QualifiedTypeReference(tokens, positions); + } else { + ref = new ArrayQualifiedTypeReference(tokens, dim, positions); + ref.sourceEnd = endPosition; + } + } + }; + return ref; + } + protected Expression getTypeReference(Expression exp) { + + exp.bits &= ~AstNode.RestrictiveFlagMASK; + exp.bits |= TYPE; + return exp; + } + protected NameReference getUnspecifiedReference() { + /* build a (unspecified) NameReference which may be qualified*/ + + int length; + NameReference ref; + if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) + // single variable reference + ref = new SingleNameReference(identifierStack[identifierPtr], identifierPositionStack[identifierPtr--]); + else + //Qualified variable reference + { + char[][] tokens = new char[length][]; + identifierPtr -= length; + System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + ref = new QualifiedNameReference(tokens, (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart + (int) identifierPositionStack[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 = identifierLengthStack[identifierLengthPtr--]) == 1) { + // single variable reference + ref = new SingleNameReference(identifierStack[identifierPtr], identifierPositionStack[identifierPtr--]); + ref.bits &= ~AstNode.RestrictiveFlagMASK; + ref.bits |= LOCAL | 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][]; + identifierPtr -= length; + System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length); + ref = new QualifiedNameReference(tokens, (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart + (int) identifierPositionStack[identifierPtr + length]); // sourceEnd + ref.bits &= ~AstNode.RestrictiveFlagMASK; + ref.bits |= LOCAL | FIELD; + return ref; + } + public void goForBlockStatementsOrMethodHeaders() { + //tells the scanner to go for block statements or method headers parsing + + firstToken = TokenNameMULTIPLY; + scanner.recordLineSeparator = false; + } + public void goForClassBodyDeclarations() { + //tells the scanner to go for any body declarations parsing + + firstToken = TokenNameAND; + scanner.recordLineSeparator = true; + } + public void goForCompilationUnit() { + //tells the scanner to go for compilation unit parsing + + firstToken = TokenNamePLUS_PLUS; + scanner.linePtr = -1; + scanner.recordLineSeparator = true; + scanner.currentLine = null; + scanner.lines = new ArrayList(); + } + public void goForConstructorBody() { + //tells the scanner to go for compilation unit parsing + + firstToken = TokenNameEQUAL_EQUAL; + scanner.recordLineSeparator = false; + } + public void goForExpression() { + //tells the scanner to go for an expression parsing + + firstToken = TokenNameREMAINDER; + scanner.recordLineSeparator = false; + } + public void goForFieldDeclaration() { + //tells the scanner to go for field declaration parsing + + firstToken = TokenNameAND_AND; + scanner.recordLineSeparator = true; + } + public void goForGenericMethodDeclaration() { + //tells the scanner to go for generic method declarations parsing + + firstToken = TokenNameDIVIDE; + scanner.recordLineSeparator = true; + } + public void goForHeaders() { + //tells the scanner to go for headers only parsing + + firstToken = TokenNameUNSIGNED_RIGHT_SHIFT; + scanner.recordLineSeparator = true; + } + public void goForImportDeclaration() { + //tells the scanner to go for import declaration parsing + + firstToken = TokenNameOR_OR; + scanner.recordLineSeparator = true; + } + public void goForInitializer() { + //tells the scanner to go for initializer parsing + + firstToken = TokenNameRIGHT_SHIFT; + scanner.recordLineSeparator = false; + } + public void goForMethodBody() { + //tells the scanner to go for method body parsing + + firstToken = TokenNameMINUS_MINUS; + scanner.recordLineSeparator = false; + } + public void goForPackageDeclaration() { + //tells the scanner to go for package declaration parsing + + firstToken = TokenNameQUESTION; + scanner.recordLineSeparator = true; + } + public void goForTypeDeclaration() { + //tells the scanner to go for type (interface or class) declaration parsing + + firstToken = TokenNamePLUS; + scanner.recordLineSeparator = true; + } + public final static void grammar() { + /* + --main options + %options ACTION, AN=JavaAction.java, GP=java, + %options FILE-PREFIX=java, ESCAPE=$, PREFIX=TokenName, OUTPUT-SIZE=125 , + %options NOGOTO-DEFAULT, SINGLE-PRODUCTIONS, LALR=1 , TABLE=TIME , + + --error recovering options..... + %options ERROR_MAPS + + --grammar understanding options + %options first follow + %options TRACE=FULL , + %options VERBOSE + + --Usefull macros helping reading/writing semantic actions + $Define + $putCase + /. case $rule_number : // System.out.println("$rule_text"); + ./ + + $break + /. + break ; + ./ + + -- here it starts really ------------------------------------------ + $Terminals + + Identifier + + abstract assert boolean break byte case catch char class + continue default do double else extends false final finally float + for if implements import instanceof int + interface long native new null package private + protected public return short static strictfp super switch + synchronized this throw throws transient true try void + volatile while + + IntegerLiteral + LongLiteral + FloatingPointLiteral + DoubleLiteral + CharacterLiteral + StringLiteral + + PLUS_PLUS + MINUS_MINUS + EQUAL_EQUAL + LESS_EQUAL + GREATER_EQUAL + NOT_EQUAL + LEFT_SHIFT + RIGHT_SHIFT + UNSIGNED_RIGHT_SHIFT + PLUS_EQUAL + MINUS_EQUAL + MULTIPLY_EQUAL + DIVIDE_EQUAL + AND_EQUAL + OR_EQUAL + XOR_EQUAL + REMAINDER_EQUAL + LEFT_SHIFT_EQUAL + RIGHT_SHIFT_EQUAL + UNSIGNED_RIGHT_SHIFT_EQUAL + OR_OR + AND_AND + PLUS + MINUS + NOT + REMAINDER + XOR + AND + MULTIPLY + OR + TWIDDLE + DIVIDE + GREATER + LESS + LPAREN + RPAREN + LBRACE + RBRACE + LBRACKET + RBRACKET + SEMICOLON + QUESTION + COLON + COMMA + DOT + EQUAL + + -- BodyMarker + + $Alias + + '++' ::= PLUS_PLUS + '--' ::= MINUS_MINUS + '==' ::= EQUAL_EQUAL + '<=' ::= LESS_EQUAL + '>=' ::= GREATER_EQUAL + '!=' ::= NOT_EQUAL + '<<' ::= LEFT_SHIFT + '>>' ::= RIGHT_SHIFT + '>>>' ::= UNSIGNED_RIGHT_SHIFT + '+=' ::= PLUS_EQUAL + '-=' ::= MINUS_EQUAL + '*=' ::= MULTIPLY_EQUAL + '/=' ::= DIVIDE_EQUAL + '&=' ::= AND_EQUAL + '|=' ::= OR_EQUAL + '^=' ::= XOR_EQUAL + '%=' ::= REMAINDER_EQUAL + '<<=' ::= LEFT_SHIFT_EQUAL + '>>=' ::= RIGHT_SHIFT_EQUAL + '>>>=' ::= UNSIGNED_RIGHT_SHIFT_EQUAL + '||' ::= OR_OR + '&&' ::= AND_AND + + '+' ::= PLUS + '-' ::= MINUS + '!' ::= NOT + '%' ::= REMAINDER + '^' ::= XOR + '&' ::= AND + '*' ::= MULTIPLY + '|' ::= OR + '~' ::= TWIDDLE + '/' ::= DIVIDE + '>' ::= GREATER + '<' ::= LESS + '(' ::= LPAREN + ')' ::= RPAREN + '{' ::= LBRACE + '}' ::= RBRACE + '[' ::= LBRACKET + ']' ::= RBRACKET + ';' ::= SEMICOLON + '?' ::= QUESTION + ':' ::= COLON + ',' ::= COMMA + '.' ::= DOT + '=' ::= EQUAL + + $Start + Goal + + $Rules + + /. // This method is part of an automatic generation : do NOT edit-modify + protected void consumeRule(int act) { + switch ( act ) { + ./ + + + + Goal ::= '++' CompilationUnit + Goal ::= '--' MethodBody + Goal ::= '==' ConstructorBody + -- Initializer + Goal ::= '>>' StaticInitializer + Goal ::= '>>' Initializer + -- error recovery + Goal ::= '>>>' Headers + Goal ::= '*' BlockStatements + Goal ::= '*' MethodPushModifiersHeader + Goal ::= '*' CatchHeader + -- JDOM + Goal ::= '&&' FieldDeclaration + Goal ::= '||' ImportDeclaration + Goal ::= '?' PackageDeclaration + Goal ::= '+' TypeDeclaration + Goal ::= '/' GenericMethodDeclaration + Goal ::= '&' ClassBodyDeclaration + -- code snippet + Goal ::= '%' Expression + -- completion parser + Goal ::= '!' ConstructorBlockStatementsopt + Goal ::= '~' BlockStatementsopt + + Literal -> IntegerLiteral + Literal -> LongLiteral + Literal -> FloatingPointLiteral + Literal -> DoubleLiteral + Literal -> CharacterLiteral + Literal -> StringLiteral + Literal -> null + Literal -> BooleanLiteral + BooleanLiteral -> true + BooleanLiteral -> false + + ------------------------------------------------------------- + ------------------------------------------------------------- + --a Type results in both a push of its dimension(s) and its name(s). + + Type ::= PrimitiveType + /.$putCase consumePrimitiveType(); $break ./ + Type -> ReferenceType + + PrimitiveType -> NumericType + NumericType -> IntegralType + NumericType -> FloatingPointType + + PrimitiveType -> 'boolean' + PrimitiveType -> 'void' + IntegralType -> 'byte' + IntegralType -> 'short' + IntegralType -> 'int' + IntegralType -> 'long' + IntegralType -> 'char' + FloatingPointType -> 'float' + FloatingPointType -> 'double' + + ReferenceType ::= ClassOrInterfaceType + /.$putCase consumeReferenceType(); $break ./ + ReferenceType -> ArrayType -- here a push of dimensions is done, that explains the two previous push 0 + + ClassOrInterfaceType -> Name + + -- + -- These rules have been rewritten to avoid some conflicts introduced + -- by adding the 1.1 features + -- + -- ArrayType ::= PrimitiveType '[' ']' + -- ArrayType ::= Name '[' ']' + -- ArrayType ::= ArrayType '[' ']' + -- + + ArrayType ::= PrimitiveType Dims + ArrayType ::= Name Dims + + ClassType -> ClassOrInterfaceType + + + -------------------------------------------------------------- + -------------------------------------------------------------- + + Name -> SimpleName + Name -> QualifiedName + + SimpleName -> 'Identifier' + + QualifiedName ::= Name '.' SimpleName + /.$putCase consumeQualifiedName(); $break ./ + + CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt TypeDeclarationsopt + /.$putCase consumeCompilationUnit(); $break ./ + + EnterCompilationUnit ::= $empty + /.$putCase consumeEnterCompilationUnit(); $break ./ + + Headers -> Header + Headers ::= Headers Header + + Header -> ImportDeclaration + Header -> PackageDeclaration + Header -> ClassHeader + Header -> InterfaceHeader + Header -> StaticInitializer + Header -> MethodHeader + Header -> ConstructorHeader + Header -> FieldDeclaration + Header -> AllocationHeader + + CatchHeader ::= 'catch' '(' FormalParameter ')' '{' + /.$putCase consumeCatchHeader(); $break ./ + + ImportDeclarations -> ImportDeclaration + ImportDeclarations ::= ImportDeclarations ImportDeclaration + /.$putCase consumeImportDeclarations(); $break ./ + + TypeDeclarations -> TypeDeclaration + TypeDeclarations ::= TypeDeclarations TypeDeclaration + /.$putCase consumeTypeDeclarations(); $break ./ + + PackageDeclaration ::= PackageDeclarationName ';' + /.$putCase consumePackageDeclaration(); $break ./ + + PackageDeclarationName ::= 'package' Name + /.$putCase consumePackageDeclarationName(); $break ./ + + ImportDeclaration -> SingleTypeImportDeclaration + ImportDeclaration -> TypeImportOnDemandDeclaration + + SingleTypeImportDeclaration ::= SingleTypeImportDeclarationName ';' + /.$putCase consumeSingleTypeImportDeclaration(); $break ./ + + SingleTypeImportDeclarationName ::= 'import' Name + /.$putCase consumeSingleTypeImportDeclarationName(); $break ./ + + TypeImportOnDemandDeclaration ::= TypeImportOnDemandDeclarationName ';' + /.$putCase consumeTypeImportOnDemandDeclaration(); $break ./ + + TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' + /.$putCase consumeTypeImportOnDemandDeclarationName(); $break ./ + + TypeDeclaration -> ClassDeclaration + TypeDeclaration -> InterfaceDeclaration + -- this declaration in part of a list od declaration and we will + -- use and optimized list length calculation process + -- thus we decrement the number while it will be incremend..... + TypeDeclaration ::= ';' + /. $putCase consumeEmptyTypeDeclaration(); $break ./ + + --18.7 Only in the LALR(1) Grammar + + Modifiers ::= Modifier + Modifiers ::= Modifiers Modifier + + Modifier -> 'public' + Modifier -> 'protected' + Modifier -> 'private' + Modifier -> 'static' + Modifier -> 'abstract' + Modifier -> 'final' + Modifier -> 'native' + Modifier -> 'synchronized' + Modifier -> 'transient' + Modifier -> 'volatile' + Modifier -> 'strictfp' + + --18.8 Productions from 8: Class Declarations + --ClassModifier ::= + -- 'abstract' + -- | 'final' + -- | 'public' + --18.8.1 Productions from 8.1: Class Declarations + + ClassDeclaration ::= ClassHeader ClassBody + /.$putCase consumeClassDeclaration(); $break ./ + + ClassHeader ::= ClassHeaderName ClassHeaderExtendsopt ClassHeaderImplementsopt + /.$putCase consumeClassHeader(); $break ./ + + ClassHeaderName ::= Modifiersopt 'class' 'Identifier' + /.$putCase consumeClassHeaderName(); $break ./ + + ClassHeaderExtends ::= 'extends' ClassType + /.$putCase consumeClassHeaderExtends(); $break ./ + + ClassHeaderImplements ::= 'implements' InterfaceTypeList + /.$putCase consumeClassHeaderImplements(); $break ./ + + InterfaceTypeList -> InterfaceType + InterfaceTypeList ::= InterfaceTypeList ',' InterfaceType + /.$putCase consumeInterfaceTypeList(); $break ./ + + InterfaceType ::= ClassOrInterfaceType + /.$putCase consumeInterfaceType(); $break ./ + + ClassBody ::= '{' ClassBodyDeclarationsopt '}' + + ClassBodyDeclarations ::= ClassBodyDeclaration + ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration + /.$putCase consumeClassBodyDeclarations(); $break ./ + + ClassBodyDeclaration -> ClassMemberDeclaration + ClassBodyDeclaration -> StaticInitializer + ClassBodyDeclaration -> ConstructorDeclaration + --1.1 feature + ClassBodyDeclaration ::= Diet NestedMethod Block + /.$putCase consumeClassBodyDeclaration(); $break ./ + Diet ::= $empty + /.$putCase consumeDiet(); $break./ + + Initializer ::= Diet NestedMethod Block + /.$putCase consumeClassBodyDeclaration(); $break ./ + + ClassMemberDeclaration -> FieldDeclaration + ClassMemberDeclaration -> MethodDeclaration + --1.1 feature + ClassMemberDeclaration -> ClassDeclaration + --1.1 feature + ClassMemberDeclaration -> InterfaceDeclaration + + -- Empty declarations are not valid Java ClassMemberDeclarations. + -- However, since the current (2/14/97) Java compiler accepts them + -- (in fact, some of the official tests contain this erroneous + -- syntax) + + GenericMethodDeclaration -> MethodDeclaration + GenericMethodDeclaration -> ConstructorDeclaration + + ClassMemberDeclaration ::= ';' + /.$putCase consumeEmptyClassMemberDeclaration(); $break./ + + --18.8.2 Productions from 8.3: Field Declarations + --VariableModifier ::= + -- 'public' + -- | 'protected' + -- | 'private' + -- | 'static' + -- | 'final' + -- | 'transient' + -- | 'volatile' + + FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';' + /.$putCase consumeFieldDeclaration(); $break ./ + + VariableDeclarators -> VariableDeclarator + VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator + /.$putCase consumeVariableDeclarators(); $break ./ + + VariableDeclarator ::= VariableDeclaratorId EnterVariable ExitVariableWithoutInitialization + + VariableDeclarator ::= VariableDeclaratorId EnterVariable '=' ForceNoDiet VariableInitializer RestoreDiet ExitVariableWithInitialization + + EnterVariable ::= $empty + /.$putCase consumeEnterVariable(); $break ./ + + ExitVariableWithInitialization ::= $empty + /.$putCase consumeExitVariableWithInitialization(); $break ./ + + ExitVariableWithoutInitialization ::= $empty + /.$putCase consumeExitVariableWithoutInitialization(); $break ./ + + ForceNoDiet ::= $empty + /.$putCase consumeForceNoDiet(); $break ./ + RestoreDiet ::= $empty + /.$putCase consumeRestoreDiet(); $break ./ + + VariableDeclaratorId ::= 'Identifier' Dimsopt + + VariableInitializer -> Expression + VariableInitializer -> ArrayInitializer + + --18.8.3 Productions from 8.4: Method Declarations + --MethodModifier ::= + -- 'public' + -- | 'protected' + -- | 'private' + -- | 'static' + -- | 'abstract' + -- | 'final' + -- | 'native' + -- | 'synchronized' + -- + + MethodDeclaration -> AbstractMethodDeclaration + MethodDeclaration ::= MethodHeader MethodBody + /.$putCase // set to true to consume a method with a body + consumeMethodDeclaration(true); $break ./ + + AbstractMethodDeclaration ::= MethodHeader ';' + /.$putCase // set to false to consume a method without body + consumeMethodDeclaration(false); $break ./ + + MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims MethodHeaderThrowsClauseopt + /.$putCase consumeMethodHeader(); $break ./ + + MethodPushModifiersHeader ::= MethodPushModifiersHeaderName MethodHeaderParameters MethodHeaderExtendedDims MethodHeaderThrowsClauseopt + /.$putCase consumeMethodHeader(); $break ./ + + MethodPushModifiersHeaderName ::= Modifiers Type PushModifiers 'Identifier' '(' + /.$putCase consumeMethodPushModifiersHeaderName(); $break ./ + + MethodPushModifiersHeaderName ::= Type PushModifiers 'Identifier' '(' + /.$putCase consumeMethodPushModifiersHeaderName(); $break ./ + + MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + /.$putCase consumeMethodHeaderName(); $break ./ + + MethodHeaderParameters ::= FormalParameterListopt ')' + /.$putCase consumeMethodHeaderParameters(); $break ./ + + MethodHeaderExtendedDims ::= Dimsopt + /.$putCase consumeMethodHeaderExtendedDims(); $break ./ + + MethodHeaderThrowsClause ::= 'throws' ClassTypeList + /.$putCase consumeMethodHeaderThrowsClause(); $break ./ + + ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters MethodHeaderThrowsClauseopt + /.$putCase consumeConstructorHeader(); $break ./ + + ConstructorHeaderName ::= Modifiersopt 'Identifier' '(' + /.$putCase consumeConstructorHeaderName(); $break ./ + + FormalParameterList -> FormalParameter + FormalParameterList ::= FormalParameterList ',' FormalParameter + /.$putCase consumeFormalParameterList(); $break ./ + + --1.1 feature + FormalParameter ::= Modifiersopt Type VariableDeclaratorId + /.$putCase // the boolean is used to know if the modifiers should be reset + consumeFormalParameter(); $break ./ + + ClassTypeList -> ClassTypeElt + ClassTypeList ::= ClassTypeList ',' ClassTypeElt + /.$putCase consumeClassTypeList(); $break ./ + + ClassTypeElt ::= ClassType + /.$putCase consumeClassTypeElt(); $break ./ + + + MethodBody ::= NestedMethod '{' BlockStatementsopt '}' + /.$putCase consumeMethodBody(); $break ./ + + NestedMethod ::= $empty + /.$putCase consumeNestedMethod(); $break ./ + + --18.8.4 Productions from 8.5: Static Initializers + + StaticInitializer ::= StaticOnly Block + /.$putCase consumeStaticInitializer(); $break./ + + StaticOnly ::= 'static' + /.$putCase consumeStaticOnly(); $break ./ + + --18.8.5 Productions from 8.6: Constructor Declarations + --ConstructorModifier ::= + -- 'public' + -- | 'protected' + -- | 'private' + -- + -- + ConstructorDeclaration ::= ConstructorHeader ConstructorBody + /.$putCase consumeConstructorDeclaration() ; $break ./ + + -- These rules are added to be able to parse constructors with no body + ConstructorDeclaration ::= ConstructorHeader ';' + /.$putCase consumeInvalidConstructorDeclaration() ; $break ./ + + -- the rules ExplicitConstructorInvocationopt has been expanded + -- in the rule below in order to make the grammar lalr(1). + -- ConstructorBody ::= '{' ExplicitConstructorInvocationopt BlockStatementsopt '}' + -- Other inlining has occured into the next rule too.... + + ConstructorBody ::= NestedMethod '{' ConstructorBlockStatementsopt '}' + /.$putCase consumeConstructorBody(); $break ./ + + ConstructorBlockStatementsopt -> BlockStatementsopt + + ConstructorBlockStatementsopt -> ExplicitConstructorInvocation + + ConstructorBlockStatementsopt ::= ExplicitConstructorInvocation BlockStatements + /.$putCase consumeConstructorBlockStatements(); $break ./ + + ExplicitConstructorInvocation ::= 'this' '(' ArgumentListopt ')' ';' + /.$putCase consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.This); $break ./ + + ExplicitConstructorInvocation ::= 'super' '(' ArgumentListopt ')' ';' + /.$putCase consumeExplicitConstructorInvocation(0,ExplicitConstructorCall.Super); $break ./ + + --1.1 feature + ExplicitConstructorInvocation ::= Primary '.' 'super' '(' ArgumentListopt ')' ';' + /.$putCase consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.Super); $break ./ + + --1.1 feature + ExplicitConstructorInvocation ::= Name '.' 'super' '(' ArgumentListopt ')' ';' + /.$putCase consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.Super); $break ./ + + --1.1 feature + ExplicitConstructorInvocation ::= Primary '.' 'this' '(' ArgumentListopt ')' ';' + /.$putCase consumeExplicitConstructorInvocation(1, ExplicitConstructorCall.This); $break ./ + + --1.1 feature + ExplicitConstructorInvocation ::= Name '.' 'this' '(' ArgumentListopt ')' ';' + /.$putCase consumeExplicitConstructorInvocation(2, ExplicitConstructorCall.This); $break ./ + + --18.9 Productions from 9: Interface Declarations + + --18.9.1 Productions from 9.1: Interface Declarations + --InterfaceModifier ::= + -- 'public' + -- | 'abstract' + -- + InterfaceDeclaration ::= InterfaceHeader InterfaceBody + /.$putCase consumeInterfaceDeclaration(); $break ./ + + InterfaceHeader ::= InterfaceHeaderName InterfaceHeaderExtendsopt + /.$putCase consumeInterfaceHeader(); $break ./ + + InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier' + /.$putCase consumeInterfaceHeaderName(); $break ./ + + -- This rule will be used to accept inner local interface and then report a relevant error message + InvalidInterfaceDeclaration -> InterfaceHeader InterfaceBody + + InterfaceHeaderExtends ::= 'extends' InterfaceTypeList + /.$putCase consumeInterfaceHeaderExtends(); $break ./ + + InterfaceBody ::= '{' InterfaceMemberDeclarationsopt '}' + + InterfaceMemberDeclarations -> InterfaceMemberDeclaration + InterfaceMemberDeclarations ::= InterfaceMemberDeclarations InterfaceMemberDeclaration + /.$putCase consumeInterfaceMemberDeclarations(); $break ./ + + --same as for class members + InterfaceMemberDeclaration ::= ';' + /.$putCase consumeEmptyInterfaceMemberDeclaration(); $break ./ + + -- This rule is added to be able to parse non abstract method inside interface and then report a relevent error message + InvalidMethodDeclaration -> MethodHeader MethodBody + + InterfaceMemberDeclaration -> ConstantDeclaration + InterfaceMemberDeclaration ::= InvalidMethodDeclaration + /.$putCase ignoreMethodBody(); $break ./ + + -- These rules are added to be able to parse constructors inside interface and then report a relevent error message + InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody + /.$putCase ignoreInvalidConstructorDeclaration(true); $break ./ + + InvalidConstructorDeclaration ::= ConstructorHeader ';' + /.$putCase ignoreInvalidConstructorDeclaration(false); $break ./ + + InterfaceMemberDeclaration -> AbstractMethodDeclaration + InterfaceMemberDeclaration -> InvalidConstructorDeclaration + + --1.1 feature + InterfaceMemberDeclaration -> ClassDeclaration + --1.1 feature + InterfaceMemberDeclaration -> InterfaceDeclaration + + ConstantDeclaration -> FieldDeclaration + + ArrayInitializer ::= '{' ,opt '}' + /.$putCase consumeEmptyArrayInitializer(); $break ./ + ArrayInitializer ::= '{' VariableInitializers '}' + /.$putCase consumeArrayInitializer(); $break ./ + ArrayInitializer ::= '{' VariableInitializers , '}' + /.$putCase consumeArrayInitializer(); $break ./ + + VariableInitializers ::= VariableInitializer + VariableInitializers ::= VariableInitializers ',' VariableInitializer + /.$putCase consumeVariableInitializers(); $break ./ + + Block ::= OpenBlock '{' BlockStatementsopt '}' + /.$putCase consumeBlock(); $break ./ + OpenBlock ::= $empty + /.$putCase consumeOpenBlock() ; $break ./ + + BlockStatements -> BlockStatement + BlockStatements ::= BlockStatements BlockStatement + /.$putCase consumeBlockStatements() ; $break ./ + + BlockStatement -> LocalVariableDeclarationStatement + BlockStatement -> Statement + --1.1 feature + BlockStatement -> ClassDeclaration + BlockStatement ::= InvalidInterfaceDeclaration + /.$putCase ignoreInterfaceDeclaration(); $break ./ + + LocalVariableDeclarationStatement ::= LocalVariableDeclaration ';' + /.$putCase consumeLocalVariableDeclarationStatement(); $break ./ + + LocalVariableDeclaration ::= Type PushModifiers VariableDeclarators + /.$putCase consumeLocalVariableDeclaration(); $break ./ + + -- 1.1 feature + -- The modifiers part of this rule makes the grammar more permissive. + -- The only modifier here is final. We put Modifiers to allow multiple modifiers + -- This will require to check the validity of the modifier + + LocalVariableDeclaration ::= Modifiers Type PushModifiers VariableDeclarators + /.$putCase consumeLocalVariableDeclaration(); $break ./ + + PushModifiers ::= $empty + /.$putCase consumePushModifiers(); $break ./ + + Statement -> StatementWithoutTrailingSubstatement + Statement -> LabeledStatement + Statement -> IfThenStatement + Statement -> IfThenElseStatement + Statement -> WhileStatement + Statement -> ForStatement + + StatementNoShortIf -> StatementWithoutTrailingSubstatement + StatementNoShortIf -> LabeledStatementNoShortIf + StatementNoShortIf -> IfThenElseStatementNoShortIf + StatementNoShortIf -> WhileStatementNoShortIf + StatementNoShortIf -> ForStatementNoShortIf + + StatementWithoutTrailingSubstatement -> AssertStatement + StatementWithoutTrailingSubstatement -> Block + StatementWithoutTrailingSubstatement -> EmptyStatement + StatementWithoutTrailingSubstatement -> ExpressionStatement + StatementWithoutTrailingSubstatement -> SwitchStatement + StatementWithoutTrailingSubstatement -> DoStatement + StatementWithoutTrailingSubstatement -> BreakStatement + StatementWithoutTrailingSubstatement -> ContinueStatement + StatementWithoutTrailingSubstatement -> ReturnStatement + StatementWithoutTrailingSubstatement -> SynchronizedStatement + StatementWithoutTrailingSubstatement -> ThrowStatement + StatementWithoutTrailingSubstatement -> TryStatement + + EmptyStatement ::= ';' + /.$putCase consumeEmptyStatement(); $break ./ + + LabeledStatement ::= 'Identifier' ':' Statement + /.$putCase consumeStatementLabel() ; $break ./ + + LabeledStatementNoShortIf ::= 'Identifier' ':' StatementNoShortIf + /.$putCase consumeStatementLabel() ; $break ./ + + ExpressionStatement ::= StatementExpression ';' + /. $putCase consumeExpressionStatement(); $break ./ + + StatementExpression ::= Assignment + StatementExpression ::= PreIncrementExpression + StatementExpression ::= PreDecrementExpression + StatementExpression ::= PostIncrementExpression + StatementExpression ::= PostDecrementExpression + StatementExpression ::= MethodInvocation + StatementExpression ::= ClassInstanceCreationExpression + + IfThenStatement ::= 'if' '(' Expression ')' Statement + /.$putCase consumeStatementIfNoElse(); $break ./ + + IfThenElseStatement ::= 'if' '(' Expression ')' StatementNoShortIf 'else' Statement + /.$putCase consumeStatementIfWithElse(); $break ./ + + IfThenElseStatementNoShortIf ::= 'if' '(' Expression ')' StatementNoShortIf 'else' StatementNoShortIf + /.$putCase consumeStatementIfWithElse(); $break ./ + + SwitchStatement ::= 'switch' OpenBlock '(' Expression ')' SwitchBlock + /.$putCase consumeStatementSwitch() ; $break ./ + + SwitchBlock ::= '{' '}' + /.$putCase consumeEmptySwitchBlock() ; $break ./ + + SwitchBlock ::= '{' SwitchBlockStatements '}' + SwitchBlock ::= '{' SwitchLabels '}' + SwitchBlock ::= '{' SwitchBlockStatements SwitchLabels '}' + /.$putCase consumeSwitchBlock() ; $break ./ + + SwitchBlockStatements -> SwitchBlockStatement + SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement + /.$putCase consumeSwitchBlockStatements() ; $break ./ + + SwitchBlockStatement ::= SwitchLabels BlockStatements + /.$putCase consumeSwitchBlockStatement() ; $break ./ + + SwitchLabels -> SwitchLabel + SwitchLabels ::= SwitchLabels SwitchLabel + /.$putCase consumeSwitchLabels() ; $break ./ + + SwitchLabel ::= 'case' ConstantExpression ':' + /. $putCase consumeCaseLabel(); $break ./ + + SwitchLabel ::= 'default' ':' + /. $putCase consumeDefaultLabel(); $break ./ + + WhileStatement ::= 'while' '(' Expression ')' Statement + /.$putCase consumeStatementWhile() ; $break ./ + + WhileStatementNoShortIf ::= 'while' '(' Expression ')' StatementNoShortIf + /.$putCase consumeStatementWhile() ; $break ./ + + DoStatement ::= 'do' Statement 'while' '(' Expression ')' ';' + /.$putCase consumeStatementDo() ; $break ./ + + ForStatement ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' Statement + /.$putCase consumeStatementFor() ; $break ./ + ForStatementNoShortIf ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' StatementNoShortIf + /.$putCase consumeStatementFor() ; $break ./ + + --the minus one allows to avoid a stack-to-stack transfer + ForInit ::= StatementExpressionList + /.$putCase consumeForInit() ; $break ./ + ForInit -> LocalVariableDeclaration + + ForUpdate -> StatementExpressionList + + StatementExpressionList -> StatementExpression + StatementExpressionList ::= StatementExpressionList ',' StatementExpression + /.$putCase consumeStatementExpressionList() ; $break ./ + + -- 1.4 feature + AssertStatement ::= 'assert' Expression ';' + /.$putCase consumeSimpleAssertStatement() ; $break ./ + + AssertStatement ::= 'assert' Expression ':' Expression ';' + /.$putCase consumeAssertStatement() ; $break ./ + + BreakStatement ::= 'break' ';' + /.$putCase consumeStatementBreak() ; $break ./ + + BreakStatement ::= 'break' Identifier ';' + /.$putCase consumeStatementBreakWithLabel() ; $break ./ + + ContinueStatement ::= 'continue' ';' + /.$putCase consumeStatementContinue() ; $break ./ + + ContinueStatement ::= 'continue' Identifier ';' + /.$putCase consumeStatementContinueWithLabel() ; $break ./ + + ReturnStatement ::= 'return' Expressionopt ';' + /.$putCase consumeStatementReturn() ; $break ./ + + ThrowStatement ::= 'throw' Expression ';' + /.$putCase consumeStatementThrow(); + $break ./ + + SynchronizedStatement ::= OnlySynchronized '(' Expression ')' Block + /.$putCase consumeStatementSynchronized(); $break ./ + OnlySynchronized ::= 'synchronized' + /.$putCase consumeOnlySynchronized(); $break ./ + + + TryStatement ::= 'try' Block Catches + /.$putCase consumeStatementTry(false); $break ./ + TryStatement ::= 'try' Block Catchesopt Finally + /.$putCase consumeStatementTry(true); $break ./ + + Catches -> CatchClause + Catches ::= Catches CatchClause + /.$putCase consumeCatches(); $break ./ + + CatchClause ::= 'catch' '(' FormalParameter ')' Block + /.$putCase consumeStatementCatch() ; $break ./ + + Finally ::= 'finally' Block + + --18.12 Productions from 14: Expressions + + --for source positionning purpose + PushLPAREN ::= '(' + /.$putCase consumeLeftParen(); $break ./ + PushRPAREN ::= ')' + /.$putCase consumeRightParen(); $break ./ + + Primary -> PrimaryNoNewArray + Primary -> ArrayCreationExpression + + PrimaryNoNewArray -> Literal + PrimaryNoNewArray ::= 'this' + /.$putCase consumePrimaryNoNewArrayThis(); $break ./ + + PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN + /.$putCase consumePrimaryNoNewArray(); $break ./ + + PrimaryNoNewArray -> ClassInstanceCreationExpression + PrimaryNoNewArray -> FieldAccess + --1.1 feature + PrimaryNoNewArray ::= Name '.' 'this' + /.$putCase consumePrimaryNoNewArrayNameThis(); $break ./ + PrimaryNoNewArray ::= Name '.' 'super' + /.$putCase consumePrimaryNoNewArrayNameSuper(); $break ./ + + --1.1 feature + --PrimaryNoNewArray ::= Type '.' 'class' + --inline Type in the previous rule in order to make the grammar LL1 instead + -- of LL2. The result is the 3 next rules. + PrimaryNoNewArray ::= Name '.' 'class' + /.$putCase consumePrimaryNoNewArrayName(); $break ./ + + PrimaryNoNewArray ::= ArrayType '.' 'class' + /.$putCase consumePrimaryNoNewArrayArrayType(); $break ./ + + PrimaryNoNewArray ::= PrimitiveType '.' 'class' + /.$putCase consumePrimaryNoNewArrayPrimitiveType(); $break ./ + + PrimaryNoNewArray -> MethodInvocation + PrimaryNoNewArray -> ArrayAccess + + --1.1 feature + -- + -- In Java 1.0 a ClassBody could not appear at all in a + -- ClassInstanceCreationExpression. + -- + + AllocationHeader ::= 'new' ClassType '(' ArgumentListopt ')' + /.$putCase consumeAllocationHeader(); $break ./ + + ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt + /.$putCase consumeClassInstanceCreationExpression(); $break ./ + --1.1 feature + + ClassInstanceCreationExpression ::= Primary '.' 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt + /.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./ + + --1.1 feature + ClassInstanceCreationExpression ::= ClassInstanceCreationExpressionName 'new' SimpleName '(' ArgumentListopt ')' ClassBodyopt + /.$putCase consumeClassInstanceCreationExpressionQualified() ; $break ./ + + ClassInstanceCreationExpressionName ::= Name '.' + /.$putCase consumeClassInstanceCreationExpressionName() ; $break ./ + + ClassBodyopt ::= $empty --test made using null as contents + /.$putCase consumeClassBodyopt(); $break ./ + ClassBodyopt ::= EnterAnonymousClassBody ClassBody + + EnterAnonymousClassBody ::= $empty + /.$putCase consumeEnterAnonymousClassBody(); $break ./ + + ArgumentList ::= Expression + ArgumentList ::= ArgumentList ',' Expression + /.$putCase consumeArgumentList(); $break ./ + + --Thess rules are re-written in order to be ll1 + --ArrayCreationExpression ::= 'new' ArrayType ArrayInitializer + --ArrayCreationExpression ::= 'new' PrimitiveType DimExprs Dimsopt + --ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimExprs Dimsopt + --DimExprs ::= DimExpr + --DimExprs ::= DimExprs DimExpr + + ArrayCreationExpression ::= 'new' PrimitiveType DimWithOrWithOutExprs ArrayInitializeropt + /.$putCase consumeArrayCreationExpression(); $break ./ + ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimWithOrWithOutExprs ArrayInitializeropt + /.$putCase consumeArrayCreationExpression(); $break ./ + + DimWithOrWithOutExprs ::= DimWithOrWithOutExpr + DimWithOrWithOutExprs ::= DimWithOrWithOutExprs DimWithOrWithOutExpr + /.$putCase consumeDimWithOrWithOutExprs(); $break ./ + + DimWithOrWithOutExpr ::= '[' Expression ']' + DimWithOrWithOutExpr ::= '[' ']' + /. $putCase consumeDimWithOrWithOutExpr(); $break ./ + -- ----------------------------------------------- + + Dims ::= DimsLoop + /. $putCase consumeDims(); $break ./ + DimsLoop -> OneDimLoop + DimsLoop ::= DimsLoop OneDimLoop + OneDimLoop ::= '[' ']' + /. $putCase consumeOneDimLoop(); $break ./ + + FieldAccess ::= Primary '.' 'Identifier' + /.$putCase consumeFieldAccess(false); $break ./ + + FieldAccess ::= 'super' '.' 'Identifier' + /.$putCase consumeFieldAccess(true); $break ./ + + MethodInvocation ::= Name '(' ArgumentListopt ')' + /.$putCase consumeMethodInvocationName(); $break ./ + + MethodInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' + /.$putCase consumeMethodInvocationPrimary(); $break ./ + + MethodInvocation ::= 'super' '.' 'Identifier' '(' ArgumentListopt ')' + /.$putCase consumeMethodInvocationSuper(); $break ./ + + ArrayAccess ::= Name '[' Expression ']' + /.$putCase consumeArrayAccess(true); $break ./ + ArrayAccess ::= PrimaryNoNewArray '[' Expression ']' + /.$putCase consumeArrayAccess(false); $break ./ + + PostfixExpression -> Primary + PostfixExpression ::= Name + /.$putCase consumePostfixExpression(); $break ./ + PostfixExpression -> PostIncrementExpression + PostfixExpression -> PostDecrementExpression + + PostIncrementExpression ::= PostfixExpression '++' + /.$putCase consumeUnaryExpression(OperatorExpression.PLUS,true); $break ./ + + PostDecrementExpression ::= PostfixExpression '--' + /.$putCase consumeUnaryExpression(OperatorExpression.MINUS,true); $break ./ + + --for source managment purpose + PushPosition ::= $empty + /.$putCase consumePushPosition(); $break ./ + + UnaryExpression -> PreIncrementExpression + UnaryExpression -> PreDecrementExpression + UnaryExpression ::= '+' PushPosition UnaryExpression + /.$putCase consumeUnaryExpression(OperatorExpression.PLUS); $break ./ + UnaryExpression ::= '-' PushPosition UnaryExpression + /.$putCase consumeUnaryExpression(OperatorExpression.MINUS); $break ./ + UnaryExpression -> UnaryExpressionNotPlusMinus + + PreIncrementExpression ::= '++' PushPosition UnaryExpression + /.$putCase consumeUnaryExpression(OperatorExpression.PLUS,false); $break ./ + + PreDecrementExpression ::= '--' PushPosition UnaryExpression + /.$putCase consumeUnaryExpression(OperatorExpression.MINUS,false); $break ./ + + UnaryExpressionNotPlusMinus -> PostfixExpression + UnaryExpressionNotPlusMinus ::= '~' PushPosition UnaryExpression + /.$putCase consumeUnaryExpression(OperatorExpression.TWIDDLE); $break ./ + UnaryExpressionNotPlusMinus ::= '!' PushPosition UnaryExpression + /.$putCase consumeUnaryExpression(OperatorExpression.NOT); $break ./ + UnaryExpressionNotPlusMinus -> CastExpression + + CastExpression ::= PushLPAREN PrimitiveType Dimsopt PushRPAREN UnaryExpression + /.$putCase consumeCastExpression(); $break ./ + CastExpression ::= PushLPAREN Name Dims PushRPAREN UnaryExpressionNotPlusMinus + /.$putCase consumeCastExpression(); $break ./ + -- Expression is here only in order to make the grammar LL1 + CastExpression ::= PushLPAREN Expression PushRPAREN UnaryExpressionNotPlusMinus + /.$putCase consumeCastExpressionLL1(); $break ./ + + MultiplicativeExpression -> UnaryExpression + MultiplicativeExpression ::= MultiplicativeExpression '*' UnaryExpression + /.$putCase consumeBinaryExpression(OperatorExpression.MULTIPLY); $break ./ + MultiplicativeExpression ::= MultiplicativeExpression '/' UnaryExpression + /.$putCase consumeBinaryExpression(OperatorExpression.DIVIDE); $break ./ + MultiplicativeExpression ::= MultiplicativeExpression '%' UnaryExpression + /.$putCase consumeBinaryExpression(OperatorExpression.REMAINDER); $break ./ + + AdditiveExpression -> MultiplicativeExpression + AdditiveExpression ::= AdditiveExpression '+' MultiplicativeExpression + /.$putCase consumeBinaryExpression(OperatorExpression.PLUS); $break ./ + AdditiveExpression ::= AdditiveExpression '-' MultiplicativeExpression + /.$putCase consumeBinaryExpression(OperatorExpression.MINUS); $break ./ + + ShiftExpression -> AdditiveExpression + ShiftExpression ::= ShiftExpression '<<' AdditiveExpression + /.$putCase consumeBinaryExpression(OperatorExpression.LEFT_SHIFT); $break ./ + ShiftExpression ::= ShiftExpression '>>' AdditiveExpression + /.$putCase consumeBinaryExpression(OperatorExpression.RIGHT_SHIFT); $break ./ + ShiftExpression ::= ShiftExpression '>>>' AdditiveExpression + /.$putCase consumeBinaryExpression(OperatorExpression.UNSIGNED_RIGHT_SHIFT); $break ./ + + RelationalExpression -> ShiftExpression + RelationalExpression ::= RelationalExpression '<' ShiftExpression + /.$putCase consumeBinaryExpression(OperatorExpression.LESS); $break ./ + RelationalExpression ::= RelationalExpression '>' ShiftExpression + /.$putCase consumeBinaryExpression(OperatorExpression.GREATER); $break ./ + RelationalExpression ::= RelationalExpression '<=' ShiftExpression + /.$putCase consumeBinaryExpression(OperatorExpression.LESS_EQUAL); $break ./ + RelationalExpression ::= RelationalExpression '>=' ShiftExpression + /.$putCase consumeBinaryExpression(OperatorExpression.GREATER_EQUAL); $break ./ + RelationalExpression ::= RelationalExpression 'instanceof' ReferenceType + /.$putCase consumeInstanceOfExpression(OperatorExpression.INSTANCEOF); $break ./ + + EqualityExpression -> RelationalExpression + EqualityExpression ::= EqualityExpression '==' RelationalExpression + /.$putCase consumeEqualityExpression(OperatorExpression.EQUAL_EQUAL); $break ./ + EqualityExpression ::= EqualityExpression '!=' RelationalExpression + /.$putCase consumeEqualityExpression(OperatorExpression.NOT_EQUAL); $break ./ + + AndExpression -> EqualityExpression + AndExpression ::= AndExpression '&' EqualityExpression + /.$putCase consumeBinaryExpression(OperatorExpression.AND); $break ./ + + ExclusiveOrExpression -> AndExpression + ExclusiveOrExpression ::= ExclusiveOrExpression '^' AndExpression + /.$putCase consumeBinaryExpression(OperatorExpression.XOR); $break ./ + + InclusiveOrExpression -> ExclusiveOrExpression + InclusiveOrExpression ::= InclusiveOrExpression '|' ExclusiveOrExpression + /.$putCase consumeBinaryExpression(OperatorExpression.OR); $break ./ + + ConditionalAndExpression -> InclusiveOrExpression + ConditionalAndExpression ::= ConditionalAndExpression '&&' InclusiveOrExpression + /.$putCase consumeBinaryExpression(OperatorExpression.AND_AND); $break ./ + + ConditionalOrExpression -> ConditionalAndExpression + ConditionalOrExpression ::= ConditionalOrExpression '||' ConditionalAndExpression + /.$putCase consumeBinaryExpression(OperatorExpression.OR_OR); $break ./ + + ConditionalExpression -> ConditionalOrExpression + ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression + /.$putCase consumeConditionalExpression(OperatorExpression.QUESTIONCOLON) ; $break ./ + + AssignmentExpression -> ConditionalExpression + AssignmentExpression -> Assignment + + Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression + /.$putCase consumeAssignment(); $break ./ + + -- this rule is added to parse an array initializer in a assigment and then report a syntax error knowing the exact senario + InvalidArrayInitializerAssignement ::= LeftHandSide AssignmentOperator ArrayInitializer + Assignment ::= InvalidArrayInitializerAssignement + /.$putcase ignoreExpressionAssignment();$break ./ + + LeftHandSide ::= Name + /.$putCase consumeLeftHandSide(); $break ./ + LeftHandSide -> FieldAccess + LeftHandSide -> ArrayAccess + + AssignmentOperator ::= '=' + /.$putCase consumeAssignmentOperator(EQUAL); $break ./ + AssignmentOperator ::= '*=' + /.$putCase consumeAssignmentOperator(MULTIPLY); $break ./ + AssignmentOperator ::= '/=' + /.$putCase consumeAssignmentOperator(DIVIDE); $break ./ + AssignmentOperator ::= '%=' + /.$putCase consumeAssignmentOperator(REMAINDER); $break ./ + AssignmentOperator ::= '+=' + /.$putCase consumeAssignmentOperator(PLUS); $break ./ + AssignmentOperator ::= '-=' + /.$putCase consumeAssignmentOperator(MINUS); $break ./ + AssignmentOperator ::= '<<=' + /.$putCase consumeAssignmentOperator(LEFT_SHIFT); $break ./ + AssignmentOperator ::= '>>=' + /.$putCase consumeAssignmentOperator(RIGHT_SHIFT); $break ./ + AssignmentOperator ::= '>>>=' + /.$putCase consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT); $break ./ + AssignmentOperator ::= '&=' + /.$putCase consumeAssignmentOperator(AND); $break ./ + AssignmentOperator ::= '^=' + /.$putCase consumeAssignmentOperator(XOR); $break ./ + AssignmentOperator ::= '|=' + /.$putCase consumeAssignmentOperator(OR); $break ./ + + Expression -> AssignmentExpression + + ConstantExpression -> Expression + + -- The following rules are for optional nonterminals. + -- + + PackageDeclarationopt -> $empty + PackageDeclarationopt -> PackageDeclaration + + ClassHeaderExtendsopt ::= $empty + ClassHeaderExtendsopt -> ClassHeaderExtends + + Expressionopt ::= $empty + /.$putCase consumeEmptyExpression(); $break ./ + Expressionopt -> Expression + + + --------------------------------------------------------------------------------------- + -- + -- The rules below are for optional terminal symbols. An optional comma, + -- is only used in the context of an array initializer - It is a + -- "syntactic sugar" that otherwise serves no other purpose. By contrast, + -- an optional identifier is used in the definition of a break and + -- continue statement. When the identifier does not appear, a NULL + -- is produced. When the identifier is present, the user should use the + -- corresponding TOKEN(i) method. See break statement as an example. + -- + --------------------------------------------------------------------------------------- + + ,opt -> $empty + ,opt -> , + + ImportDeclarationsopt ::= $empty + /.$putCase consumeEmptyImportDeclarationsopt(); $break ./ + ImportDeclarationsopt ::= ImportDeclarations + /.$putCase consumeImportDeclarationsopt(); $break ./ + + + TypeDeclarationsopt ::= $empty + /.$putCase consumeEmptyTypeDeclarationsopt(); $break ./ + TypeDeclarationsopt ::= TypeDeclarations + /.$putCase consumeTypeDeclarationsopt(); $break ./ + + ClassBodyDeclarationsopt ::= $empty + /.$putCase consumeEmptyClassBodyDeclarationsopt(); $break ./ + ClassBodyDeclarationsopt ::= NestedType ClassBodyDeclarations + /.$putCase consumeClassBodyDeclarationsopt(); $break ./ + + Modifiersopt ::= $empty + /. $putCase consumeDefaultModifiers(); $break ./ + Modifiersopt ::= Modifiers + /.$putCase consumeModifiers(); $break ./ + + BlockStatementsopt ::= $empty + /.$putCase consumeEmptyBlockStatementsopt(); $break ./ + BlockStatementsopt -> BlockStatements + + Dimsopt ::= $empty + /. $putCase consumeEmptyDimsopt(); $break ./ + Dimsopt -> Dims + + ArgumentListopt ::= $empty + /. $putCase consumeEmptyArgumentListopt(); $break ./ + ArgumentListopt -> ArgumentList + + MethodHeaderThrowsClauseopt ::= $empty + MethodHeaderThrowsClauseopt -> MethodHeaderThrowsClause + + FormalParameterListopt ::= $empty + /.$putcase consumeFormalParameterListopt(); $break ./ + FormalParameterListopt -> FormalParameterList + + ClassHeaderImplementsopt ::= $empty + ClassHeaderImplementsopt -> ClassHeaderImplements + + InterfaceMemberDeclarationsopt ::= $empty + /. $putCase consumeEmptyInterfaceMemberDeclarationsopt(); $break ./ + InterfaceMemberDeclarationsopt ::= NestedType InterfaceMemberDeclarations + /. $putCase consumeInterfaceMemberDeclarationsopt(); $break ./ + + NestedType ::= $empty + /.$putCase consumeNestedType(); $break./ + + ForInitopt ::= $empty + /. $putCase consumeEmptyForInitopt(); $break ./ + ForInitopt -> ForInit + + ForUpdateopt ::= $empty + /. $putCase consumeEmptyForUpdateopt(); $break ./ + ForUpdateopt -> ForUpdate + + InterfaceHeaderExtendsopt ::= $empty + InterfaceHeaderExtendsopt -> InterfaceHeaderExtends + + Catchesopt ::= $empty + /. $putCase consumeEmptyCatchesopt(); $break ./ + Catchesopt -> Catches + + ArrayInitializeropt ::= $empty + /. $putCase consumeEmptyArrayInitializeropt(); $break ./ + ArrayInitializeropt -> ArrayInitializer + + /. } + } ./ + + --------------------------------------------------------------------------------------- + + $names + + -- BodyMarker ::= '"class Identifier { ... MethodHeader "' + + -- void ::= 'void' + + PLUS_PLUS ::= '++' + MINUS_MINUS ::= '--' + EQUAL_EQUAL ::= '==' + LESS_EQUAL ::= '<=' + GREATER_EQUAL ::= '>=' + NOT_EQUAL ::= '!=' + LEFT_SHIFT ::= '<<' + RIGHT_SHIFT ::= '>>' + UNSIGNED_RIGHT_SHIFT ::= '>>>' + PLUS_EQUAL ::= '+=' + MINUS_EQUAL ::= '-=' + MULTIPLY_EQUAL ::= '*=' + DIVIDE_EQUAL ::= '/=' + AND_EQUAL ::= '&=' + OR_EQUAL ::= '|=' + XOR_EQUAL ::= '^=' + REMAINDER_EQUAL ::= '%=' + LEFT_SHIFT_EQUAL ::= '<<=' + RIGHT_SHIFT_EQUAL ::= '>>=' + UNSIGNED_RIGHT_SHIFT_EQUAL ::= '>>>=' + OR_OR ::= '||' + AND_AND ::= '&&' + + PLUS ::= '+' + MINUS ::= '-' + NOT ::= '!' + REMAINDER ::= '%' + XOR ::= '^' + AND ::= '&' + MULTIPLY ::= '*' + OR ::= '|' + TWIDDLE ::= '~' + DIVIDE ::= '/' + GREATER ::= '>' + LESS ::= '<' + LPAREN ::= '(' + RPAREN ::= ')' + LBRACE ::= '{' + RBRACE ::= '}' + LBRACKET ::= '[' + RBRACKET ::= ']' + SEMICOLON ::= ';' + QUESTION ::= '?' + COLON ::= ':' + COMMA ::= ',' + DOT ::= '.' + EQUAL ::= '=' + + $end + -- need a carriage return after the $end + */ + } + protected void ignoreExpressionAssignment() { + // Assignment ::= InvalidArrayInitializerAssignement + // encoded operator would be: intStack[intPtr] + intPtr--; + ArrayInitializer arrayInitializer = (ArrayInitializer) expressionStack[expressionPtr--]; + expressionLengthPtr--; + // report a syntax error and abort parsing + problemReporter().arrayConstantsOnlyInArrayInitializers(arrayInitializer.sourceStart, arrayInitializer.sourceEnd); + } + protected void ignoreInterfaceDeclaration() { + // BlockStatement ::= InvalidInterfaceDeclaration + //InterfaceDeclaration ::= Modifiersopt 'interface' 'Identifier' ExtendsInterfacesopt InterfaceHeader InterfaceBody + + // length declarations + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + //there are length declarations + //dispatch according to the type of the declarations + dispatchDeclarationInto(length); + } + + flushAnnotationsDefinedPriorTo(endStatementPosition); + + // report the problem and continue parsing + TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr]; + typeDecl.bodyEnd = endStatementPosition; + problemReporter().cannotDeclareLocalInterface(typeDecl.name, typeDecl.sourceStart, typeDecl.sourceEnd); + + // mark fields and initializer with local type mark if needed + markFieldsWithLocalType(typeDecl); + + // remove the ast node created in interface header + astPtr--; + // Don't create an astnode for this inner interface, but have to push + // a 0 on the astLengthStack to be consistent with the reduction made + // at the end of the method: + // public void parse(MethodDeclaration md, CompilationUnitDeclaration unit) + pushOnAstLengthStack(0); + } + protected void ignoreInvalidConstructorDeclaration(boolean hasBody) { + // InvalidConstructorDeclaration ::= ConstructorHeader ConstructorBody ==> true + // InvalidConstructorDeclaration ::= ConstructorHeader ';' ==> false + + /* + astStack : modifiers arguments throws statements + identifierStack : name + ==> + astStack : MethodDeclaration + identifierStack : + */ + + //must provide a default constructor call when needed + + if (hasBody) { + // pop the position of the { (body of the method) pushed in block decl + intPtr--; + } + + //statements + if (hasBody) { + realBlockPtr--; + } + + int length; + if (hasBody && ((length = astLengthStack[astLengthPtr--]) != 0)) { + astPtr -= length; + } + } + protected void ignoreMethodBody() { + // InterfaceMemberDeclaration ::= InvalidMethodDeclaration + + /* + astStack : modifiers arguments throws statements + identifierStack : type name + intStack : dim dim dim + ==> + astStack : MethodDeclaration + identifierStack : + intStack : + */ + + // pop the position of the { (body of the method) pushed in block decl + intPtr--; + // retrieve end position of method declarator + + //statements + realBlockPtr--; + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + astPtr -= length; + } + + //watch for } that could be given as a unicode ! ( u007D is '}' ) + MethodDeclaration md = (MethodDeclaration) astStack[astPtr]; + md.bodyEnd = endPosition; + md.declarationSourceEnd = flushAnnotationsDefinedPriorTo(endStatementPosition); + + // report the problem and continue the parsing - narrowing the problem onto the method + problemReporter().abstractMethodNeedingNoBody(md); + } + public void initialize() { + //positionning the parser for a new compilation unit + //avoiding stack reallocation and all that.... + astPtr = -1; + astLengthPtr = -1; + expressionPtr = -1; + expressionLengthPtr = -1; + identifierPtr = -1; + identifierLengthPtr = -1; + intPtr = -1; + nestedMethod[nestedType = 0] = 0; // need to reset for further reuse + variablesCounter[nestedType] = 0; + dimensions = 0; + realBlockPtr = -1; + compilationUnit = null; + referenceContext = null; + endStatementPosition = 0; + + //remove objects from stack too, while the same parser/compiler couple is + //re-used between two compilations .... + + int astLength = astStack.length; + if (noAstNodes.length < astLength) { + noAstNodes = new AstNode[astLength]; + //System.out.println("Resized AST stacks : "+ astLength); + + } + System.arraycopy(noAstNodes, 0, astStack, 0, astLength); + + int expressionLength = expressionStack.length; + if (noExpressions.length < expressionLength) { + noExpressions = new Expression[expressionLength]; + //System.out.println("Resized EXPR stacks : "+ expressionLength); + } + System.arraycopy(noExpressions, 0, expressionStack, 0, expressionLength); + + // reset scanner state + scanner.commentPtr = -1; + scanner.eofPosition = Integer.MAX_VALUE; + + resetModifiers(); + + // recovery + lastCheckPoint = -1; + currentElement = null; + restartRecovery = false; + hasReportedError = false; + recoveredStaticInitializerStart = 0; + lastIgnoredToken = -1; + lastErrorEndPosition = -1; + listLength = 0; + } + public void initializeScanner() { + this.scanner = + new Scanner( + false, + false, + this.problemReporter.options.getNonExternalizedStringLiteralSeverity() != ProblemSeverities.Ignore, + this.assertMode); + } + 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$ + symbol_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + action = lhs; + } + public final 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 (diet && (dietInt == 0)) + scanner.diet = true; + } + protected void markCurrentMethodWithLocalType() { + 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 TypeDeclaration) { // mark type for now: all fields will be marked when added to this type + node.bits |= AstNode.HasLocalTypeMASK; + return; + } + } + // default to reference context (case of parse method body) + if (this.referenceContext instanceof AbstractMethodDeclaration || this.referenceContext instanceof TypeDeclaration) { + ((AstNode) this.referenceContext).bits |= AstNode.HasLocalTypeMASK; + } + } + protected void markFieldsWithLocalType(TypeDeclaration type) { + if (type.fields == null || (type.bits & AstNode.HasLocalTypeMASK) == 0) + return; + for (int i = 0, length = type.fields.length; i < length; i++) { + type.fields[i].bits |= AstNode.HasLocalTypeMASK; + } + } + /* + * Move checkpoint location (current implementation is moving it by one token) + * + * Answers true if successfully moved checkpoint (i.e. did not attempt to move it + * beyond end of file). + */ + protected boolean moveRecoveryCheckpoint() { + + int pos = lastCheckPoint; + /* reset scanner, and move checkpoint by one token */ + scanner.startPosition = pos; + scanner.currentPosition = pos; + scanner.diet = false; // quit jumping over method bodies + + /* if about to restart, then no need to shift token */ + if (restartRecovery) { + lastIgnoredToken = -1; + return true; + } + + /* protect against shifting on an invalid token */ + lastIgnoredToken = nextIgnoredToken; + nextIgnoredToken = -1; + do { + try { + nextIgnoredToken = scanner.getNextToken(); + if (scanner.currentPosition == scanner.startPosition) { + scanner.currentPosition++; // on fake completion identifier + nextIgnoredToken = -1; + } + + } catch (InvalidInputException e) { + pos = scanner.currentPosition; + } + } while (nextIgnoredToken < 0); + + if (nextIgnoredToken == TokenNameEOF) { // no more recovery after this point + if (currentToken == TokenNameEOF) { // already tried one iteration on EOF + return false; + } + } + lastCheckPoint = scanner.currentPosition; + + /* reset scanner again to previous checkpoint location*/ + scanner.startPosition = pos; + scanner.currentPosition = pos; + scanner.commentPtr = -1; + + return true; + + /* + The following implementation moves the checkpoint location by one line: + + int pos = lastCheckPoint; + // reset scanner, and move checkpoint by one token + scanner.startPosition = pos; + scanner.currentPosition = pos; + scanner.diet = false; // quit jumping over method bodies + + // if about to restart, then no need to shift token + if (restartRecovery){ + lastIgnoredToken = -1; + return true; + } + + // protect against shifting on an invalid token + lastIgnoredToken = nextIgnoredToken; + nextIgnoredToken = -1; + + boolean wasTokenizingWhiteSpace = scanner.tokenizeWhiteSpace; + scanner.tokenizeWhiteSpace = true; + checkpointMove: + do { + try { + nextIgnoredToken = scanner.getNextToken(); + switch(nextIgnoredToken){ + case Scanner.TokenNameWHITESPACE : + if(scanner.getLineNumber(scanner.startPosition) + == scanner.getLineNumber(scanner.currentPosition)){ + nextIgnoredToken = -1; + } + break; + case TokenNameSEMICOLON : + case TokenNameLBRACE : + case TokenNameRBRACE : + break; + case TokenNameIdentifier : + if(scanner.currentPosition == scanner.startPosition){ + scanner.currentPosition++; // on fake completion identifier + } + default: + nextIgnoredToken = -1; + break; + case TokenNameEOF : + break checkpointMove; + } + } catch(InvalidInputException e){ + pos = scanner.currentPosition; + } + } while (nextIgnoredToken < 0); + scanner.tokenizeWhiteSpace = wasTokenizingWhiteSpace; + + if (nextIgnoredToken == TokenNameEOF) { // no more recovery after this point + if (currentToken == TokenNameEOF) { // already tried one iteration on EOF + return false; + } + } + lastCheckPoint = scanner.currentPosition; + + // reset scanner again to previous checkpoint location + scanner.startPosition = pos; + scanner.currentPosition = pos; + scanner.commentPtr = -1; + + return true; + */ + } + protected MessageSend newMessageSend() { + // '(' ArgumentListopt ')' + // the arguments are on the expression stack + + MessageSend m = new MessageSend(); + int length; + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, m.arguments = new Expression[length], 0, length); + }; + return m; + } + protected static int ntAction(int state, int sym) { + return action[state + sym]; + } + private final void optimizedConcatNodeLists() { + /*back from a recursive loop. Virtualy group the + astNode into an array using astLengthStack*/ + + /* + * This is a case where you have two sublists into the astStack that you want + * to merge in one list. There is no action required on the 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 astStack. + * Look at the InterfaceMemberDeclarations for an example. + * This case optimizes the fact that p == 1. + */ + + astLengthStack[--astLengthPtr]++; + } + protected static int original_state(int state) { + return -check(state); + } + /*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() { + + hasReportedError = false; + int act = START_STATE; + stateStackTop = -1; + currentToken = getFirstToken(); + ProcessTerminals : for (;;) { + try { + stack[++stateStackTop] = act; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = stack.length; + int oldStack[] = stack; + stack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, stack, 0, oldStackLength); + stack[stateStackTop] = act; + }; + + act = tAction(act, currentToken); + + if (act == ERROR_ACTION || restartRecovery) { + int errorPos = scanner.currentPosition; + if (!hasReportedError) { + this.reportSyntaxError(ERROR_ACTION, currentToken, stateStackTop); + hasReportedError = true; + } + if (resumeOnSyntaxError()) { + if (act == ERROR_ACTION) + lastErrorEndPosition = errorPos; + act = START_STATE; + stateStackTop = -1; + currentToken = getFirstToken(); + continue ProcessTerminals; + } else { + act = ERROR_ACTION; + } + break ProcessTerminals; + } + if (act <= NUM_RULES) + stateStackTop--; + else if (act > ERROR_ACTION) { /* shift-reduce */ + consumeToken(currentToken); + if (currentElement != null) + this.recoveryTokenCheck(); + try { + currentToken = scanner.getNextToken(); + } catch (InvalidInputException e) { + if (!hasReportedError) { + this.problemReporter().scannerError(this, e.getMessage()); + hasReportedError = true; + } + lastCheckPoint = scanner.currentPosition; + restartRecovery = true; + } + act -= ERROR_ACTION; + } else if (act < ACCEPT_ACTION) { /* shift */ + consumeToken(currentToken); + if (currentElement != null) + this.recoveryTokenCheck(); + try { + currentToken = scanner.getNextToken(); + } catch (InvalidInputException e) { + if (!hasReportedError) { + this.problemReporter().scannerError(this, e.getMessage()); + hasReportedError = true; + } + lastCheckPoint = scanner.currentPosition; + restartRecovery = true; + } + continue ProcessTerminals; + } else + break ProcessTerminals; + + ProcessNonTerminals : do { /* reduce */ + consumeRule(act); + stateStackTop -= (rhs[act] - 1); + act = ntAction(stack[stateStackTop], lhs[act]); + } while (act <= NUM_RULES); + } + endParse(act); + } + // A P I + + public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { + //only parse the method body of cd + //fill out its statements + + //convert bugs into parse error + + initialize(); + goForConstructorBody(); + nestedMethod[nestedType]++; + + referenceContext = cd; + compilationUnit = unit; + + scanner.resetTo(cd.sourceEnd + 1, cd.declarationSourceEnd); + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } + + if (lastAct == ERROR_ACTION) { + initialize(); + return; + } + + //statements + cd.explicitDeclarations = realBlockStack[realBlockPtr--]; + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) { + astPtr -= length; + if (astStack[astPtr + 1] instanceof ExplicitConstructorCall) + //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? + { + System.arraycopy(astStack, astPtr + 2, cd.statements = new Statement[length - 1], 0, length - 1); + cd.constructorCall = (ExplicitConstructorCall) astStack[astPtr + 1]; + } else { //need to add explicitly the super(); + System.arraycopy(astStack, astPtr + 1, cd.statements = new Statement[length], 0, length); + cd.constructorCall = SuperReference.implicitSuperConstructorCall(); + } + } else { + cd.constructorCall = SuperReference.implicitSuperConstructorCall(); + } + + if (cd.constructorCall.sourceEnd == 0) { + cd.constructorCall.sourceEnd = cd.sourceEnd; + cd.constructorCall.sourceStart = cd.sourceStart; + } + } + // A P I + + public void parse(Initializer ini, TypeDeclaration type, CompilationUnitDeclaration unit) { + //only parse the method body of md + //fill out method statements + + //convert bugs into parse error + + initialize(); + goForInitializer(); + nestedMethod[nestedType]++; + + referenceContext = type; + compilationUnit = unit; + + scanner.resetTo(ini.sourceStart, ini.sourceEnd); // just on the beginning { + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } + + if (lastAct == ERROR_ACTION) { + return; + } + + ini.block = ((Initializer) astStack[astPtr]).block; + + // mark initializer with local type if one was found during parsing + if ((type.bits & AstNode.HasLocalTypeMASK) != 0) { + ini.bits |= AstNode.HasLocalTypeMASK; + } + } + // 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.isNative()) + return; + if ((md.modifiers & AccSemicolonBody) != 0) + return; + + initialize(); + goForMethodBody(); + nestedMethod[nestedType]++; + + referenceContext = md; + compilationUnit = unit; + + scanner.resetTo(md.sourceEnd + 1, md.declarationSourceEnd); + // reset the scanner to parser from { down to } + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } + + if (lastAct == ERROR_ACTION) { + return; + } + + //refill statements + md.explicitDeclarations = realBlockStack[realBlockPtr--]; + int length; + if ((length = astLengthStack[astLengthPtr--]) != 0) + System.arraycopy(astStack, (astPtr -= length) + 1, md.statements = new Statement[length], 0, length); + } + // A P I + + public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult) { + // parses a compilation unit and manages error handling (even bugs....) + + CompilationUnitDeclaration unit; + try { + /* automaton initialization */ + initialize(); + goForCompilationUnit(); + + /* scanner initialization */ + scanner.setSource(sourceUnit.getContents()); + + /* unit creation */ + referenceContext = + compilationUnit = new CompilationUnitDeclaration(problemReporter, compilationResult, scanner.source.length); + /* run automaton */ + parse(); + } finally { + unit = compilationUnit; + compilationUnit = null; // reset parser + } + return unit; + } + // 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(); + goForCompilationUnit(); + + /* scanner initialization */ + scanner.setSource(sourceUnit.getContents()); + scanner.resetTo(start, end); + /* unit creation */ + referenceContext = + compilationUnit = new CompilationUnitDeclaration(problemReporter, compilationResult, scanner.source.length); + /* run automaton */ + parse(); + } finally { + unit = compilationUnit; + compilationUnit = null; // reset parser + } + return unit; + } + /** + * 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. + */ + public ProblemReporter problemReporter() { + if (scanner.recordLineSeparator) { + compilationUnit.compilationResult.lineSeparatorPositions = scanner.getLineEnds(); + } + problemReporter.referenceContext = referenceContext; + return 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 */ + + try { + identifierStack[++identifierPtr] = scanner.getCurrentIdentifierSource(); + identifierPositionStack[identifierPtr] = (((long) scanner.startPosition) << 32) + (scanner.currentPosition - 1); + } catch (IndexOutOfBoundsException e) { + /*---stack reallaocation (identifierPtr is correct)---*/ + int oldStackLength = identifierStack.length; + char[][] oldStack = identifierStack; + identifierStack = new char[oldStackLength + 20][]; + System.arraycopy(oldStack, 0, identifierStack, 0, oldStackLength); + identifierStack[identifierPtr] = scanner.getCurrentTokenSource(); + /*identifier position stack*/ + long[] oldPos = identifierPositionStack; + identifierPositionStack = new long[oldStackLength + 20]; + System.arraycopy(oldPos, 0, identifierPositionStack, 0, oldStackLength); + identifierPositionStack[identifierPtr] = (((long) scanner.startPosition) << 32) + (scanner.currentPosition - 1); + }; + + try { + identifierLengthStack[++identifierLengthPtr] = 1; + } catch (IndexOutOfBoundsException e) { + /*---stack reallocation (identifierLengthPtr is correct)---*/ + int oldStackLength = identifierLengthStack.length; + int oldStack[] = identifierLengthStack; + identifierLengthStack = new int[oldStackLength + 10]; + System.arraycopy(oldStack, 0, identifierLengthStack, 0, oldStackLength); + identifierLengthStack[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 */ + + try { + identifierLengthStack[++identifierLengthPtr] = flag; + } catch (IndexOutOfBoundsException e) { + /*---stack reallaocation (identifierLengthPtr is correct)---*/ + int oldStackLength = identifierLengthStack.length; + int oldStack[] = identifierLengthStack; + identifierLengthStack = new int[oldStackLength + 10]; + System.arraycopy(oldStack, 0, identifierLengthStack, 0, oldStackLength); + identifierLengthStack[identifierLengthPtr] = flag; + }; + + } + protected void pushOnAstLengthStack(int pos) { + try { + astLengthStack[++astLengthPtr] = pos; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = astLengthStack.length; + int[] oldPos = astLengthStack; + astLengthStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldPos, 0, astLengthStack, 0, oldStackLength); + astLengthStack[astLengthPtr] = pos; + } + } + protected void pushOnAstStack(AstNode node) { + /*add a new obj on top of the ast stack + astPtr points on the top*/ + + try { + astStack[++astPtr] = node; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = astStack.length; + AstNode[] oldStack = astStack; + astStack = new AstNode[oldStackLength + AstStackIncrement]; + System.arraycopy(oldStack, 0, astStack, 0, oldStackLength); + astPtr = oldStackLength; + astStack[astPtr] = node; + } + + try { + astLengthStack[++astLengthPtr] = 1; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = astLengthStack.length; + int[] oldPos = astLengthStack; + astLengthStack = new int[oldStackLength + AstStackIncrement]; + System.arraycopy(oldPos, 0, astLengthStack, 0, oldStackLength); + astLengthStack[astLengthPtr] = 1; + } + } + protected void pushOnExpressionStack(Expression expr) { + + try { + expressionStack[++expressionPtr] = expr; + } catch (IndexOutOfBoundsException e) { + //expressionPtr is correct + int oldStackLength = expressionStack.length; + Expression[] oldStack = expressionStack; + expressionStack = new Expression[oldStackLength + ExpressionStackIncrement]; + System.arraycopy(oldStack, 0, expressionStack, 0, oldStackLength); + expressionStack[expressionPtr] = expr; + } + + try { + expressionLengthStack[++expressionLengthPtr] = 1; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = expressionLengthStack.length; + int[] oldPos = expressionLengthStack; + expressionLengthStack = new int[oldStackLength + ExpressionStackIncrement]; + System.arraycopy(oldPos, 0, expressionLengthStack, 0, oldStackLength); + expressionLengthStack[expressionLengthPtr] = 1; + } + } + protected void pushOnExpressionStackLengthStack(int pos) { + try { + expressionLengthStack[++expressionLengthPtr] = pos; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = expressionLengthStack.length; + int[] oldPos = expressionLengthStack; + expressionLengthStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldPos, 0, expressionLengthStack, 0, oldStackLength); + expressionLengthStack[expressionLengthPtr] = pos; + } + } + protected void pushOnIntStack(int pos) { + + try { + intStack[++intPtr] = pos; + } catch (IndexOutOfBoundsException e) { + //intPtr is correct + int oldStackLength = intStack.length; + int oldStack[] = intStack; + intStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, intStack, 0, oldStackLength); + intStack[intPtr] = pos; + } + } + protected static char[] readTable(String filename) throws java.io.IOException { + + //files are located at Parser.class directory + + InputStream stream = new BufferedInputStream(Parser.class.getResourceAsStream(filename)); + if (stream == null) { + throw new java.io.IOException(Util.bind("parser.missingFile", filename)); //$NON-NLS-1$ + } + byte[] bytes = null; + try { + bytes = Util.getInputStreamAsByteArray(stream, -1); + } finally { + try { + stream.close(); + } catch (IOException e) { + } + } + + //minimal integrity check (even size expected) + int length = bytes.length; + if (length % 2 != 0) + throw new java.io.IOException(Util.bind("parser.corruptedFile", filename)); //$NON-NLS-1$ + + // 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; + } + /* Token check performed on every token shift once having entered + * recovery mode. + */ + public void recoveryTokenCheck() { + switch (currentToken) { + case TokenNameLBRACE : + { + RecoveredElement newElement = currentElement.updateOnOpeningBrace(scanner.currentPosition - 1); + lastCheckPoint = scanner.currentPosition; + if (newElement != null) { // null means nothing happened + restartRecovery = true; // opening brace detected + currentElement = newElement; + } + break; + } + case TokenNameRBRACE : + { + endPosition = this.flushAnnotationsDefinedPriorTo(scanner.currentPosition - 1); + RecoveredElement newElement = currentElement.updateOnClosingBrace(scanner.startPosition, scanner.currentPosition - 1); + lastCheckPoint = scanner.currentPosition; + if (newElement != currentElement) { + currentElement = newElement; + } + } + } + } + protected void reportSyntaxError(int act, int currentKind, int stateStackTop) { + + /* remember current scanner position */ + int startPos = scanner.startPosition; + int currentPos = scanner.currentPosition; + + String[] expectings; + String tokenName = name[symbol_index[currentKind]]; + + //fetch all "accurate" possible terminals that could recover the error + int start, end = start = asi(stack[stateStackTop]); + while (asr[end] != 0) + end++; + int length = end - start; + expectings = new String[length]; + if (length != 0) { + char[] indexes = new char[length]; + System.arraycopy(asr, start, indexes, 0, length); + for (int i = 0; i < length; i++) { + expectings[i] = name[symbol_index[indexes[i]]]; + } + } + + //if the pb is an EOF, try to tell the user that they are some + if (tokenName.equals(UNEXPECTED_EOF)) { + if (!this.checkAndReportBracketAnomalies(problemReporter())) { + char[] tokenSource; + try { + tokenSource = this.scanner.getCurrentTokenSource(); + } catch (Exception e) { + tokenSource = new char[] { + }; + } + problemReporter().parseError( + this.scanner.startPosition, + this.scanner.currentPosition - 1, + tokenSource, + tokenName, + expectings); + } + } else { //the next test is HEAVILY grammar DEPENDENT. + if ((length == 2) && (tokenName.equals(";")) //$NON-NLS-1$ + && (expectings[0] == "++") //$NON-NLS-1$ + && (expectings[1] == "--") //$NON-NLS-1$ + && (expressionPtr > -1)) { + // the ; is not the expected token ==> it ends a statement when an expression is not ended + problemReporter().invalidExpressionAsStatement(expressionStack[expressionPtr]); + } else { + char[] tokenSource; + try { + tokenSource = this.scanner.getCurrentTokenSource(); + } catch (Exception e) { + tokenSource = new char[] { + }; + } + problemReporter().parseError( + this.scanner.startPosition, + this.scanner.currentPosition - 1, + tokenSource, + tokenName, + expectings); + this.checkAndReportBracketAnomalies(problemReporter()); + } + } + /* reset scanner where it was */ + scanner.startPosition = startPos; + scanner.currentPosition = currentPos; + } + protected void resetModifiers() { + modifiers = AccDefault; + modifiersSourceStart = -1; // <-- see comment into modifiersFlag(int) + scanner.commentPtr = -1; + } + /* + * Reset context so as to resume to regular parse loop + */ + protected void resetStacks() { + + astPtr = -1; + astLengthPtr = -1; + expressionPtr = -1; + expressionLengthPtr = -1; + identifierPtr = -1; + identifierLengthPtr = -1; + intPtr = -1; + nestedMethod[nestedType = 0] = 0; // need to reset for further reuse + variablesCounter[nestedType] = 0; + dimensions = 0; + realBlockStack[realBlockPtr = 0] = 0; + recoveredStaticInitializerStart = 0; + listLength = 0; + } + /* + * Reset context so as to resume to regular parse loop + * If unable to reset for resuming, answers false. + * + * Move checkpoint location, reset internal stacks and + * decide which grammar goal is activated. + */ + protected boolean resumeAfterRecovery() { + + // reset internal stacks + this.resetStacks(); + + /* attempt to move checkpoint location */ + if (!this.moveRecoveryCheckpoint()) + return false; + + // only look for headers + if (referenceContext instanceof CompilationUnitDeclaration) { + goForHeaders(); + diet = true; // passed this point, will not consider method bodies + return true; + } + // does not know how to restart + return false; + } + /* + * Syntax error was detected. Will attempt to perform some recovery action in order + * to resume to the regular parse loop. + */ + protected boolean resumeOnSyntaxError() { + + /* request recovery initialization */ + if (currentElement == null) { + currentElement = this.buildInitialRecoveryState(); // build some recovered elements + } + /* do not investigate deeper in recovery when no recovered element */ + if (currentElement == null) + return false; + + /* manual forced recovery restart - after headers */ + if (restartRecovery) { + 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(); + } + protected static int tAction(int state, int sym) { + return action[check(state + sym) == sym ? state + sym : state]; + } + public String toString() { + + String s = "identifierStack : char[][] = {"; //$NON-NLS-1$ + for (int i = 0; i <= identifierPtr; i++) { + s = s + "\"" + String.valueOf(identifierStack[i]) + "\","; //$NON-NLS-1$ //$NON-NLS-2$ + }; + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "identierLengthStack : int[] = {"; //$NON-NLS-1$ + for (int i = 0; i <= identifierLengthPtr; i++) { + s = s + identifierLengthStack[i] + ","; //$NON-NLS-1$ + }; + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "astLengthStack : int[] = {"; //$NON-NLS-1$ + for (int i = 0; i <= astLengthPtr; i++) { + s = s + astLengthStack[i] + ","; //$NON-NLS-1$ + }; + s = s + "}\n"; //$NON-NLS-1$ + s = s + "astPtr : int = " + String.valueOf(astPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + s = s + "intStack : int[] = {"; //$NON-NLS-1$ + for (int i = 0; i <= intPtr; i++) { + s = s + intStack[i] + ","; //$NON-NLS-1$ + }; + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "expressionLengthStack : int[] = {"; //$NON-NLS-1$ + for (int i = 0; i <= expressionLengthPtr; i++) { + s = s + expressionLengthStack[i] + ","; //$NON-NLS-1$ + }; + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "expressionPtr : int = " + String.valueOf(expressionPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + s = s + "\n\n\n----------------Scanner--------------\n" + 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 */ + 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 + astStack[astPtr - variableDeclaratorsCounter + 1].sourceStart; + for (int i = 0; i < variableDeclaratorsCounter - 1; i++) { + //last one is special(see below) + field = (FieldDeclaration) astStack[astPtr - i - 1]; + field.endPart1Position = endTypeDeclarationPosition; + field.endPart2Position = -1 + astStack[astPtr - i].sourceStart; + } + //last one + (field = (FieldDeclaration) astStack[astPtr]).endPart1Position = endTypeDeclarationPosition; + field.endPart2Position = field.declarationSourceEnd; + + } + protected void updateSourcePosition(Expression exp) { + //update the source Position of the expression + + //intStack : int int + //--> + //intStack : + + exp.sourceEnd = intStack[intPtr--]; + exp.sourceStart = intStack[intPtr--]; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java index c685210..8eb108a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/IPreferenceConstants.java @@ -11,75 +11,92 @@ Contributors: **********************************************************************/ package net.sourceforge.phpeclipse; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IPluginDescriptor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Status; -//import org.eclipse.jdt.internal.ui.JavaStatusConstants; -//import org.eclipse.jdt.internal.ui.JavaUIMessages; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.plugin.AbstractUIPlugin; - /** * The main plugin class to be used in the desktop. */ public interface IPreferenceConstants { - - public static final String LOCALHOST_PREF = "_localhost"; //$NON-NLS-1$ - public static final String DOCUMENTROOT_PREF = "_documentroot"; //$NON-NLS-1$ - public static final String USE_EXTERNAL_BROWSER_PREF = "_use_external_browser"; //$NON-NLS-1$ - public static final String EXTERNAL_BROWSER_PREF = "_external_browser"; //$NON-NLS-1$ - public static final String MYSQL_PREF = "_my_sql"; //$NON-NLS-1$ - public static final String APACHE_START_PREF = "_apache_start"; //$NON-NLS-1$ - public static final String APACHE_STOP_PREF = "_apache_stop"; //$NON-NLS-1$ - public static final String APACHE_RESTART_PREF = "_apache_restart"; //$NON-NLS-1$ - public static final String SHOW_OUTPUT_IN_CONSOLE = "_sho_output_in_console"; //$NON-NLS-1$ - public static final String EXTERNAL_PARSER_PREF = "_external_parser"; //$NON-NLS-1$ + public static final String LOCALHOST_PREF = "_localhost"; + public static final String DOCUMENTROOT_PREF = "_documentroot"; + public static final String USE_EXTERNAL_BROWSER_PREF = "_use_external_browser"; + public static final String EXTERNAL_BROWSER_PREF = "_external_browser"; + public static final String MYSQL_PREF = "_my_sql"; + public static final String APACHE_START_PREF = "_apache_start"; + public static final String APACHE_STOP_PREF = "_apache_stop"; + public static final String APACHE_RESTART_PREF = "_apache_restart"; + public static final String SHOW_OUTPUT_IN_CONSOLE = "_sho_output_in_console"; + public static final String EXTERNAL_PARSER_PREF = "_external_parser"; + public static final String PHP_PARSER_DEFAULT = "_php_parser_default"; + public static final String PHP_INTERNAL_PARSER = "_php_internal_parser"; + public static final String PHP_EXTERNAL_PARSER = "_php_external_parser"; + public static final String PHP_PARSE_ON_SAVE = "_php_parse_on_save"; + public static final String PHP_MULTILINE_COMMENT = "_php_multilineComment"; + public static final String PHP_MULTILINE_COMMENT_BOLD = "_php_multilineComment_bold"; + public static final String PHP_MULTILINE_COMMENT_ITALIC = "_php_multilineComment_italic"; + public static final String PHP_MULTILINE_COMMENT_UNDERLINE = "_php_multilineComment_underline"; + public static final String PHP_SINGLELINE_COMMENT = "_php_singlelineComment"; + public static final String PHP_SINGLELINE_COMMENT_BOLD = "_php_singlelineComment_bold"; + public static final String PHP_SINGLELINE_COMMENT_ITALIC = "_php_singlelineComment_italic"; + public static final String PHP_SINGLELINE_COMMENT_UNDERLINE = "_php_singlelineComment_underline"; + public static final String PHP_KEYWORD = "_php_keyword"; + public static final String PHP_KEYWORD_BOLD = "_php_keyword_bold"; + public static final String PHP_KEYWORD_ITALIC = "_php_keyword_italic"; + public static final String PHP_KEYWORD_UNDERLINE = "_php_keyword_underline"; + public static final String PHP_VARIABLE = "_php_variable"; + public static final String PHP_VARIABLE_BOLD = "_php_variable_bold"; + public static final String PHP_VARIABLE_ITALIC = "_php_variable_italic"; + public static final String PHP_VARIABLE_UNDERLINE = "_php_variable_underline"; + public static final String PHP_TYPE = "_php_type"; + public static final String PHP_TYPE_BOLD = "_php_type_bold"; + public static final String PHP_TYPE_ITALIC = "_php_type_italic"; + public static final String PHP_TYPE_UNDERLINE = "_php_type_underline"; + public static final String PHP_CONSTANT = "_php_constant"; + public static final String PHP_CONSTANT_BOLD = "_php_constant_bold"; + public static final String PHP_CONSTANT_ITALIC = "_php_constant_italic"; + public static final String PHP_CONSTANT_UNDERLINE = "_php_constant_underline"; + public static final String PHP_FUNCTIONNAME = "_php_functionname"; + public static final String PHP_FUNCTIONNAME_BOLD = "_php_functionname_bold"; + public static final String PHP_FUNCTIONNAME_ITALIC = "_php_functionname_italic"; + public static final String PHP_FUNCTIONNAME_UNDERLINE = "_php_functionname_underline"; + public static final String PHP_STRING = "_php_string"; + public static final String PHP_STRING_BOLD = "_php_string_bold"; + public static final String PHP_STRING_ITALIC = "_php_string_italic"; + public static final String PHP_STRING_UNDERLINE = "_php_string_underline"; + public static final String PHP_DEFAULT = "_php_default"; + public static final String PHP_DEFAULT_BOLD = "_php_default_bold"; + public static final String PHP_DEFAULT_ITALIC = "_php_default_italic"; + public static final String PHP_DEFAULT_UNDERLINE = "_php_default_underline"; + public static final String LINKED_POSITION_COLOR = "_linkedPositionColor"; + public static final String PHP_EDITOR_BACKGROUND = "_php_editor_background"; + public static final String PHP_USERDEF_XMLFILE = "_userdef_xmlfile"; + + /*Language stuff - under dev*/ + public static final String RESOURCE_BUNDLE = "_php_editor_res_bundle"; //$NON-NLS-1$ + public static final String LANGUAGE_DEFAULT = "net.sourceforge.phpeclipse.newPHPPreferencesMessages_en_GB"; + public static final String RESOURCE_BUNDLE_DE = "net.sourceforge.phpeclipse.newPHPPreferencesMessages_DE"; + public static final String RESOURCE_BUNDLE_FR = "net.sourceforge.phpeclipse.newPHPPreferencesMessages_FR"; + public static final String RESOURCE_BUNDLE_EN_GB = "net.sourceforge.phpeclipse.newPHPPreferencesMessages_en_GB"; - public static final String PHP_PARSER_DEFAULT = "_php_parser_default"; //$NON-NLS-1$ - public static final String PHP_INTERNAL_PARSER = "_php_internal_parser"; //$NON-NLS-1$ - public static final String PHP_EXTERNAL_PARSER = "_php_external_parser"; //$NON-NLS-1$ - public static final String PHP_PARSE_ON_SAVE = "_php_parse_on_save"; //$NON-NLS-1$ - - public static final String PHP_MULTILINE_COMMENT = "_php_multilineComment"; //$NON-NLS-1$ - public static final String PHP_SINGLELINE_COMMENT = "_php_singlelineComment"; //$NON-NLS-1$ - public static final String PHP_KEYWORD = "_php_keyword"; //$NON-NLS-1$ - public static final String PHP_VARIABLE = "_php_variable"; //$NON-NLS-1$ - public static final String PHP_FUNCTIONNAME = "_php_functionname"; //$NON-NLS-1$ - public static final String PHP_STRING = "_php_string"; //$NON-NLS-1$ - public static final String PHP_DEFAULT = "_php_default"; //$NON-NLS-1$ - - public static final String LINKED_POSITION_COLOR= "_linkedPositionColor"; //$NON-NLS-1$ - + public static final String FORMATTER_TAB_SIZE = "_formatter_tab_size"; + public static final String SPACES_FOR_TABS = "_formatter_tab_size"; + + public static final String EDITOR_BOLD_SUFFIX = "_editor_bold_suffix"; /** Preference key for showing the line number ruler */ - public final static String LINE_NUMBER_RULER= "_lineNumberRuler"; //$NON-NLS-1$ + public final static String LINE_NUMBER_RULER = "_lineNumberRuler"; //$NON-NLS-1$ /** Preference key for the foreground color of the line numbers */ - public final static String LINE_NUMBER_COLOR= "_lineNumberColor"; //$NON-NLS-1$ - - public final static String FORMATTER_TAB_SIZE= "_formatterTabSize"; //$NON-NLS-1$ - public final static String SPACES_FOR_TABS = "false"; - + public final static String LINE_NUMBER_COLOR = "_lineNumberColor"; //$NON-NLS-1$ + public final static String PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT = "_defaultBackgroundColor"; //$NON-NLS-1$ public final static String PREFERENCE_COLOR_BACKGROUND = "backgroundColor"; //$NON-NLS-1$ - + /** Preference key for content assist proposal color */ - public final static String PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$ + public final static String PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ /** Preference key for content assist proposal color */ - public final static String PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$ + public final static String PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ + public static final String EDITOR_EVALUTE_TEMPORARY_PROBLEMS = null; + public static final String EDITOR_CORRECTION_INDICATION = null; - public static final String PHP_OUTLINE_CLASS = "_php_outline_class"; //$NON-NLS-1$ - public static final String PHP_OUTLINE_FUNC = "_php_outline_func"; //$NON-NLS-1$ - public static final String PHP_OUTLINE_VAR = "_php_outline_var"; //$NON-NLS-1$ + public static final String PHP_OUTLINE_CLASS = "_php_outline_class"; //$NON-NLS-1$ + public static final String PHP_OUTLINE_FUNC = "_php_outline_func"; //$NON-NLS-1$ + public static final String PHP_OUTLINE_VAR = "_php_outline_var"; //$NON-NLS-1$ } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPCore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPCore.java index 81943ac..454c2e8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPCore.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPCore.java @@ -3,16 +3,14 @@ package net.sourceforge.phpeclipse; import java.util.ArrayList; import java.util.List; +import net.sourceforge.phpeclipse.resourcesview.PHPFile; +import net.sourceforge.phpeclipse.resourcesview.PHPProject; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; -import net.sourceforge.phpeclipse.resourcesview.*; -import net.sourceforge.phpeclipse.resourcesview.PHPFile; -import net.sourceforge.phpeclipse.resourcesview.PHPProject; - public class PHPCore { public static IProject[] getPHPProjects() { @@ -26,7 +24,7 @@ public class PHPCore { } IProject[] phpProjects = new IProject[phpProjectsList.size()]; - return (IProject[]) phpProjectsList.toArray(phpProjects); + return (IProject[]) phpProjectsList.toArray(phpProjects); } public static PHPProject getPHPProject(String name) { @@ -76,7 +74,7 @@ public class PHPCore { System.err.println("Exception occurred in PHPCore#create(IProject): " + e.toString()); } - return null; + return null; } public static void addPHPNature(IProject project, IProgressMonitor monitor) throws CoreException { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipseBasePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipseBasePreferencePage.java new file mode 100644 index 0000000..5b9af53 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipseBasePreferencePage.java @@ -0,0 +1,208 @@ +package net.sourceforge.phpeclipse; + +import java.util.ArrayList; + +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.jface.preference.DirectoryFieldEditor; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.preference.RadioGroupFieldEditor; +import org.eclipse.jface.preference.StringFieldEditor; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Group; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +import net.sourceforge.phpeclipse.preferences.PHPPreferencesMessages; + +public class PHPEclipseBasePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { + + private SelectionListener SelectionListener; + private ModifyListener ModifyListener; + private ModifyListener TextModifyListener; + + private ArrayList CheckBoxes = new ArrayList(); + private ArrayList ComboBoxes = new ArrayList(); + private ArrayList TextBoxes = new ArrayList(); + private ArrayList RadioButtons = new ArrayList(); + + StringFieldEditor localHostSFE; + DirectoryFieldEditor documentRootDFE; + BooleanFieldEditor externalBrowserBFE; + StringFieldEditor externalBrowserSFE; + StringFieldEditor apacheStartSFE; + StringFieldEditor apacheStopSFE; + StringFieldEditor apacheRestartSFE; + StringFieldEditor mySQLCommandSFE; + RadioGroupFieldEditor chooseParser; + BooleanFieldEditor parseOnSave; + + public PHPEclipseBasePreferencePage() { + super(); + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + setDescription(PHPPreferencesMessages.getString("PHPBasePreferencePage.description")); //$NON-NLS-1$ + } + public void init(IWorkbench workbench) { + } + protected void performDefaults() { + localHostSFE.loadDefault(); + documentRootDFE.loadDefault(); + externalBrowserBFE.loadDefault(); + externalBrowserSFE.loadDefault(); + apacheStartSFE.loadDefault(); + apacheStopSFE.loadDefault(); + apacheRestartSFE.loadDefault(); + mySQLCommandSFE.loadDefault(); + chooseParser.loadDefault(); + parseOnSave.loadDefault(); + super.performDefaults(); + } + + public boolean performOk() { + localHostSFE.store(); + documentRootDFE.store(); + externalBrowserBFE.store(); + externalBrowserSFE.store(); + apacheStartSFE.store(); + apacheStopSFE.store(); + apacheRestartSFE.store(); + mySQLCommandSFE.store(); + chooseParser.store(); + parseOnSave.store(); + return super.performOk(); + } + + protected Control createContents(Composite parent) { + initializeDialogUnits(parent); + final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + Composite composite = new Composite(parent, SWT.LEFT); + composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + composite.setLayout(new GridLayout()); + //Create Websettings + Composite webSettingsComposite = new Composite(composite, SWT.NONE); + webSettingsComposite.setLayout(new GridLayout()); + webSettingsComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Group webSettingsGroup = new Group(webSettingsComposite, SWT.NONE); + webSettingsGroup.setText(PHPPreferencesMessages.getString("PHPBasePreferencePage.websettingsGroup")); + webSettingsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + webSettingsGroup.setLayout(new GridLayout()); + localHostSFE = + new StringFieldEditor( + IPreferenceConstants.LOCALHOST_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.websettingsGroup.localhost"), + webSettingsGroup); + localHostSFE.setPreferencePage(this); + localHostSFE.setPreferenceStore(getPreferenceStore()); + localHostSFE.load(); + documentRootDFE = + new DirectoryFieldEditor( + IPreferenceConstants.DOCUMENTROOT_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.websettingsGroup.docroot"), + webSettingsGroup); + documentRootDFE.setPreferencePage(this); + documentRootDFE.setPreferenceStore(getPreferenceStore()); + documentRootDFE.load(); + externalBrowserBFE = + new BooleanFieldEditor( + IPreferenceConstants.USE_EXTERNAL_BROWSER_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.websettingsGroup.useexternal"), + webSettingsGroup); + externalBrowserBFE.setPreferencePage(this); + externalBrowserBFE.setPreferenceStore(getPreferenceStore()); + externalBrowserBFE.load(); + externalBrowserSFE = + new StringFieldEditor( + IPreferenceConstants.EXTERNAL_BROWSER_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.websettingsGroup.browser"), + webSettingsGroup); + externalBrowserSFE.setPreferencePage(this); + externalBrowserSFE.setPreferenceStore(getPreferenceStore()); + externalBrowserSFE.load(); + + //Create apache + Composite apacheSettingsComposite = new Composite(composite, SWT.NULL); + apacheSettingsComposite.setLayout(new GridLayout()); + apacheSettingsComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Group apacheSettingsGroup = new Group(apacheSettingsComposite, SWT.NONE); + apacheSettingsGroup.setText(PHPPreferencesMessages.getString("PHPBasePreferencePage.apacheGroup")); + apacheSettingsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + apacheSettingsGroup.setLayout(new GridLayout()); + apacheStartSFE = + new StringFieldEditor( + IPreferenceConstants.APACHE_START_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.apacheGroup.start"), + apacheSettingsGroup); + apacheStartSFE.setPreferencePage(this); + apacheStartSFE.setPreferenceStore(getPreferenceStore()); + apacheStartSFE.load(); + apacheStopSFE = + new StringFieldEditor( + IPreferenceConstants.APACHE_STOP_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.apacheGroup.stop"), + apacheSettingsGroup); + apacheStopSFE.setPreferencePage(this); + apacheStopSFE.setPreferenceStore(getPreferenceStore()); + apacheStopSFE.load(); + apacheRestartSFE = + new StringFieldEditor( + IPreferenceConstants.APACHE_RESTART_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.apacheGroup.restart"), + apacheSettingsGroup); + apacheRestartSFE.setPreferencePage(this); + apacheRestartSFE.setPreferenceStore(getPreferenceStore()); + apacheRestartSFE.load(); + + //Create mySQL + Composite mySQLSettingsComposite = new Composite(composite, SWT.NULL); + mySQLSettingsComposite.setLayout(new GridLayout()); + mySQLSettingsComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Group mySQLSettingsGroup = new Group(mySQLSettingsComposite, SWT.NONE); + mySQLSettingsGroup.setText(PHPPreferencesMessages.getString("PHPBasePreferencePage.mySQLGroup")); + mySQLSettingsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + mySQLSettingsGroup.setLayout(new GridLayout()); + mySQLCommandSFE = + new StringFieldEditor( + IPreferenceConstants.MYSQL_PREF, + PHPPreferencesMessages.getString("PHPBasePreferencePage.mySQLGroup.command"), + mySQLSettingsGroup); + mySQLCommandSFE.setPreferencePage(this); + mySQLCommandSFE.setPreferenceStore(getPreferenceStore()); + mySQLCommandSFE.load(); + + //Create parser settings composite + Composite parserSettingsComposite = new Composite(composite, SWT.NONE); + parserSettingsComposite.setLayout(new GridLayout()); + parserSettingsComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + Group parserSettingsGroup = new Group(parserSettingsComposite, SWT.NONE); + parserSettingsGroup.setText(PHPPreferencesMessages.getString("PHPBasePreferencePage.parsers")); + parserSettingsGroup.setLayout(new GridLayout()); + parserSettingsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + chooseParser = + new RadioGroupFieldEditor( + IPreferenceConstants.PHP_PARSER_DEFAULT, + PHPPreferencesMessages.getString("PHPBasePreferencePage.parsers.choose"), + 1, + new String[][] { + { PHPPreferencesMessages.getString("PHPBasePreferencePage.parsers.internal"), IPreferenceConstants.PHP_INTERNAL_PARSER }, + { + PHPPreferencesMessages.getString("PHPBasePreferencePage.parsers.external"), IPreferenceConstants.PHP_EXTERNAL_PARSER } + }, parserSettingsGroup); + chooseParser.setPreferencePage(this); + chooseParser.setPreferenceStore(getPreferenceStore()); + chooseParser.load(); + parseOnSave = new BooleanFieldEditor(PHPeclipsePlugin.PHP_PARSE_ON_SAVE, "&Parse automatically on save", parserSettingsGroup); + parseOnSave.setPreferencePage(this); + parseOnSave.setPreferenceStore(getPreferenceStore()); + parseOnSave.load(); + + return composite; + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipsePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipsePreferencePage.java deleted file mode 100644 index 8a047f1..0000000 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPEclipsePreferencePage.java +++ /dev/null @@ -1,115 +0,0 @@ -/********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Klaus Hartlage - www.eclipseproject.de -**********************************************************************/ -package net.sourceforge.phpeclipse; - -import org.eclipse.jface.preference.BooleanFieldEditor; -import org.eclipse.jface.preference.DirectoryFieldEditor; -import org.eclipse.jface.preference.FieldEditorPreferencePage; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.RadioGroupFieldEditor; -import org.eclipse.jface.preference.StringFieldEditor; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; - -/** - * - * @author khartlage - */ -public class PHPEclipsePreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { - - public PHPEclipsePreferencePage() { - super(FieldEditorPreferencePage.GRID); - //Initialize the preference store we wish to use - setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - } - - protected void createFieldEditors() { - final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - - StringFieldEditor localhost = new StringFieldEditor(PHPeclipsePlugin.LOCALHOST_PREF, "&Localhost:", 60, getFieldEditorParent()); - - DirectoryFieldEditor documentRoot = - new DirectoryFieldEditor(PHPeclipsePlugin.DOCUMENTROOT_PREF, "&DocumentRoot:", getFieldEditorParent()); - - BooleanFieldEditor useExternalBrowser = - new BooleanFieldEditor(PHPeclipsePlugin.USE_EXTERNAL_BROWSER_PREF, "&Use External Browser", getFieldEditorParent()); - - StringFieldEditor externalBrowser = - new StringFieldEditor(PHPeclipsePlugin.EXTERNAL_BROWSER_PREF, "&External Browser command:", 60, getFieldEditorParent()); - - StringFieldEditor startMySQL = - new StringFieldEditor(PHPeclipsePlugin.MYSQL_PREF, "&MySQL command:", 60, getFieldEditorParent()); - - StringFieldEditor startApache = - new StringFieldEditor(PHPeclipsePlugin.APACHE_START_PREF, "Start &Apache command:", 60, getFieldEditorParent()); - - StringFieldEditor stopApache = - new StringFieldEditor(PHPeclipsePlugin.APACHE_STOP_PREF, "&Stop Apache command:", 60, getFieldEditorParent()); - - StringFieldEditor restartApache = - new StringFieldEditor(PHPeclipsePlugin.APACHE_RESTART_PREF, "&Restart Apache command:", 60, getFieldEditorParent()); - - StringFieldEditor externalParser = - new StringFieldEditor(PHPeclipsePlugin.EXTERNAL_PARSER_PREF, "&External Parser command:", 60, getFieldEditorParent()); - - - RadioGroupFieldEditor chooseParser = new RadioGroupFieldEditor( - IPreferenceConstants.PHP_PARSER_DEFAULT, - "Choose PHP parser", - 1, - new String[][] { - {"Internal parser", - IPreferenceConstants.PHP_INTERNAL_PARSER - }, - {"External parser", - IPreferenceConstants.PHP_EXTERNAL_PARSER - } - }, - this.getFieldEditorParent()); - - BooleanFieldEditor parseOnSave = - new BooleanFieldEditor(PHPeclipsePlugin.PHP_PARSE_ON_SAVE, "&Parse automatically on save", getFieldEditorParent()); - - BooleanFieldEditor outlineShowClass = - new BooleanFieldEditor(PHPeclipsePlugin.PHP_OUTLINE_CLASS, "Show classes in outline", getFieldEditorParent()); - BooleanFieldEditor outlineShowFunc = - new BooleanFieldEditor(PHPeclipsePlugin.PHP_OUTLINE_FUNC, "Show functions in outline", getFieldEditorParent()); - BooleanFieldEditor outlineShowVar = - new BooleanFieldEditor(PHPeclipsePlugin.PHP_OUTLINE_VAR, "Show variables in outline", getFieldEditorParent()); - - - addField(localhost); - addField(documentRoot); - addField(useExternalBrowser); - addField(externalBrowser); - addField(startMySQL); - addField(startApache); - - addField(stopApache); - addField(restartApache); - - addField(externalParser); - - addField(chooseParser); - addField(parseOnSave); - addField(outlineShowClass) ; - addField(outlineShowFunc); - addField(outlineShowVar); - } - - /** - * @see IWorkbenchPreferencePage#init - */ - public void init(IWorkbench workbench) { - } - -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java new file mode 100644 index 0000000..fed2faf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java @@ -0,0 +1,76 @@ +package net.sourceforge.phpeclipse; + +import java.util.ArrayList; + +import net.sourceforge.phpeclipse.preferences.PHPPreferencesMessages; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +public class PHPLanguagePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { + private ArrayList RadioButtons = new ArrayList(); + + protected Control createContents(Composite parent) { + Composite lingoComposite= new Composite(parent, SWT.NULL); + lingoComposite.setLayout(new GridLayout()); + Group lingoGroup= new Group(lingoComposite, SWT.NONE); + lingoGroup.setText(PHPPreferencesMessages.getString("PHPLanguagePreferencePage.preflingo")); + lingoGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + lingoGroup.setLayout(new GridLayout()); + Label lg = new Label(lingoGroup, SWT.WRAP); + lg.setText(PHPPreferencesMessages.getString("PHPLanguagePreferencePage.choose")); + addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.english"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_EN_GB); //$NON-NLS-1$ + addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.german"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_DE); //$NON-NLS-1$ + addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.french"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_FR); //$NON-NLS-1$ + return lingoComposite; + } + public void init(IWorkbench arg0) { + } + private Button addRadioButton(Composite parent, String label, String key, String value) { + GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); + Button button= new Button(parent, SWT.RADIO); + button.setText(label); + button.setData(new String[] { key, value }); + button.setLayoutData(gd); + button.setSelection(value.equals(PHPeclipsePlugin.getDefault().getPreferenceStore().getString(key))); + RadioButtons.add(button); + return button; + } + + protected void performDefaults() { + IPreferenceStore store= getPreferenceStore(); + for (int i= 0; i < RadioButtons.size(); i++) { + Button button= (Button) RadioButtons.get(i); + String[] info= (String[]) button.getData(); + button.setSelection(info[1].equals(store.getDefaultString(info[0]))); + } + super.performDefaults(); + } + + public boolean performOk() { + IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); + for (int i= 0; i < RadioButtons.size(); i++) { + Button button= (Button) RadioButtons.get(i); + if (button.getSelection()) { + String[] info= (String[]) button.getData(); + store.setValue(info[0], info[1]); + } + } + PHPeclipsePlugin.getDefault().savePluginPreferences(); + PHPPreferencesMessages.setResourceBundle( + PHPeclipsePlugin.getDefault().getPreferenceStore().getString(IPreferenceConstants.RESOURCE_BUNDLE)); + + return super.performOk(); + } +} + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPOutlinePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPOutlinePreferencePage.java new file mode 100644 index 0000000..0366a7c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPOutlinePreferencePage.java @@ -0,0 +1,56 @@ +/********************************************************************** +Copyright (c) 2000, 2002 IBM Corp. and others. +All rights reserved. This program and the accompanying materials +are made available under the terms of the Common Public License v1.0 +which accompanies this distribution, and is available at +http://www.eclipse.org/legal/cpl-v10.html + +Contributors: + IBM Corporation - Initial implementation + Klaus Hartlage - www.eclipseproject.de +**********************************************************************/ +package net.sourceforge.phpeclipse; + +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.jface.preference.DirectoryFieldEditor; +import org.eclipse.jface.preference.FieldEditorPreferencePage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.RadioGroupFieldEditor; +import org.eclipse.jface.preference.StringFieldEditor; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +/** + * + * @author khartlage + */ +public class PHPOutlinePreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { + + public PHPOutlinePreferencePage() { + super(FieldEditorPreferencePage.GRID); + //Initialize the preference store we wish to use + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + } + + protected void createFieldEditors() { + final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + + BooleanFieldEditor outlineShowClass = + new BooleanFieldEditor(PHPeclipsePlugin.PHP_OUTLINE_CLASS, "Show classes in outline", getFieldEditorParent()); + BooleanFieldEditor outlineShowFunc = + new BooleanFieldEditor(PHPeclipsePlugin.PHP_OUTLINE_FUNC, "Show functions in outline", getFieldEditorParent()); + BooleanFieldEditor outlineShowVar = + new BooleanFieldEditor(PHPeclipsePlugin.PHP_OUTLINE_VAR, "Show variables in outline", getFieldEditorParent()); + + addField(outlineShowClass); + addField(outlineShowFunc); + addField(outlineShowVar); + } + + /** + * @see IWorkbenchPreferencePage#init + */ + public void init(IWorkbench workbench) { + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java new file mode 100644 index 0000000..22b06ff --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java @@ -0,0 +1,464 @@ +package net.sourceforge.phpeclipse; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import net.sourceforge.phpeclipse.preferences.ColorEditor; +import net.sourceforge.phpeclipse.preferences.OverlayPreferenceStore; +import net.sourceforge.phpeclipse.preferences.PHPPreferencesMessages; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.jface.preference.FileFieldEditor; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceConverter; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.jface.text.source.ISourceViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; + +/* + * The preference page for setting the PHP Editor options. + */ +public class PHPSyntaxEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { + + public final OverlayPreferenceStore.OverlayKey[] Keys = + new OverlayPreferenceStore.OverlayKey[] { + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_MULTILINE_COMMENT), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_MULTILINE_COMMENT_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_MULTILINE_COMMENT_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_MULTILINE_COMMENT_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_SINGLELINE_COMMENT), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_SINGLELINE_COMMENT_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_SINGLELINE_COMMENT_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_SINGLELINE_COMMENT_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_KEYWORD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_KEYWORD_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_KEYWORD_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_KEYWORD_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_VARIABLE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_VARIABLE_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_VARIABLE_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_VARIABLE_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_TYPE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_TYPE_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_TYPE_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_TYPE_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_CONSTANT), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_CONSTANT_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_CONSTANT_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_CONSTANT_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_FUNCTIONNAME), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_FUNCTIONNAME_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_FUNCTIONNAME_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_FUNCTIONNAME_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_STRING), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_STRING_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_STRING_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_STRING_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_DEFAULT), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_DEFAULT_BOLD), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_DEFAULT_ITALIC), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_DEFAULT_UNDERLINE), + new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_USERDEF_XMLFILE)}; + + private final String[][] SyntaxColorListModel = + new String[][] { + { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.multiLineComment"), + IPreferenceConstants.PHP_MULTILINE_COMMENT }, + { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.singleLineComment"), + IPreferenceConstants.PHP_SINGLELINE_COMMENT }, + { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.keywords"), IPreferenceConstants.PHP_KEYWORD }, { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.variables"), IPreferenceConstants.PHP_VARIABLE }, { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.types"), IPreferenceConstants.PHP_TYPE }, { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.functions"), IPreferenceConstants.PHP_FUNCTIONNAME }, { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.constants"), IPreferenceConstants.PHP_CONSTANT }, { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.strings"), IPreferenceConstants.PHP_STRING }, { + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.others"), IPreferenceConstants.PHP_DEFAULT } + }; + + private OverlayPreferenceStore OverlayStore; + + private Map ColorButtons = new HashMap(); + private SelectionListener ColorButtonListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + public void widgetSelected(SelectionEvent e) { + ColorEditor editor = (ColorEditor) e.widget.getData(); + PreferenceConverter.setValue(OverlayStore, (String) ColorButtons.get(editor), editor.getColorValue()); + } + }; + + private Map CheckBoxes = new HashMap(); + private SelectionListener CheckBoxListener = new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + } + public void widgetSelected(SelectionEvent e) { + Button button = (Button) e.widget; + OverlayStore.setValue((String) CheckBoxes.get(button), button.getSelection()); + } + }; + + private List SyntaxColorList; + private ColorEditor SyntaxForegroundColorEditor; + private Button BoldCheckBox; + private Button ItalicCheckBox; + private Button UnderlineCheckBox; + private FileFieldEditor userdefPHPSyntaxFileFFE; + + public PHPSyntaxEditorPreferencePage() { + setDescription(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.description")); //$NON-NLS-1$ + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + OverlayStore = new OverlayPreferenceStore(getPreferenceStore(), Keys); + } + + public void init(IWorkbench workbench) { + } + + public void createControl(Composite parent) { + super.createControl(parent); + } + + private void handleSyntaxColorListSelection() { + int i = SyntaxColorList.getSelectionIndex(); + String key = SyntaxColorListModel[i][1]; + RGB rgb = PreferenceConverter.getColor(OverlayStore, key); + SyntaxForegroundColorEditor.setColorValue(rgb); + BoldCheckBox.setSelection(OverlayStore.getBoolean(key + "_bold")); + ItalicCheckBox.setSelection(OverlayStore.getBoolean(key + "_italic")); + UnderlineCheckBox.setSelection(OverlayStore.getBoolean(key + "_underline")); + } + + private Control createSyntaxPage(Composite parent) { + + Composite colorComposite = new Composite(parent, SWT.NULL); + colorComposite.setLayout(new GridLayout()); + + Label label = new Label(colorComposite, SWT.LEFT); + label.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.syntax")); //$NON-NLS-1$ + label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Composite editorComposite = new Composite(colorComposite, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + layout.marginHeight = 0; + layout.marginWidth = 0; + editorComposite.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + editorComposite.setLayoutData(gd); + + SyntaxColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); + gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = convertHeightInCharsToPixels(5); + SyntaxColorList.setLayoutData(gd); + + Composite stylesComposite = new Composite(editorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + + label = new Label(stylesComposite, SWT.LEFT); + label.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.color")); //$NON-NLS-1$ + gd = new GridData(); + gd.horizontalAlignment = GridData.BEGINNING; + label.setLayoutData(gd); + + SyntaxForegroundColorEditor = new ColorEditor(stylesComposite); + Button foregroundColorButton = SyntaxForegroundColorEditor.getButton(); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + foregroundColorButton.setLayoutData(gd); + + BoldCheckBox = new Button(stylesComposite, SWT.CHECK); + BoldCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.bold")); //$NON-NLS-1$ + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + BoldCheckBox.setLayoutData(gd); + + ItalicCheckBox = new Button(stylesComposite, SWT.CHECK); + ItalicCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.italic")); //$NON-NLS-1$ + ItalicCheckBox.setEnabled(false); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + ItalicCheckBox.setLayoutData(gd); + + UnderlineCheckBox = new Button(stylesComposite, SWT.CHECK); + UnderlineCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.underline")); //$NON-NLS-1$ + UnderlineCheckBox.setEnabled(false); + gd = new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalAlignment = GridData.BEGINNING; + gd.horizontalSpan = 2; + UnderlineCheckBox.setLayoutData(gd); + + Composite customSyntaxComposite = new Composite(colorComposite, SWT.NONE); + layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 3; + stylesComposite.setLayout(layout); + stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); + + userdefPHPSyntaxFileFFE = + new FileFieldEditor( + IPreferenceConstants.PHP_USERDEF_XMLFILE, + PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.syntaxdialog"), + colorComposite); + userdefPHPSyntaxFileFFE.setPreferencePage(this); + userdefPHPSyntaxFileFFE.setPreferenceStore(getPreferenceStore()); + userdefPHPSyntaxFileFFE.load(); + + SyntaxColorList.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + public void widgetSelected(SelectionEvent e) { + handleSyntaxColorListSelection(); + } + }); + + foregroundColorButton.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + public void widgetSelected(SelectionEvent e) { + int i = SyntaxColorList.getSelectionIndex(); + String key = SyntaxColorListModel[i][1]; + + PreferenceConverter.setValue(OverlayStore, key, SyntaxForegroundColorEditor.getColorValue()); + } + }); + BoldCheckBox.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + public void widgetSelected(SelectionEvent e) { + int i = SyntaxColorList.getSelectionIndex(); + String key = SyntaxColorListModel[i][1]; + OverlayStore.setValue(key + "_bold", BoldCheckBox.getSelection()); + } + }); + + ItalicCheckBox.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + public void widgetSelected(SelectionEvent e) { + int i = SyntaxColorList.getSelectionIndex(); + String key = SyntaxColorListModel[i][1]; + OverlayStore.setValue(key + "_italic", ItalicCheckBox.getSelection()); + } + }); + + UnderlineCheckBox.addSelectionListener(new SelectionListener() { + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + public void widgetSelected(SelectionEvent e) { + int i = SyntaxColorList.getSelectionIndex(); + String key = SyntaxColorListModel[i][1]; + OverlayStore.setValue(key + "_underline", UnderlineCheckBox.getSelection()); + } + }); + return colorComposite; + } + + private void initializeViewerColors(ISourceViewer viewer) { + + IPreferenceStore store = OverlayStore; + if (store != null) { + + StyledText styledText = viewer.getTextWidget(); + } + } + + private Color createColor(IPreferenceStore store, String key, Display display) { + RGB rgb = null; + if (store.contains(key)) { + if (store.isDefault(key)) + rgb = PreferenceConverter.getDefaultColor(store, key); + else + rgb = PreferenceConverter.getColor(store, key); + if (rgb != null) + return new Color(display, rgb); + } + return null; + } + + private static void setEnabled(Control control, boolean enable) { + control.setEnabled(enable); + if (control instanceof Composite) { + Composite composite = (Composite) control; + Control[] children = composite.getChildren(); + for (int i = 0; i < children.length; i++) + setEnabled(children[i], enable); + } + } + + private static void indent(Control control) { + GridData gridData = new GridData(); + gridData.horizontalIndent = 20; + control.setLayoutData(gridData); + } + + private static void createDependency(final Button master, final Control slave) { + indent(slave); + master.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent e) { + slave.setEnabled(master.getSelection()); + } + + public void widgetDefaultSelected(SelectionEvent e) { + } + }); + } + + protected Control createContents(Composite parent) { + OverlayStore.load(); + OverlayStore.start(); + //Create overall composite + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + composite.setLayout(layout); + Composite syntaxComposite = new Composite(composite, SWT.NULL); + syntaxComposite.setLayout(new GridLayout()); + layout = new GridLayout(); + layout.numColumns = 3; + Group syntaxGroup = new Group(syntaxComposite, SWT.NONE); + syntaxGroup.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.foreground")); + syntaxGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + syntaxGroup.setLayout(layout); + createSyntaxPage(syntaxGroup); + + initialize(); + return composite; + } + + private void initialize() { + initializeFields(); + for (int i = 0; i < SyntaxColorListModel.length; i++) + SyntaxColorList.add(SyntaxColorListModel[i][0]); + SyntaxColorList.getDisplay().asyncExec(new Runnable() { + public void run() { + if (SyntaxColorList != null && !SyntaxColorList.isDisposed()) { + SyntaxColorList.select(0); + handleSyntaxColorListSelection(); + } + } + }); + } + + private void initializeFields() { + + Iterator e = ColorButtons.keySet().iterator(); + while (e.hasNext()) { + ColorEditor c = (ColorEditor) e.next(); + String key = (String) ColorButtons.get(c); + RGB rgb = PreferenceConverter.getColor(OverlayStore, key); + c.setColorValue(rgb); + } + + e = CheckBoxes.keySet().iterator(); + while (e.hasNext()) { + Button b = (Button) e.next(); + String key = (String) CheckBoxes.get(b); + b.setSelection(OverlayStore.getBoolean(key)); + } + } + + public boolean performOk() { + OverlayStore.propagate(); + IPreferenceStore store = getPreferenceStore(); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + userdefPHPSyntaxFileFFE.store(); + return true; + } + + protected void performDefaults() { + OverlayStore.loadDefaults(); + initializeFields(); + handleSyntaxColorListSelection(); + userdefPHPSyntaxFileFFE.loadDefault(); + super.performDefaults(); + } + + public void dispose() { + if (OverlayStore != null) { + OverlayStore.stop(); + OverlayStore = null; + } + super.dispose(); + } + + private Control addColorButton(Composite composite, String label, String key, int indentation) { + Label labelControl = new Label(composite, SWT.NONE); + labelControl.setText(label); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + labelControl.setLayoutData(gd); + ColorEditor editor = new ColorEditor(composite); + Button button = editor.getButton(); + button.setData(editor); + gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + button.setLayoutData(gd); + button.addSelectionListener(ColorButtonListener); + ColorButtons.put(editor, key); + return composite; + } + + private Button addCheckBox(Composite parent, String label, String key, int indentation) { + Button checkBox = new Button(parent, SWT.CHECK); + checkBox.setText(label); + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); + gd.horizontalIndent = indentation; + gd.horizontalSpan = 2; + checkBox.setLayoutData(gd); + checkBox.addSelectionListener(CheckBoxListener); + CheckBoxes.put(checkBox, key); + return checkBox; + } + + private void updateStatus(IStatus status) { + } + + /** + * @deprecated Inline to avoid reference to preference page + */ + public static boolean indicateQuixFixableProblems() { + // return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); + return false; + } + + /** + * @deprecated Inline to avoid reference to preference page + */ + static public boolean synchronizeOutlineOnCursorMove() { + // return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); + return false; + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxPreferencePage.java deleted file mode 100644 index a182244..0000000 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxPreferencePage.java +++ /dev/null @@ -1,64 +0,0 @@ -/********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Klaus Hartlage - www.eclipseproject.de -**********************************************************************/ -package net.sourceforge.phpeclipse; - -import org.eclipse.jface.preference.BooleanFieldEditor; -import org.eclipse.jface.preference.ColorFieldEditor; -import org.eclipse.jface.preference.FieldEditorPreferencePage; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; - -/** - * - * @author khartlage - */ -public class PHPSyntaxPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage, IPreferenceConstants { - - public PHPSyntaxPreferencePage() { - super(FieldEditorPreferencePage.GRID); - //Initialize the preference store we wish to use - setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); - } - - protected void createFieldEditors() { - final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - - BooleanFieldEditor showLineNumbers = - new BooleanFieldEditor(PHPeclipsePlugin.LINE_NUMBER_RULER, "Show line numbers", getFieldEditorParent()); - this.addField(showLineNumbers); - - ColorFieldEditor multilineComment = - new ColorFieldEditor(PHP_MULTILINE_COMMENT, "Multi-line comment:", this.getFieldEditorParent()); - this.addField(multilineComment); - ColorFieldEditor singlelineComment = - new ColorFieldEditor(PHP_SINGLELINE_COMMENT, "Single-line comment:", this.getFieldEditorParent()); - this.addField(singlelineComment); - ColorFieldEditor keyWords = new ColorFieldEditor(PHP_KEYWORD, "Keywords:", this.getFieldEditorParent()); - this.addField(keyWords); - ColorFieldEditor variables = new ColorFieldEditor(PHP_VARIABLE, "Variables:", this.getFieldEditorParent()); - this.addField(variables); - ColorFieldEditor types = new ColorFieldEditor(PHP_FUNCTIONNAME, "Built-in functions:", this.getFieldEditorParent()); - this.addField(types); - ColorFieldEditor strings = new ColorFieldEditor(PHP_STRING, "Strings:", this.getFieldEditorParent()); - this.addField(strings); - ColorFieldEditor others = new ColorFieldEditor(PHP_DEFAULT, "Others:", this.getFieldEditorParent()); - this.addField(others); - } - - /** - * @see IWorkbenchPreferencePage#init - */ - public void init(IWorkbench workbench) { - } - -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java index 41eae55..0cb4ae8 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java @@ -11,16 +11,13 @@ Contributors: **********************************************************************/ package net.sourceforge.phpeclipse; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - import net.sourceforge.phpdt.internal.ui.preferences.TemplatePreferencePage; import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry; import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider; -import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; import net.sourceforge.phpeclipse.resourcesview.PHPElement; import net.sourceforge.phpeclipse.resourcesview.PHPElementAdapterFactory; import net.sourceforge.phpeclipse.resourcesview.ResourceAdapterFactory; + import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; @@ -39,6 +36,9 @@ import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.plugin.AbstractUIPlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr; +import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider; + /** * The main plugin class to be used in the desktop. */ @@ -60,7 +60,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon public static final String PLUGIN_ID = "net.sourceforge.phpeclipse"; //$NON-NLS-1$ public final static String PHP_NATURE_ID = PLUGIN_ID + ".phpnature"; public static final String PHP_RESOURCES_VIEW_ID = PLUGIN_ID + ".resourcesview.ViewPHPResources"; //$NON-NLS-1$ - + //The shared instance. private static PHPeclipsePlugin plugin; //Resource bundle. @@ -100,11 +100,11 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon super(descriptor); plugin = this; setJVM(); -// try { -// resourceBundle = ResourceBundle.getBundle("net.sourceforge.PHPeclipsePluginResources"); -// } catch (MissingResourceException x) { -// resourceBundle = null; -// } + // try { + // resourceBundle = ResourceBundle.getBundle("net.sourceforge.PHPeclipsePluginResources"); + // } catch (MissingResourceException x) { + // resourceBundle = null; + // } } public static ImageDescriptorRegistry getImageDescriptorRegistry() { @@ -113,7 +113,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon private ImageDescriptorRegistry internalGetImageDescriptorRegistry() { if (fImageDescriptorRegistry == null) - fImageDescriptorRegistry= new ImageDescriptorRegistry(); + fImageDescriptorRegistry = new ImageDescriptorRegistry(); return fImageDescriptorRegistry; } // @TODO: refactor this into a better method name ! @@ -174,7 +174,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon } public static IWorkbenchPage getActivePage() { - return getDefault().getActivePage(); + return PHPeclipsePlugin.getActivePage(); } public static IWorkbenchWindow getActiveWorkbenchWindow() { @@ -210,9 +210,10 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon // public static void log(Throwable e) { // log(new Status(IStatus.ERROR, getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$ // } + public static void log(int severity, String message) { - Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null) ; - log(status) ; + Status status = new Status(severity, PLUGIN_ID, IStatus.OK, message, null); + log(status); } public static void log(Throwable e) { log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.ERROR, "PHPeclipsePlugin.internalErrorOccurred", e)); //$NON-NLS-1$ @@ -229,21 +230,21 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon * Returns the string from the plugin's resource bundle, * or 'key' if not found. */ -// public static String getResourceString(String key) { -// ResourceBundle bundle = PHPeclipsePlugin.getDefault().getResourceBundle(); -// try { -// return bundle.getString(key); -// } catch (MissingResourceException e) { -// return key; -// } -// } + // public static String getResourceString(String key) { + // ResourceBundle bundle = PHPeclipsePlugin.getDefault().getResourceBundle(); + // try { + // return bundle.getString(key); + // } catch (MissingResourceException e) { + // return key; + // } + // } /** * Returns the plugin's resource bundle, */ -// public ResourceBundle getResourceBundle() { -// return resourceBundle; -// } + // public ResourceBundle getResourceBundle() { + // return resourceBundle; + // } protected void initializeDefaultPreferences(IPreferenceStore store) { // windows preferences: @@ -258,9 +259,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon } else { store.setDefault(EXTERNAL_BROWSER_PREF, "netscape {0}"); } - store.setDefault(DOCUMENTROOT_PREF, getWorkspace().getRoot().getLocation().toString() ); - // store.setDefault(DOCUMENTROOT_PREF, "c:\\eclipse\\workspace"); // WIN_32 - // store.setDefault(DOCUMENTROOT_PREF, "/eclipse/workspace"); // UNIX + store.setDefault(DOCUMENTROOT_PREF, getWorkspace().getRoot().getLocation().toString()); if ((jvm == WINDOWS_9x) || (jvm == WINDOWS_NT)) { store.setDefault(EXTERNAL_PARSER_PREF, "c:\\apache\\php\\php -l -f {0}"); store.setDefault(MYSQL_PREF, "c:\\apache\\mysql\\bin\\mysqld.exe --standalone"); @@ -273,43 +272,55 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon store.setDefault(APACHE_START_PREF, "/apache/apache -c \"DocumentRoot \"{0}\"\""); store.setDefault(APACHE_STOP_PREF, "/apache/apache.exe -k shutdown"); store.setDefault(APACHE_RESTART_PREF, "/apache/apache -k restart"); - + } store.setDefault(PHP_PARSER_DEFAULT, PHP_EXTERNAL_PARSER); store.setDefault(PHP_INTERNAL_PARSER, "false"); store.setDefault(PHP_EXTERNAL_PARSER, "true"); - + store.setDefault(PHP_PARSE_ON_SAVE, "true"); - + // show line numbers: store.setDefault(LINE_NUMBER_RULER, "false"); store.setDefault(FORMATTER_TAB_SIZE, "4"); - + // php syntax highlighting + store.setDefault(PHP_USERDEF_XMLFILE, ""); //assume there is none chooA + PreferenceConverter.setDefault(store, PHP_MULTILINE_COMMENT, PHPColorProvider.MULTI_LINE_COMMENT); PreferenceConverter.setDefault(store, PHP_SINGLELINE_COMMENT, PHPColorProvider.SINGLE_LINE_COMMENT); PreferenceConverter.setDefault(store, PHP_KEYWORD, PHPColorProvider.KEYWORD); PreferenceConverter.setDefault(store, PHP_VARIABLE, PHPColorProvider.VARIABLE); PreferenceConverter.setDefault(store, PHP_FUNCTIONNAME, PHPColorProvider.FUNCTION_NAME); - PreferenceConverter.setDefault(store, PHP_STRING, PHPColorProvider.STRING); + PreferenceConverter.setDefault(store, PHP_CONSTANT, PHPColorProvider.CONSTANT); + PreferenceConverter.setDefault(store, PHP_TYPE, PHPColorProvider.TYPE); + PreferenceConverter.setDefault(store, PHP_STRING, PHPColorProvider.STRING); PreferenceConverter.setDefault(store, PHP_DEFAULT, PHPColorProvider.DEFAULT); + PreferenceConverter.setDefault(store, PHP_EDITOR_BACKGROUND, PHPColorProvider.BACKGROUND); PreferenceConverter.setDefault(store, LINKED_POSITION_COLOR, PHPColorProvider.LINKED_POSITION_COLOR); PreferenceConverter.setDefault(store, LINE_NUMBER_COLOR, PHPColorProvider.LINE_NUMBER_COLOR); - store.setDefault(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, "true"); //$NON-NLS-1$ + store.setDefault(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, "true"); PreferenceConverter.setDefault(store, PREFERENCE_COLOR_BACKGROUND, PHPColorProvider.BACKGROUND_COLOR); + //language stuff + store.setDefault(RESOURCE_BUNDLE, LANGUAGE_DEFAULT); + store.setDefault(RESOURCE_BUNDLE_EN_GB, "true"); + store.setDefault(RESOURCE_BUNDLE_DE, "false"); + store.setDefault(RESOURCE_BUNDLE_FR, "false"); + store.setDefault(PHP_OUTLINE_CLASS, "true"); //$NON-NLS-1$ store.setDefault(PHP_OUTLINE_FUNC, "true"); //$NON-NLS-1$ store.setDefault(PHP_OUTLINE_VAR, "true"); //$NON-NLS-1$ - TemplatePreferencePage.initDefaults(store); + TemplatePreferencePage.initDefaults(store); + new PHPSyntaxRdr(); //this will initialize the static fields in the syntaxrdr class } - - public void startup() throws CoreException { + + public void startup() throws CoreException { super.startup(); - IAdapterManager manager= Platform.getAdapterManager(); + IAdapterManager manager = Platform.getAdapterManager(); manager.registerAdapters(new PHPElementAdapterFactory(), PHPElement.class); manager.registerAdapters(new ResourceAdapterFactory(), IResource.class); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_DE.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_DE.properties new file mode 100644 index 0000000..c837737 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_DE.properties @@ -0,0 +1,65 @@ +######################################### +# PHPProjectLibraryPage +######################################### + +PHPProjectLibraryPage.elementNotIProject=FEHLER: Element ist kein IProject +PHPProjectLibraryPage.project=Projekt +PHPProjectLibraryPage.tabName=Projekte + + +######################################### +# Property Pages +######################################### + +PHPProjectPropertyPage.phpProjectClosed=Das ausgewählte Projekt ist ein PHP Projekt, aber es ist geschlossen. +PHPProjectPropertyPage.performOkExceptionDialogTitle=Kann nicht sichern +PHPProjectPropertyPage.performOkExceptionDialogMessage=FEHLER: Kann die Projekt Eigenschaften nicht sichern + +######################################### +# Preference Pages +######################################### +PHPBasePreferencePage.description=PHP Voreinstellungen +PHPBasePreferencePage.websettingsGroup=Webserver Einstellungen +PHPBasePreferencePage.websettingsGroup.localhost=Localhost +PHPBasePreferencePage.websettingsGroup.docroot=DocumentRoot +PHPBasePreferencePage.websettingsGroup.browser=Externes Browser Kommando +PHPBasePreferencePage.websettingsGroup.useexternal=Benutze externen Browser +PHPBasePreferencePage.apacheGroup=Apache Einstellungen +PHPBasePreferencePage.apacheGroup.start=Start Apache +PHPBasePreferencePage.apacheGroup.stop=Stop Apache +PHPBasePreferencePage.apacheGroup.restart=Restart Apache +PHPBasePreferencePage.mySQLGroup=MySQL Einstellungen +PHPBasePreferencePage.mySQLGroup.command=MySQL Kommando +PHPBasePreferencePage.parsers=Parser Einstellungen +PHPBasePreferencePage.parsers.pos=Parse beim Sichern +PHPBasePreferencePage.parsers.external=Externer Parser +PHPBasePreferencePage.parsers.internal=Interner Parser +PHPBasePreferencePage.parsers.choose=PHP Parser auswählen + +PHPEditorSyntaxPreferencePage.description:PHP Editor Preferences +PHPEditorSyntaxPreferencePage.foreground:Foreground settings +PHPEditorSyntaxPreferencePage.syntax:Syntax highlighting +PHPEditorSyntaxPreferencePage.color:Colour +PHPEditorSyntaxPreferencePage.bold:Bold +PHPEditorSyntaxPreferencePage.italic:Italic +PHPEditorSyntaxPreferencePage.underline:Underline +PHPEditorSyntaxPreferencePage.multiLineComment=Multi-line comment +PHPEditorSyntaxPreferencePage.singleLineComment=Single-line comment +PHPEditorSyntaxPreferencePage.keywords=Keywords +PHPEditorSyntaxPreferencePage.variables=Variables +PHPEditorSyntaxPreferencePage.types=Types +PHPEditorSyntaxPreferencePage.functions=Functions +PHPEditorSyntaxPreferencePage.constants=Constants +PHPEditorSyntaxPreferencePage.strings=Strings +PHPEditorSyntaxPreferencePage.others=Others +PHPEditorSyntaxPreferencePage.syntaxdialog=Custom PHP Syntax File: +PHPEditorSyntaxPreferencePage.browse=Browse.. +PHPEditorSyntaxPreferencePage.textfont=Text font + +PHPLanguagePreferencePage.description=PHP Editor Language +PHPLanguagePreferencePage.preflingo=PHP Language Preference +PHPLanguagePreferencePage.choose=Choose Language +PHPLanguagePreferencePage.english=Englisch +PHPLanguagePreferencePage.german=Deutsch +PHPLanguagePreferencePage.french=Frensch + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties new file mode 100644 index 0000000..2963607 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties @@ -0,0 +1,65 @@ +######################################### +# PHPProjectLibraryPage +######################################### + +PHPProjectLibraryPage.elementNotIProject=ERROR: Element not IProject +PHPProjectLibraryPage.project=Project +PHPProjectLibraryPage.tabName=Projects + + +######################################### +# Property Pages +######################################### + +PHPProjectPropertyPage.phpProjectClosed=The project selected is a PHP project, but is closed. +PHPProjectPropertyPage.performOkExceptionDialogTitle=Unable to save +PHPProjectPropertyPage.performOkExceptionDialogMessage=ERROR: Unable to save project properties. + +######################################### +# Preference Pages +######################################### +PHPBasePreferencePage.description=PHP Preferences +PHPBasePreferencePage.websettingsGroup=Webserver Settings +PHPBasePreferencePage.websettingsGroup.localhost=Localhost +PHPBasePreferencePage.websettingsGroup.docroot=DocumentRoot +PHPBasePreferencePage.websettingsGroup.browser=External browser command +PHPBasePreferencePage.websettingsGroup.useexternal=Use external browser +PHPBasePreferencePage.apacheGroup=Apache Settings +PHPBasePreferencePage.apacheGroup.start=Start Apache +PHPBasePreferencePage.apacheGroup.stop=Stop Apache +PHPBasePreferencePage.apacheGroup.restart=Restart Apache +PHPBasePreferencePage.mySQLGroup=MySQL Settings +PHPBasePreferencePage.mySQLGroup.command=MySQL command +PHPBasePreferencePage.parsers=Parsing settings +PHPBasePreferencePage.parsers.pos=Parse on save +PHPBasePreferencePage.parsers.external=External +PHPBasePreferencePage.parsers.internal=Internal +PHPBasePreferencePage.parsers.choose=Choose PHP Parser + +PHPEditorSyntaxPreferencePage.description:PHP Editor Preferences +PHPEditorSyntaxPreferencePage.foreground:Foreground settings +PHPEditorSyntaxPreferencePage.syntax:Syntax highlighting +PHPEditorSyntaxPreferencePage.color:Colour +PHPEditorSyntaxPreferencePage.bold:Bold +PHPEditorSyntaxPreferencePage.italic:Italic +PHPEditorSyntaxPreferencePage.underline:Underline +PHPEditorSyntaxPreferencePage.multiLineComment=Multi-line comment +PHPEditorSyntaxPreferencePage.singleLineComment=Single-line comment +PHPEditorSyntaxPreferencePage.keywords=Keywords +PHPEditorSyntaxPreferencePage.variables=Variables +PHPEditorSyntaxPreferencePage.types=Types +PHPEditorSyntaxPreferencePage.functions=Functions +PHPEditorSyntaxPreferencePage.constants=Constants +PHPEditorSyntaxPreferencePage.strings=Strings +PHPEditorSyntaxPreferencePage.others=Others +PHPEditorSyntaxPreferencePage.syntaxdialog=Custom PHP Syntax File: +PHPEditorSyntaxPreferencePage.browse=Browse.. +PHPEditorSyntaxPreferencePage.textfont=Text font + +PHPLanguagePreferencePage.description=PHP Editor Language +PHPLanguagePreferencePage.preflingo=PHP Language Preference +PHPLanguagePreferencePage.choose=Choose Language +PHPLanguagePreferencePage.english=Anglase +PHPLanguagePreferencePage.german=Deutsch +PHPLanguagePreferencePage.french=Francais + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_en_GB.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_en_GB.properties new file mode 100644 index 0000000..b007252 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_en_GB.properties @@ -0,0 +1,64 @@ +######################################### +# PHPProjectLibraryPage +######################################### + +PHPProjectLibraryPage.elementNotIProject=ERROR: Element not IProject +PHPProjectLibraryPage.project=Project +PHPProjectLibraryPage.tabName=Projects + + +######################################### +# Property Pages +######################################### + +PHPProjectPropertyPage.phpProjectClosed=The project selected is a PHP project, but is closed. +PHPProjectPropertyPage.performOkExceptionDialogTitle=Unable to save +PHPProjectPropertyPage.performOkExceptionDialogMessage=ERROR: Unable to save project properties. + +######################################### +# Preference Pages +######################################### +PHPBasePreferencePage.description=PHP Preferences +PHPBasePreferencePage.websettingsGroup=Webserver Settings +PHPBasePreferencePage.websettingsGroup.localhost=Localhost +PHPBasePreferencePage.websettingsGroup.docroot=DocumentRoot +PHPBasePreferencePage.websettingsGroup.browser=External browser command +PHPBasePreferencePage.websettingsGroup.useexternal=Use external browser +PHPBasePreferencePage.apacheGroup=Apache Settings +PHPBasePreferencePage.apacheGroup.start=Start Apache +PHPBasePreferencePage.apacheGroup.stop=Stop Apache +PHPBasePreferencePage.apacheGroup.restart=Restart Apache +PHPBasePreferencePage.mySQLGroup=MySQL Settings +PHPBasePreferencePage.mySQLGroup.command=MySQL command +PHPBasePreferencePage.parsers=Parsing settings +PHPBasePreferencePage.parsers.pos=Parse on save +PHPBasePreferencePage.parsers.external=External +PHPBasePreferencePage.parsers.internal=Internal +PHPBasePreferencePage.parsers.choose=Choose PHP Parser + +PHPEditorSyntaxPreferencePage.description:PHP Editor Preferences +PHPEditorSyntaxPreferencePage.foreground:Foreground settings +PHPEditorSyntaxPreferencePage.syntax:Syntax highlighting +PHPEditorSyntaxPreferencePage.color:Colour +PHPEditorSyntaxPreferencePage.bold:Bold +PHPEditorSyntaxPreferencePage.italic:Italic +PHPEditorSyntaxPreferencePage.underline:Underline +PHPEditorSyntaxPreferencePage.multiLineComment=Multi-line comment +PHPEditorSyntaxPreferencePage.singleLineComment=Single-line comment +PHPEditorSyntaxPreferencePage.keywords=Keywords +PHPEditorSyntaxPreferencePage.variables=Variables +PHPEditorSyntaxPreferencePage.types=Types +PHPEditorSyntaxPreferencePage.functions=Functions +PHPEditorSyntaxPreferencePage.constants=Constants +PHPEditorSyntaxPreferencePage.strings=Strings +PHPEditorSyntaxPreferencePage.others=Others +PHPEditorSyntaxPreferencePage.syntaxdialog=Custom PHP Syntax File: +PHPEditorSyntaxPreferencePage.browse=Browse.. +PHPEditorSyntaxPreferencePage.textfont=Text font + +PHPLanguagePreferencePage.description=PHP Editor Language +PHPLanguagePreferencePage.preflingo=PHP Language Preference +PHPLanguagePreferencePage.choose=Choose Language +PHPLanguagePreferencePage.english=English +PHPLanguagePreferencePage.german=German +PHPLanguagePreferencePage.french=French diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java new file mode 100644 index 0000000..fc456a4 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java @@ -0,0 +1,276 @@ +package net.sourceforge.phpeclipse.phpeditor; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.util.Vector; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.Serializer; +import org.apache.xml.serialize.SerializerFactory; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jface.preference.IPreferenceStore; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; +import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; +import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword; +import net.sourceforge.phpeclipse.phpeditor.php.PHPType; + +/** + * PHPSyntaxRdr reads PHP specifics from an XML file (eg. keywords) + */ + +public class PHPSyntaxRdr { + private static final String PHPDEFAULT_FILE = "default-phpsyntax.xml"; //$NON-NLS-1$ + private static final String PHPSYNTAX_FILE = "phpsyntax.xml"; //$NON-NLS-1$ + private static final String USERSYNTAX_FILE = "usersyntax.xml"; //$NON-NLS-1$ + private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; //$NON-NLS-1$ + private static final String PHPSYNTAX_TAG = "phpsyntax"; + private static final String KEYWORD_ATTR = "keyword"; + private static final String TYPE_ATTR = "type"; + private static final String CONSTANT_ATTR = "constant"; + private static final String FN_ATTR = "function"; + private static final String DESCRIPTION = "description"; + private static final String USAGE_ATTR = "usage"; + private static final String TOKENVAL_ATTR = "tokenval"; + private static IPreferenceStore store; + private static boolean hasXMLFileBeenRead = true; + + //The following variable is used to hold the syntax from + //the suers custom file - if that file should be changed, + //then all entries in this variable should be removed from + //the word list, reread from the file and then reinserted. + private static Vector userdefsyntaxdata; + + private static Vector syntaxdata; + + public PHPSyntaxRdr() { + syntaxdata = new Vector(); + store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + } + + public static void readInSyntax() { + try { + hasXMLFileBeenRead = true; + /*Attempt to read the syntax file from the metadata + * if this does not work, create metadata from default*/ + File syntaxFile = getSyntaxFile(); + if (syntaxFile.exists()) { + readFromFile(syntaxFile); + } else { + readFromStream(PHPSyntaxRdr.class.getResourceAsStream(PHPSYNTAX_FILE)); + saveToFile(syntaxFile); + } + /*Read the user-defined syntax file if it exists*/ + //String buffer = new String(store.getString(PHPeclipsePlugin.PHP_USERDEF_XMLFILE)); + if (store == null) + store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); + if (!buffer.equals("") || buffer != null) { + readFromFile(buffer); + } + } catch (CoreException ce) { + ce.printStackTrace(); + } + } + + public static void readFromFile(String filename) { + try { + readFromFile(new File(filename)); + } catch (CoreException e) { + } + } + + public static void readFromFile(File file) throws CoreException { + InputStream stream = null; + try { + stream = new FileInputStream(file); + readFromStream(stream); + } catch (IOException e) { + throwReadException(e); + } finally { + try { + if (stream != null) { + stream.close(); + } + } catch (IOException e) { + } + } + } + public static void readFromStream(InputStream stream) throws CoreException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder parser = factory.newDocumentBuilder(); + Document document = parser.parse(new InputSource(stream)); + //Read in the Standard PHPSyntax "stuff" + NodeList elements = document.getElementsByTagName(PHPSYNTAX_TAG); + + int count = elements.getLength(); + for (int i = 0; i != count; i++) { + Node node = elements.item(i); + NamedNodeMap attributes = node.getAttributes(); + + if (attributes == null) + continue; + + String Keyword = getAttributeValue(attributes, KEYWORD_ATTR); + String Type = getAttributeValue(attributes, TYPE_ATTR); + String Function = getAttributeValue(attributes, FN_ATTR); + String Constant = getAttributeValue(attributes, CONSTANT_ATTR); + String Description = getAttributeValue(attributes, DESCRIPTION); + String Usage = getAttributeValue(attributes, USAGE_ATTR); + String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR); + + if (Keyword == null && Type == null && Function == null && Constant == null) { + //ignore as it is not a valid phpsyntax tag + } else { + if (Keyword != null) { + syntaxdata.addElement(new PHPKeyword(Keyword, Description, Tokenval)); + } else if (Type != null) { + syntaxdata.addElement(new PHPType(Type, Description)); + } else if (Function != null) { + syntaxdata.addElement(new PHPFunction(Function, Description, Usage)); + } else if (Constant != null) { + syntaxdata.addElement(new PHPConstant(Constant, Description)); + } + } + } + } catch (ParserConfigurationException e) { + throwReadException(e); + } catch (IOException e) { + throwReadException(e); + } catch (SAXException e) { + throwReadException(e); + } + } + + public static Vector getsyntaxdata() { + return (Vector) syntaxdata.clone(); + } + + public static void replaceUserDefFile() { + /*Replace the user-defined syntax file if it exists*/ + String buffer = new String(store.getString(IPreferenceConstants.PHP_USERDEF_XMLFILE)); + if (!buffer.equals("") || buffer == null) { + readFromFile(buffer); + } + } + + public static Vector getUserDefinitions() { + return (Vector) userdefsyntaxdata.clone(); + } + + private static File getSyntaxFile() { + IPath path = PHPeclipsePlugin.getDefault().getStateLocation(); + path = path.append(PHPSYNTAX_FILE); + return path.toFile(); + } + + private static String getAttributeValue(NamedNodeMap attributes, String name) { + Node node = attributes.getNamedItem(name); + return node == null ? null : node.getNodeValue(); + } + + public static void saveToFile(File file) throws CoreException { + OutputStream stream = null; + try { + stream = new FileOutputStream(file); + saveToStream(stream); + } catch (IOException e) { + throwWriteException(e); + } finally { + try { + if (stream != null) + stream.close(); + } catch (IOException e) { + } + } + } + + public static void saveToStream(OutputStream stream) throws CoreException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Node root = document.createElement("PHPStandardSyntax"); // $NON-NLS-1$ //$NON-NLS-1$ + document.appendChild(root); + for (int i = 0; i != syntaxdata.size(); i++) { + Object bufferobj = (Object) syntaxdata.get(i); + Attr name = null; + Node node = document.createElement(PHPSYNTAX_TAG); // $NON-NLS-1$ //$NON-NLS-1$ + root.appendChild(node); + NamedNodeMap attributes = node.getAttributes(); + if (bufferobj instanceof PHPType) + name = document.createAttribute(TYPE_ATTR); + if (bufferobj instanceof PHPKeyword) + name = document.createAttribute(KEYWORD_ATTR); + if (bufferobj instanceof PHPFunction) + name = document.createAttribute(FN_ATTR); + if (bufferobj instanceof PHPConstant) + name = document.createAttribute(CONSTANT_ATTR); + name.setValue(((PHPElement) bufferobj).getName()); + attributes.setNamedItem(name); + Attr description = document.createAttribute(DESCRIPTION); + description.setValue(((PHPElement) bufferobj).getDescription()); + attributes.setNamedItem(description); + if (bufferobj instanceof PHPKeyword) { + Attr tokenval = document.createAttribute(TOKENVAL_ATTR); + tokenval.setValue((new Integer(((PHPKeyword) bufferobj).gettokenval())).toString()); + attributes.setNamedItem(tokenval); + } + if (bufferobj instanceof PHPFunction) { + Attr usage = document.createAttribute(USAGE_ATTR); + usage.setValue(((PHPFunction) bufferobj).getUsage()); + attributes.setNamedItem(usage); + } + } + OutputFormat format = new OutputFormat(); + format.setPreserveSpace(true); + try { + Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format); + serializer.asDOMSerializer().serialize(document); + } catch (UnsupportedEncodingException e) { + } catch (IOException e) { + } //$NON-NLS-1$ + // Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$ + } catch (ParserConfigurationException e) { + throwWriteException(e); + // } catch (IOException e) { + // throwWriteException(e); + } + } + + private static void throwReadException(Throwable t) throws CoreException { + PHPeclipsePlugin.log(t); + // IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION, + // TemplateMessages.getString("TemplateSet.error.read"), t); //$NON-NLS-1$ + // throw new JavaUIException(status); + } + + private static void throwWriteException(Throwable t) throws CoreException { + PHPeclipsePlugin.log(t); + // IStatus status= new JavaUIStatus(JavaStatusConstants.TEMPLATE_IO_EXCEPTION, + // TemplateMessages.getString("TemplateSet.error.write"), t); //$NON-NLS-1$ + // throw new JavaUIException(status); + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java index f4e6582..4851296 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java @@ -12,24 +12,25 @@ Contributors: package net.sourceforge.phpeclipse.phpeditor; import java.util.HashMap; +import java.util.Vector; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunctionDescription; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunctionNames; import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; -import org.eclipse.jface.text.BadLocationException; + import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.swt.graphics.Point; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; + /** * Example implementation for an ITextHover * which hovers over PHP code. */ public class PHPTextHover implements ITextHover { public static HashMap functionDescriptions = null; - + private static PHPWordExtractor phpWordDetector = new PHPWordExtractor(); /* (non-Javadoc) * Method declared on ITextHover @@ -39,15 +40,29 @@ public class PHPTextHover implements ITextHover { try { if (hoverRegion.getLength() > -1) { String word = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength()); - if (functionDescriptions==null) { - functionDescriptions = new HashMap(997); - for (int i=0; i -// for (int i = 0; i < PHPKeywords.PHP_KEYWORS.length; i++) -// wordRule.addWord(PHPKeywords.PHP_KEYWORS[i], keyword); -// -// /*Read in the keywords from the XML file*/ -// PHPSyntaxRdr syntaxRdr = new PHPSyntaxRdr(); -// syntaxRdr.readFromFile( -// "C:\\eclipse\\workspace\\net.sourceforge.phpeclipse\\src\\net\\sourceforge\\phpeclipse\\phpeditor" -// + java.io.File.separator -// + "syntax.xml"); -// { -// Vector Vbuffer = syntaxRdr.getKeywords(); -// String VString = null; -// //Read keywords -// while ((Vbuffer != null) && (!Vbuffer.isEmpty() && ((VString = (String) Vbuffer.remove(0)) != null))) { -// wordRule.addWord(VString, keyword); -// } -// //Read functions - to be tested -// Vbuffer = syntaxRdr.getFunctions(); -// while ((Vbuffer != null) && (!Vbuffer.isEmpty() && ((VString = (String) Vbuffer.remove(0)) != null))) { -// wordRule.addWord(VString, functionName); -// } -// } -// -// //for (int i = 0; i < PHPFunctionNames.FUNCTION_NAMES.length; i++) -// // wordRule.addWord(PHPFunctionNames.FUNCTION_NAMES[i], functionName); -// //<--choochter - for (int i = 0; i < PHPKeywords.PHP_KEYWORS.length; i++) { - wordRule.addWord(PHPKeywords.PHP_KEYWORS[i], keyword); - } - for (int i = 0; i < PHPFunctionNames.FUNCTION_NAMES.length; i++) { - wordRule.addWord(PHPFunctionNames.FUNCTION_NAMES[i], functionName); - } - for (int i = 0; i < fgConstants.length; i++) { - wordRule.addWord(fgConstants[i], keyword); + + PHPSyntaxRdr.readInSyntax(); + Vector buffer = PHPSyntaxRdr.getsyntaxdata(); + String strbuffer = null; + PHPElement elbuffer = null; + while ((buffer != null) && (!buffer.isEmpty() && ((elbuffer = (PHPElement) buffer.remove(0)) != null))) { + if (elbuffer instanceof PHPKeyword) + wordRule.addWord(((PHPKeyword) elbuffer).getName(), keyword); + if (elbuffer instanceof PHPFunction) + wordRule.addWord(((PHPFunction) elbuffer).getName(), functionName); + if (elbuffer instanceof PHPType) + wordRule.addWord(elbuffer.getName(), type); + if (elbuffer instanceof PHPConstant) + wordRule.addWord(elbuffer.getName(), constant); } rules.add(wordRule); - IRule[] result = new IRule[rules.size()]; rules.toArray(result); setRules(result); } - - public void updateToken(PHPColorProvider provider) { - final IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); - - variable.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_VARIABLE)))); - keyword.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_KEYWORD)))); - functionName.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_FUNCTIONNAME)))); - string.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_STRING)))); - comment.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_SINGLELINE_COMMENT)))); - multi_comment.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_MULTILINE_COMMENT)))); - other.setData(new TextAttribute(provider.getColor(PreferenceConverter.getColor(store, PHP_DEFAULT)))); - - } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java new file mode 100644 index 0000000..68119e7 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPConstant.java @@ -0,0 +1,16 @@ +package net.sourceforge.phpeclipse.phpeditor.php; + + +/** + * @author Choochter + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class PHPConstant extends PHPElement{ + public PHPConstant(String Name, String Description){ + super(Name, Description); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java new file mode 100644 index 0000000..be19656 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java @@ -0,0 +1,33 @@ +package net.sourceforge.phpeclipse.phpeditor.php; + +/** + * @author choochter + */ +public abstract class PHPElement { + + private String ElementName; + private String ElementDescription; + + //Setters + public final void setName(String ElementName) + { this.ElementName = ElementName; } + public final void setDescription(String ElementDescription) + { this.ElementDescription = ElementDescription; } + + //Getters + public final String getName() { return ElementName; } + public final String getDescription() { return ElementDescription; } + + public PHPElement(){} + public PHPElement(String Name, String Description){ + setName(Name); + if ((Description == null) || (Description.equals(""))) + { + setDescription(Name +" - "); + } + else { + setDescription(Description); + } + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java new file mode 100644 index 0000000..2e45bdb --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java @@ -0,0 +1,20 @@ +package net.sourceforge.phpeclipse.phpeditor.php; + +/** + * @author Choochter + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class PHPFunction extends PHPElement{ + private String FunctionUsage; + public void setUsage(String Usage) {this.FunctionUsage = Usage;} + public String getUsage() { return this.FunctionUsage; } + + public PHPFunction(String Name, String Description, String Usage){ + super(Name, Description); + setUsage(Usage); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunctionDescription.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunctionDescription.java deleted file mode 100644 index 360f893..0000000 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunctionDescription.java +++ /dev/null @@ -1,2388 +0,0 @@ -/********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Klaus Hartlage - www.eclipseproject.de -**********************************************************************/ -package net.sourceforge.phpeclipse.phpeditor.php; - -/** - * PHP function - short description - */ -public class PHPFunctionDescription { - - public static String[] FUNCTION_DESCRIPTION = - { - "mixed COM_invoke(int module, string handler_name [, mixed arg [, mixed ...]])\n"+ - "Invokes a COM module", - - "int com_load(string module_name [, string remote_host [, int codepage [, string typelib]]])\n"+ - "Loads a COM module", - - "int abs(int number)\n"+ - "Return the absolute value of the number", - - "accept_connect - ", - "float acos(float number)\n"+ - "Return the arc cosine of the number in radians", - - "add - ", - "add_iovec - ", - "addaction - ", - "addcolor - ", - "addcslashes - ", - "addentry - ", - "addfill - ", - "addshape - ", - "addslashes - ", - "addstring - ", - "addstring - ", - "align - ", - "apache_child_terminate - ", - "apache_lookup_uri - ", - "apache_lookup_uri - ", - "apache_note - ", - "apache_sub_req - ", - "array_count_values - ", - "array_diff - ", - "array_filter - ", - "array_flip - ", - "array_intersect - ", - "array_keys - ", - "array_map - ", - "array_merge - ", - "array_merge_recursive - ", - "array_multisort - ", - "array_pad - ", - "array_pop - ", - "array_push - ", - "array_rand - ", - "array_reduce - ", - "array_reverse - ", - "array_search - ", - "array_shift - ", - "array_slice - ", - "array_splice - ", - "array_sum - ", - "array_unique - ", - "array_unshift - ", - "array_values - ", - "array_walk - ", - "arsort - ", - "asin - ", - "asort - ", - "aspell_check - ", - "aspell_check_raw - ", - "aspell_new - ", - "aspell_suggest - ", - "assert - ", - "assert_options - ", - "atan - ", - "atan2 - ", - "base64_decode - ", - "base64_encode - ", - "base_convert - ", - "basename - ", - "bcadd - ", - "bccomp - ", - "bcdiv - ", - "bcmod - ", - "bcmul - ", - "bcpow - ", - "bcscale - ", - "bcsqrt - ", - "bcsub - ", - "bin2hex - ", - "bind - ", - "bindec - ", - "bindtextdomain - ", - "build_iovec - ", - "bzclose - ", - "bzcompress - ", - "bzdecompress - ", - "bzerrno - ", - "bzerror - ", - "bzerrstr - ", - "bzflush - ", - "bzopen - ", - "bzread - ", - "bzwrite - ", - "call_user_func - ", - "call_user_func_array - ", - "call_user_method - ", - "call_user_method_array - ", - "ccvs_add - ", - "ccvs_auth - ", - "ccvs_command - ", - "ccvs_count - ", - "ccvs_delete - ", - "ccvs_done - ", - "ccvs_init - ", - "ccvs_lookup - ", - "ccvs_new - ", - "ccvs_report - ", - "ccvs_return - ", - "ccvs_reverse - ", - "ccvs_sale - ", - "ccvs_status - ", - "ccvs_textvalue - ", - "ccvs_void - ", - "ceil - ", - "chdir - ", - "checkdate - ", - "checkdnsrr - ", - "checkdnsrr - ", - "chgrp - ", - "chmod - ", - "chop - ", - "chown - ", - "chr - ", - "chroot - ", - "chroot - ", - "chunk_split - ", - - "bool class_exists(string classname)\n"+ - "Checks if the class exists", - - "clearstatcache - ", - "close - ", - - "void closedir([resource dir_handle])\n"+ - "Close directory connection identified by the dir_handle", - - "closelog - ", - "com_get - ", - "com_propget - ", - "com_propput - ", - "com_propset - ", - "com_set - ", - "compact - ", - "confirm_cybermut_compiled - ", - "confirm_extname_compiled - ", - "connect - ", - "connection_aborted - ", - "connection_status - ", - "constant - ", - "convert_cyr_string - ", - "copy - ", - "cos - ", - "count - ", - "count_chars - ", - "cpdf_add_annotation - ", - "cpdf_add_outline - ", - "cpdf_arc - ", - "cpdf_begin_text - ", - "cpdf_circle - ", - "cpdf_clip - ", - "cpdf_close - ", - "cpdf_closepath - ", - "cpdf_closepath_fill_stroke - ", - "cpdf_closepath_stroke - ", - "cpdf_continue_text - ", - "cpdf_curveto - ", - "cpdf_end_text - ", - "cpdf_fill - ", - "cpdf_fill_stroke - ", - "cpdf_finalize - ", - "cpdf_finalize_page - ", - "cpdf_global_set_document_limits - ", - "cpdf_import_jpeg - ", - "cpdf_lineto - ", - "cpdf_moveto - ", - "cpdf_newpath - ", - "cpdf_open - ", - "cpdf_output_buffer - ", - "cpdf_page_init - ", - "cpdf_place_inline_image - ", - "cpdf_rect - ", - "cpdf_restore - ", - "cpdf_rlineto - ", - "cpdf_rmoveto - ", - "cpdf_rotate - ", - "cpdf_rotate_text - ", - "cpdf_save - ", - "cpdf_save_to_file - ", - "cpdf_scale - ", - "cpdf_set_action_url - ", - "cpdf_set_char_spacing - ", - "cpdf_set_creator - ", - "cpdf_set_current_page - ", - "cpdf_set_font - ", - "cpdf_set_font_directories - ", - "cpdf_set_font_map_file - ", - "cpdf_set_horiz_scaling - ", - "cpdf_set_keywords - ", - "cpdf_set_leading - ", - "cpdf_set_page_animation - ", - "cpdf_set_subject - ", - "cpdf_set_text_matrix - ", - "cpdf_set_text_pos - ", - "cpdf_set_text_rendering - ", - "cpdf_set_text_rise - ", - "cpdf_set_title - ", - "cpdf_set_viewer_preferences - ", - "cpdf_set_word_spacing - ", - "cpdf_setdash - ", - "cpdf_setflat - ", - "cpdf_setgray - ", - "cpdf_setgray_fill - ", - "cpdf_setgray_stroke - ", - "cpdf_setlinecap - ", - "cpdf_setlinejoin - ", - "cpdf_setlinewidth - ", - "cpdf_setmiterlimit - ", - "cpdf_setrgbcolor - ", - "cpdf_setrgbcolor_fill - ", - "cpdf_setrgbcolor_stroke - ", - "cpdf_show - ", - "cpdf_show_xy - ", - "cpdf_stringwidth - ", - "cpdf_stroke - ", - "cpdf_text - ", - "cpdf_translate - ", - "crack_check - ", - "crack_closedict - ", - "crack_getlastmessage - ", - "crack_opendict - ", - "crash - ", - "crc32 - ", - - "string create_function(string args, string code)\n"+ - "Creates an anonymous function, and returns its name (funny, eh?)", - - "crypt - ", - "crypt - ", - "ctype_alnum - ", - "ctype_alpha - ", - "ctype_cntrl - ", - "ctype_digit - ", - "ctype_graph - ", - "ctype_lower - ", - "ctype_print - ", - "ctype_punct - ", - "ctype_space - ", - "ctype_upper - ", - "ctype_xdigit - ", - "curl_close - ", - "curl_errno - ", - "curl_error - ", - "curl_exec - ", - "curl_getinfo - ", - "curl_getinfo - ", - "curl_init - ", - "curl_setopt - ", - "curl_version - ", - "current - ", - "cv_add - ", - "cv_auth - ", - "cv_command - ", - "cv_count - ", - "cv_delete - ", - "cv_done - ", - "cv_init - ", - "cv_lookup - ", - "cv_new - ", - "cv_report - ", - "cv_return - ", - "cv_reverse - ", - "cv_sale - ", - "cv_status - ", - "cv_textvalue - ", - "cv_void - ", - "cybercash_base64_decode - ", - "cybercash_base64_encode - ", - "cybercash_decr - ", - "cybercash_encr - ", - "cybermut_creerformulairecm - ", - "cybermut_creerreponsecm - ", - "cybermut_testmac - ", - "date - ", - "dba_close - ", - "dba_delete - ", - "dba_exists - ", - "dba_fetch - ", - "dba_firstkey - ", - "dba_insert - ", - "dba_nextkey - ", - "dba_open - ", - "dba_optimize - ", - "dba_popen - ", - "dba_replace - ", - "dba_sync - ", - "dbase_add_record - ", - "dbase_close - ", - "dbase_create - ", - "dbase_delete_record - ", - "dbase_get_record - ", - "dbase_get_record_with_names - ", - "dbase_numfields - ", - "dbase_numrecords - ", - "dbase_open - ", - "dbase_pack - ", - "dbase_replace_record - ", - "dblist - ", - "dbmclose - ", - "dbmdelete - ", - "dbmexists - ", - "dbmfetch - ", - "dbmfirstkey - ", - "dbminsert - ", - "dbmnextkey - ", - "dbmopen - ", - "dbmreplace - ", - "dbx_close - ", - "dbx_cmp_asc - ", - "dbx_cmp_desc - ", - "dbx_connect - ", - "dbx_error - ", - "dbx_query - ", - "dbx_sort - ", - "dcgettext - ", - "decbin - ", - "dechex - ", - "decoct - ", - - "bool define(string constant_name, mixed value, case_sensitive=true)\n"+ - "Define a new constant", - - "define_syslog_variables - ", - - "bool defined(string constant_name)\n"+ - "Check whether a constant exists", - - "deg2rad - ", - "delete_iovec - ", - "dgettext - ", - - "class dir(string directory)\n"+ - "Directory class with properties, handle and class and methods read, rewind and close", - - "dirname - ", - "diskfreespace - ", - "display_disabled_function - ", - "dl - ", - "domxml_add_root - ", - "domxml_attributes - ", - "domxml_children - ", - "domxml_dumpmem - ", - "domxml_elem_get_attribute - ", - "domxml_elem_set_attribute - ", - "domxml_get_attribute - ", - "domxml_getattr - ", - "domxml_new_child - ", - "domxml_new_xmldoc - ", - "domxml_node - ", - "domxml_node_attributes - ", - "domxml_node_children - ", - "domxml_node_new_child - ", - "domxml_node_set_content - ", - "domxml_node_unlink_node - ", - "domxml_root - ", - "domxml_set_attribute - ", - "domxml_setattr - ", - "domxml_unlink_node - ", - "domxml_version - ", - "doubleval - ", - "drawarc - ", - "drawcircle - ", - "drawcubic - ", - "drawcubicto - ", - "drawcurve - ", - "drawcurveto - ", - "drawglyph - ", - "drawline - ", - "drawlineto - ", - "each - ", - "easter_date - ", - "easter_days - ", - "end - ", - "ereg - ", - "ereg_replace - ", - "eregi - ", - "eregi_replace - ", - "error_log - ", - "error_reporting - ", - "escapeshellarg - ", - "escapeshellcmd - ", - "exec - ", - "exit - ", - "exp - ", - "explode - ", - "extension_loaded - ", - "extract - ", - "ezmlm_hash - ", - "ezmlm_hash - ", - "fbsql - ", - "fbsql_affected_rows - ", - "fbsql_autocommit - ", - "fbsql_close - ", - "fbsql_commit - ", - "fbsql_connect - ", - "fbsql_create_db - ", - "fbsql_data_seek - ", - "fbsql_database - ", - "fbsql_database_password - ", - "fbsql_db_query - ", - "fbsql_drop_db - ", - "fbsql_errno - ", - "fbsql_error - ", - "fbsql_fetch_array - ", - "fbsql_fetch_assoc - ", - "fbsql_fetch_field - ", - "fbsql_fetch_lengths - ", - "fbsql_fetch_object - ", - "fbsql_fetch_row - ", - "fbsql_field_flags - ", - "fbsql_field_len - ", - "fbsql_field_name - ", - "fbsql_field_seek - ", - "fbsql_field_table - ", - "fbsql_field_type - ", - "fbsql_free_result - ", - "fbsql_hostname - ", - "fbsql_insert_id - ", - "fbsql_list_dbs - ", - "fbsql_list_fields - ", - "fbsql_list_tables - ", - "fbsql_next_result - ", - "fbsql_num_fields - ", - "fbsql_num_rows - ", - "fbsql_password - ", - "fbsql_pconnect - ", - "fbsql_query - ", - "fbsql_result - ", - "fbsql_rollback - ", - "fbsql_select_db - ", - "fbsql_start_db - ", - "fbsql_stop_db - ", - "fbsql_username - ", - "fbsql_warnings - ", - "fclose - ", - "fd_alloc - ", - "fd_clear - ", - "fd_dealloc - ", - "fd_isset - ", - "fd_set - ", - "fd_zero - ", - "fdf_add_template - ", - "fdf_close - ", - "fdf_create - ", - "fdf_get_file - ", - "fdf_get_status - ", - "fdf_get_value - ", - "fdf_next_field_name - ", - "fdf_open - ", - "fdf_save - ", - "fdf_set_ap - ", - "fdf_set_file - ", - "fdf_set_flags - ", - "fdf_set_javascript_action - ", - "fdf_set_opt - ", - "fdf_set_status - ", - "fdf_set_submit_form_action - ", - "fdf_set_value - ", - "feof - ", - "fetch_iovec - ", - "fflush - ", - "fgetc - ", - "fgetcsv - ", - "fgets - ", - "fgetss - ", - "file - ", - "file_exists - ", - "fileatime - ", - "filectime - ", - "filegroup - ", - "fileinode - ", - "filemtime - ", - "fileowner - ", - "fileperms - ", - "filepro - ", - "filepro_fieldcount - ", - "filepro_fieldname - ", - "filepro_fieldtype - ", - "filepro_fieldwidth - ", - "filepro_retrieve - ", - "filepro_rowcount - ", - "filesize - ", - "filetype - ", - "flock - ", - "floor - ", - "flush - ", - "fopen - ", - "fopenstream - ", - "fopenstream - ", - "fpassthru - ", - "fputs - ", - "fread - ", - "free_iovec - ", - "frenchtojd - ", - "fribidi_log2vis - ", - "fscanf - ", - "fseek - ", - "fsockopen - ", - "fstat - ", - "ftell - ", - "ftp_cdup - ", - "ftp_chdir - ", - "ftp_connect - ", - "ftp_delete - ", - "ftp_exec - ", - "ftp_fget - ", - "ftp_fput - ", - "ftp_get - ", - "ftp_login - ", - "ftp_mdtm - ", - "ftp_mkdir - ", - "ftp_nlist - ", - "ftp_pasv - ", - "ftp_put - ", - "ftp_pwd - ", - "ftp_quit - ", - "ftp_rawlist - ", - "ftp_rename - ", - "ftp_rmdir - ", - "ftp_site - ", - "ftp_size - ", - "ftp_systype - ", - "ftruncate - ", - "func_get_arg - ", - "func_get_args - ", - "func_num_args - ", - "function_exists - ", - "fwrite - ", - "get_all_headers - ", - "get_browser - ", - "get_cfg_var - ", - "get_class - ", - "get_class_methods - ", - "get_class_vars - ", - "get_current_user - ", - "get_declared_classes - ", - "get_defined_functions - ", - "get_defined_vars - ", - "get_extension_funcs - ", - "get_html_translation_table - ", - "get_included_files - ", - "get_loaded_extensions - ", - "get_magic_quotes_gpc - ", - "get_magic_quotes_runtime - ", - "get_meta_tags - ", - "get_object_vars - ", - "get_parent_class - ", - "get_required_files - ", - "get_resource_type - ", - "getallheaders - ", - "getallheaders - ", - "getascent - ", - "getascent - ", - "getcwd - ", - "getdate - ", - "getdescent - ", - "getdescent - ", - "getenv - ", - "getheight - ", - "gethostbyaddr - ", - "gethostbyaddr - ", - "gethostbyname - ", - "gethostbyname - ", - "gethostbynamel - ", - "getimagesize - ", - "getlastmod - ", - "getleading - ", - "getleading - ", - "getmxrr - ", - "getmxrr - ", - "getmyinode - ", - "getmypid - ", - "getmyuid - ", - "getpeername - ", - "getprotobyname - ", - "getprotobynumber - ", - "getrandmax - ", - "getrusage - ", - "getrusage - ", - "getservbyname - ", - "getservbyport - ", - "getshape1 - ", - "getshape2 - ", - "getsockname - ", - "getsockopt - ", - "gettext - ", - "gettimeofday - ", - "gettype - ", - "getwidth - ", - "getwidth - ", - "getwidth - ", - "gmdate - ", - "gmmktime - ", - "gmp_abs - ", - "gmp_add - ", - "gmp_and - ", - "gmp_clrbit - ", - "gmp_cmp - ", - "gmp_com - ", - "gmp_div - ", - "gmp_div_q - ", - "gmp_div_qr - ", - "gmp_div_r - ", - "gmp_divexact - ", - "gmp_fact - ", - "gmp_gcd - ", - "gmp_gcdext - ", - "gmp_hamdist - ", - "gmp_init - ", - "gmp_intval - ", - "gmp_invert - ", - "gmp_jacobi - ", - "gmp_legendre - ", - "gmp_mod - ", - "gmp_mul - ", - "gmp_neg - ", - "gmp_or - ", - "gmp_perfect_square - ", - "gmp_popcount - ", - "gmp_pow - ", - "gmp_powm - ", - "gmp_prob_prime - ", - "gmp_random - ", - "gmp_scan0 - ", - "gmp_scan1 - ", - "gmp_setbit - ", - "gmp_sign - ", - "gmp_sqrt - ", - "gmp_sqrtrem - ", - "gmp_strval - ", - "gmp_sub - ", - "gmp_xor - ", - "gmstrftime - ", - "gmstrftime - ", - "gregoriantojd - ", - "gzclose - ", - "gzcompress - ", - "gzdeflate - ", - "gzencode - ", - "gzeof - ", - "gzfile - ", - "gzgetc - ", - "gzgets - ", - "gzgetss - ", - "gzinflate - ", - "gzopen - ", - "gzpassthru - ", - "gzputs - ", - "gzread - ", - "gzrewind - ", - "gzseek - ", - "gztell - ", - "gzuncompress - ", - "gzwrite - ", - "header - ", - "headers_sent - ", - "hebrev - ", - "hebrevc - ", - "hexdec - ", - "highlight_file - ", - "highlight_string - ", - "htmlentities - ", - "htmlspecialchars - ", - "hw_array2objrec - ", - "hw_changeobject - ", - "hw_children - ", - "hw_childrenobj - ", - "hw_close - ", - "hw_connect - ", - "hw_connection_info - ", - "hw_cp - ", - "hw_deleteobject - ", - "hw_docbyanchor - ", - "hw_docbyanchorobj - ", - "hw_document_attributes - ", - "hw_document_bodytag - ", - "hw_document_content - ", - "hw_document_setcontent - ", - "hw_document_size - ", - "hw_dummy - ", - "hw_edittext - ", - "hw_error - ", - "hw_errormsg - ", - "hw_free_document - ", - "hw_getanchors - ", - "hw_getanchorsobj - ", - "hw_getandlock - ", - "hw_getcgi - ", - "hw_getchildcoll - ", - "hw_getchildcollobj - ", - "hw_getchilddoccoll - ", - "hw_getchilddoccollobj - ", - "hw_getobject - ", - "hw_getobjectbyftquery - ", - "hw_getobjectbyftquerycoll - ", - "hw_getobjectbyftquerycollobj - ", - "hw_getobjectbyftqueryobj - ", - "hw_getobjectbyquery - ", - "hw_getobjectbyquerycoll - ", - "hw_getobjectbyquerycollobj - ", - "hw_getobjectbyqueryobj - ", - "hw_getparents - ", - "hw_getparentsobj - ", - "hw_getrellink - ", - "hw_getremote - ", - "hw_getremotechildren - ", - "hw_getsrcbydestobj - ", - "hw_gettext - ", - "hw_getusername - ", - "hw_identify - ", - "hw_incollections - ", - "hw_info - ", - "hw_inscoll - ", - "hw_insdoc - ", - "hw_insertanchors - ", - "hw_insertdocument - ", - "hw_insertobject - ", - "hw_mapid - ", - "hw_modifyobject - ", - "hw_mv - ", - "hw_new_document - ", - "hw_new_document_from_file - ", - "hw_objrec2array - ", - "hw_output_document - ", - "hw_pconnect - ", - "hw_pipecgi - ", - "hw_pipedocument - ", - "hw_root - ", - "hw_setlinkroot - ", - "hw_stat - ", - "hw_unlock - ", - "hw_who - ", - "ibase_blob_add - ", - "ibase_blob_cancel - ", - "ibase_blob_close - ", - "ibase_blob_create - ", - "ibase_blob_echo - ", - "ibase_blob_get - ", - "ibase_blob_import - ", - "ibase_blob_info - ", - "ibase_blob_open - ", - "ibase_close - ", - "ibase_commit - ", - "ibase_connect - ", - "ibase_errmsg - ", - "ibase_execute - ", - "ibase_fetch_object - ", - "ibase_fetch_row - ", - "ibase_field_info - ", - "ibase_free_query - ", - "ibase_free_result - ", - "ibase_num_fields - ", - "ibase_pconnect - ", - "ibase_prepare - ", - "ibase_query - ", - "ibase_rollback - ", - "ibase_timefmt - ", - "ibase_trans - ", - "icap_create_calendar - ", - "icap_delete_calendar - ", - "icap_delete_event - ", - "icap_fetch_event - ", - "icap_list_alarms - ", - "icap_list_events - ", - "icap_open - ", - "icap_popen - ", - "icap_rename_calendar - ", - "icap_reopen - ", - "icap_snooze - ", - "icap_store_event - ", - "iconv - ", - "iconv_get_encoding - ", - "iconv_set_encoding - ", - "ifx_affected_rows - ", - "ifx_blobinfile_mode - ", - "ifx_byteasvarchar - ", - "ifx_close - ", - "ifx_connect - ", - "ifx_copy_blob - ", - "ifx_create_blob - ", - "ifx_create_char - ", - "ifx_do - ", - "ifx_error - ", - "ifx_errormsg - ", - "ifx_fetch_row - ", - "ifx_fieldproperties - ", - "ifx_fieldtypes - ", - "ifx_free_blob - ", - "ifx_free_char - ", - "ifx_free_result - ", - "ifx_get_blob - ", - "ifx_get_char - ", - "ifx_getsqlca - ", - "ifx_htmltbl_result - ", - "ifx_nullformat - ", - "ifx_num_fields - ", - "ifx_num_rows - ", - "ifx_pconnect - ", - "ifx_prepare - ", - "ifx_query - ", - "ifx_textasvarchar - ", - "ifx_update_blob - ", - "ifx_update_char - ", - "ifxus_close_slob - ", - "ifxus_create_slob - ", - "ifxus_free_slob - ", - "ifxus_open_slob - ", - "ifxus_read_slob - ", - "ifxus_seek_slob - ", - "ifxus_tell_slob - ", - "ifxus_write_slob - ", - "ignore_user_abort - ", - "iis_addserver - ", - "iis_getdirsecurity - ", - "iis_getscriptmap - ", - "iis_getserverbycomment - ", - "iis_getserverbypath - ", - "iis_getserverright - ", - "iis_getservicestate - ", - "iis_removeserver - ", - "iis_setappsettings - ", - "iis_setdirsecurity - ", - "iis_setscriptmap - ", - "iis_setserverright - ", - "iis_startserver - ", - "iis_startservice - ", - "iis_stopserver - ", - "iis_stopservice - ", - "image2wbmp - ", - "imagealphablending - ", - "imagearc - ", - "imagechar - ", - "imagecharup - ", - "imagecolorallocate - ", - "imagecolorat - ", - "imagecolorclosest - ", - "imagecolorclosestalpha - ", - "imagecolorclosesthwb - ", - "imagecolordeallocate - ", - "imagecolorexact - ", - "imagecolorexactalpha - ", - "imagecolorresolve - ", - "imagecolorresolvealpha - ", - "imagecolorset - ", - "imagecolorsforindex - ", - "imagecolorstotal - ", - "imagecolortransparent - ", - "imagecopy - ", - "imagecopymerge - ", - "imagecopymergegray - ", - "imagecopyresampled - ", - "imagecopyresized - ", - "imagecreate - ", - "imagecreatefromgif - ", - "imagecreatefromjpeg - ", - "imagecreatefrompng - ", - "imagecreatefromstring - ", - "imagecreatefromwbmp - ", - "imagecreatefromxbm - ", - "imagecreatefromxpm - ", - "imagecreatetruecolor - ", - "imagedashedline - ", - "imagedestroy - ", - "imageellipse - ", - "imagefill - ", - "imagefilledarc - ", - "imagefilledellipse - ", - "imagefilledpolygon - ", - "imagefilledrectangle - ", - "imagefilltoborder - ", - "imagefontheight - ", - "imagefontwidth - ", - "imagegammacorrect - ", - "imagegif - ", - "imageinterlace - ", - "imagejpeg - ", - "imageline - ", - "imageloadfont - ", - "imagepalettecopy - ", - "imagepng - ", - "imagepolygon - ", - "imagepsbbox - ", - "imagepscopyfont - ", - "imagepsencodefont - ", - "imagepsextendfont - ", - "imagepsfreefont - ", - "imagepsloadfont - ", - "imagepsslantfont - ", - "imagepstext - ", - "imagerectangle - ", - "imagesetbrush - ", - "imagesetpixel - ", - "imagesetstyle - ", - "imagesetthickness - ", - "imagesettile - ", - "imagestring - ", - "imagestringup - ", - "imagesx - ", - "imagesy - ", - "imagetruecolortopalette - ", - "imagettfbbox - ", - "imagettftext - ", - "imagetypes - ", - "imagewbmp - ", - "imap_8bit - ", - "imap_alerts - ", - "imap_append - ", - "imap_base64 - ", - "imap_binary - ", - "imap_body - ", - "imap_bodystruct - ", - "imap_check - ", - "imap_clearflag_full - ", - "imap_close - ", - "imap_create - ", - "imap_createmailbox - ", - "imap_delete - ", - "imap_deletemailbox - ", - "imap_errors - ", - "imap_expunge - ", - "imap_fetch_overview - ", - "imap_fetchbody - ", - "imap_fetchheader - ", - "imap_fetchstructure - ", - "imap_fetchtext - ", - "imap_get_quota - ", - "imap_getmailboxes - ", - "imap_getsubscribed - ", - "imap_header - ", - "imap_headerinfo - ", - "imap_headers - ", - "imap_last_error - ", - "imap_list - ", - "imap_listmailbox - ", - "imap_listsubscribed - ", - "imap_lsub - ", - "imap_mail - ", - "imap_mail - ", - "imap_mail_compose - ", - "imap_mail_copy - ", - "imap_mail_move - ", - "imap_mailboxmsginfo - ", - "imap_mime_header_decode - ", - "imap_msgno - ", - "imap_num_msg - ", - "imap_num_recent - ", - "imap_open - ", - "imap_ping - ", - "imap_popen - ", - "imap_qprint - ", - "imap_rename - ", - "imap_renamemailbox - ", - "imap_reopen - ", - "imap_rfc822_parse_adrlist - ", - "imap_rfc822_parse_headers - ", - "imap_rfc822_write_address - ", - "imap_scan - ", - "imap_scanmailbox - ", - "imap_search - ", - "imap_set_quota - ", - "imap_setflag_full - ", - "imap_sort - ", - "imap_status - ", - "imap_subscribe - ", - "imap_uid - ", - "imap_undelete - ", - "imap_unsubscribe - ", - "imap_utf7_decode - ", - "imap_utf7_encode - ", - "imap_utf8 - ", - "implode - ", - "in_array - ", - "ingres_autocommit - ", - "ingres_close - ", - "ingres_commit - ", - "ingres_connect - ", - "ingres_fetch_array - ", - "ingres_fetch_object - ", - "ingres_fetch_row - ", - "ingres_field_length - ", - "ingres_field_name - ", - "ingres_field_nullable - ", - "ingres_field_precision - ", - "ingres_field_scale - ", - "ingres_field_type - ", - "ingres_num_fields - ", - "ingres_num_rows - ", - "ingres_pconnect - ", - "ingres_query - ", - "ingres_rollback - ", - "ini_alter - ", - "ini_get - ", - "ini_restore - ", - "ini_set - ", - "intval - ", - "ip2long - ", - "iptcembed - ", - "iptcparse - ", - "ircg_channel_mode - ", - "ircg_disconnect - ", - "ircg_html_encode - ", - "ircg_ignore_add - ", - "ircg_ignore_del - ", - "ircg_is_conn_alive - ", - "ircg_join - ", - "ircg_kick - ", - "ircg_lookup_format_messages - ", - "ircg_msg - ", - "ircg_nick - ", - "ircg_nickname_escape - ", - "ircg_nickname_unescape - ", - "ircg_notice - ", - "ircg_part - ", - "ircg_pconnect - ", - "ircg_register_format_messages - ", - "ircg_set_current - ", - "ircg_topic - ", - "ircg_whois - ", - "is_array - ", - "is_bool - ", - "is_dir - ", - "is_double - ", - "is_executable - ", - "is_file - ", - "is_float - ", - "is_int - ", - "is_integer - ", - "is_link - ", - "is_long - ", - "is_null - ", - "is_numeric - ", - "is_object - ", - "is_readable - ", - "is_real - ", - "is_resource - ", - "is_scalar - ", - "is_string - ", - "is_subclass_of - ", - "is_uploaded_file - ", - "is_writable - ", - "is_writeable - ", - "java_last_exception_clear - ", - "java_last_exception_get - ", - "jddayofweek - ", - "jdmonthname - ", - "jdtofrench - ", - "jdtogregorian - ", - "jdtojewish - ", - "jdtojulian - ", - "jdtounix - ", - "jewishtojd - ", - "join - ", - "jpeg2wbmp - ", - "juliantojd - ", - "key - ", - "krsort - ", - "ksort - ", - "labelframe - ", - "labelframe - ", - "lcg_value - ", - "ldap_8859_to_t61 - ", - "ldap_add - ", - "ldap_bind - ", - "ldap_close - ", - "ldap_compare - ", - "ldap_connect - ", - "ldap_count_entries - ", - "ldap_delete - ", - "ldap_dn2ufn - ", - "ldap_err2str - ", - "ldap_errno - ", - "ldap_error - ", - "ldap_explode_dn - ", - "ldap_first_attribute - ", - "ldap_first_entry - ", - "ldap_first_reference - ", - "ldap_free_result - ", - "ldap_get_attributes - ", - "ldap_get_dn - ", - "ldap_get_entries - ", - "ldap_get_option - ", - "ldap_get_values - ", - "ldap_get_values_len - ", - "ldap_list - ", - "ldap_mod_add - ", - "ldap_mod_del - ", - "ldap_mod_replace - ", - "ldap_modify - ", - "ldap_next_attribute - ", - "ldap_next_entry - ", - "ldap_next_reference - ", - "ldap_parse_reference - ", - "ldap_parse_result - ", - "ldap_read - ", - "ldap_rename - ", - "ldap_search - ", - "ldap_set_option - ", - "ldap_t61_to_8859 - ", - "ldap_unbind - ", - "leak - ", - "levenshtein - ", - "link - ", - "link - ", - "linkinfo - ", - "linkinfo - ", - "listen - ", - "localeconv - ", - "localtime - ", - "log - ", - "log10 - ", - "long2ip - ", - "lstat - ", - "ltrim - ", - "magic_quotes_runtime - ", - "mail - ", - "mail - ", - "max - ", - "mcal_append_event - ", - "mcal_close - ", - "mcal_create_calendar - ", - "mcal_date_compare - ", - "mcal_date_valid - ", - "mcal_day_of_week - ", - "mcal_day_of_year - ", - "mcal_days_in_month - ", - "mcal_delete_calendar - ", - "mcal_delete_event - ", - "mcal_event_add_attribute - ", - "mcal_event_init - ", - "mcal_event_set_alarm - ", - "mcal_event_set_category - ", - "mcal_event_set_class - ", - "mcal_event_set_description - ", - "mcal_event_set_end - ", - "mcal_event_set_recur_daily - ", - "mcal_event_set_recur_monthly_mday - ", - "mcal_event_set_recur_monthly_wday - ", - "mcal_event_set_recur_none - ", - "mcal_event_set_recur_weekly - ", - "mcal_event_set_recur_yearly - ", - "mcal_event_set_start - ", - "mcal_event_set_title - ", - "mcal_fetch_current_stream_event - ", - "mcal_fetch_event - ", - "mcal_is_leap_year - ", - "mcal_list_alarms - ", - "mcal_list_events - ", - "mcal_next_recurrence - ", - "mcal_open - ", - "mcal_popen - ", - "mcal_rename_calendar - ", - "mcal_reopen - ", - "mcal_snooze - ", - "mcal_store_event - ", - "mcal_time_valid - ", - "mcal_week_of_year - ", - "mcrypt_cbc - ", - "mcrypt_cfb - ", - "mcrypt_create_iv - ", - "mcrypt_decrypt - ", - "mcrypt_ecb - ", - "mcrypt_enc_get_algorithms_name - ", - "mcrypt_enc_get_block_size - ", - "mcrypt_enc_get_iv_size - ", - "mcrypt_enc_get_key_size - ", - "mcrypt_enc_get_modes_name - ", - "mcrypt_enc_get_supported_key_sizes - ", - "mcrypt_enc_is_block_algorithm - ", - "mcrypt_enc_is_block_algorithm_mode - ", - "mcrypt_enc_is_block_mode - ", - "mcrypt_enc_self_test - ", - "mcrypt_encrypt - ", - "mcrypt_generic - ", - "mcrypt_generic_end - ", - "mcrypt_generic_init - ", - "mcrypt_get_block_size - ", - "mcrypt_get_cipher_name - ", - "mcrypt_get_iv_size - ", - "mcrypt_get_key_size - ", - "mcrypt_list_algorithms - ", - "mcrypt_list_modes - ", - "mcrypt_module_close - ", - "mcrypt_module_get_algo_block_size - ", - "mcrypt_module_get_algo_key_size - ", - "mcrypt_module_get_supported_key_sizes - ", - "mcrypt_module_is_block_algorithm - ", - "mcrypt_module_is_block_algorithm_mode - ", - "mcrypt_module_is_block_mode - ", - "mcrypt_module_open - ", - "mcrypt_module_self_test - ", - "mcrypt_ofb - ", - "md5 - ", - "mdecrypt_generic - ", - "metaphone - ", - "method_exists - ", - "mhash - ", - "mhash_count - ", - "mhash_get_block_size - ", - "mhash_get_hash_name - ", - "mhash_keygen_s2k - ", - "microtime - ", - "min - ", - "ming_setcubicthreshold - ", - "ming_setscale - ", - "mkdir - ", - "mktime - ", - "move - ", - "move_uploaded_file - ", - "movepen - ", - "movepento - ", - "moveto - ", - "moveto - ", - "moveto - ", - "msql - ", - "msql_affected_rows - ", - "msql_close - ", - "msql_connect - ", - "msql_create_db - ", - "msql_createdb - ", - "msql_data_seek - ", - "msql_db_query - ", - "msql_dbname - ", - "msql_drop_db - ", - "msql_dropdb - ", - "msql_error - ", - "msql_fetch_array - ", - "msql_fetch_field - ", - "msql_fetch_object - ", - "msql_fetch_row - ", - "msql_field_flags - ", - "msql_field_len - ", - "msql_field_name - ", - "msql_field_seek - ", - "msql_field_table - ", - "msql_field_type - ", - "msql_fieldflags - ", - "msql_fieldlen - ", - "msql_fieldname - ", - "msql_fieldtable - ", - "msql_fieldtype - ", - "msql_free_result - ", - "msql_freeresult - ", - "msql_list_dbs - ", - "msql_list_fields - ", - "msql_list_tables - ", - "msql_listdbs - ", - "msql_listfields - ", - "msql_listtables - ", - "msql_num_fields - ", - "msql_num_rows - ", - "msql_numfields - ", - "msql_numrows - ", - "msql_pconnect - ", - "msql_query - ", - "msql_regcase - ", - "msql_result - ", - "msql_select_db - ", - "msql_selectdb - ", - "msql_tablename - ", - "mssql_affected_rows - ", - "mssql_affected_rows - ", - "mssql_close - ", - "mssql_close - ", - "mssql_close - ", - "mssql_connect - ", - "mssql_connect - ", - "mssql_connect - ", - "mssql_data_seek - ", - "mssql_data_seek - ", - "mssql_data_seek - ", - "mssql_fetch_array - ", - "mssql_fetch_array - ", - "mssql_fetch_array - ", - "mssql_fetch_batch - ", - "mssql_fetch_field - ", - "mssql_fetch_field - ", - "mssql_fetch_field - ", - "mssql_fetch_object - ", - "mssql_fetch_object - ", - "mssql_fetch_object - ", - "mssql_fetch_row - ", - "mssql_fetch_row - ", - "mssql_fetch_row - ", - "mssql_field_length - ", - "mssql_field_name - ", - "mssql_field_seek - ", - "mssql_field_seek - ", - "mssql_field_seek - ", - "mssql_field_type - ", - "mssql_free_result - ", - "mssql_free_result - ", - "mssql_free_result - ", - "mssql_get_last_message - ", - "mssql_get_last_message - ", - "mssql_get_last_message - ", - "mssql_min_client_severity - ", - "mssql_min_error_severity - ", - "mssql_min_error_severity - ", - "mssql_min_message_severity - ", - "mssql_min_message_severity - ", - "mssql_min_server_severity - ", - "mssql_next_result - ", - "mssql_num_fields - ", - "mssql_num_fields - ", - "mssql_num_fields - ", - "mssql_num_rows - ", - "mssql_num_rows - ", - "mssql_num_rows - ", - "mssql_pconnect - ", - "mssql_pconnect - ", - "mssql_pconnect - ", - "mssql_query - ", - "mssql_query - ", - "mssql_query - ", - "mssql_result - ", - "mssql_result - ", - "mssql_result - ", - "mssql_rows_affected - ", - "mssql_select_db - ", - "mssql_select_db - ", - "mssql_select_db - ", - "mt_getrandmax - ", - "mt_rand - ", - "mt_srand - ", - "multcolor - ", - "muscat_close - ", - "muscat_get - ", - "muscat_give - ", - "muscat_setup - ", - "muscat_setup_net - ", - "mysql - ", - "mysql_affected_rows - ", - "mysql_close - ", - "mysql_connect - ", - "mysql_create_db - ", - "mysql_createdb - ", - "mysql_data_seek - ", - "mysql_db_name - ", - "mysql_db_query - ", - "mysql_dbname - ", - "mysql_drop_db - ", - "mysql_dropdb - ", - "mysql_errno - ", - "mysql_error - ", - "mysql_escape_string - ", - "mysql_fetch_array - ", - "mysql_fetch_assoc - ", - "mysql_fetch_field - ", - "mysql_fetch_lengths - ", - "mysql_fetch_object - ", - "mysql_fetch_row - ", - "mysql_field_flags - ", - "mysql_field_len - ", - "mysql_field_name - ", - "mysql_field_seek - ", - "mysql_field_table - ", - "mysql_field_type - ", - "mysql_fieldflags - ", - "mysql_fieldlen - ", - "mysql_fieldname - ", - "mysql_fieldtable - ", - "mysql_fieldtype - ", - "mysql_free_result - ", - "mysql_freeresult - ", - "mysql_get_client_info - ", - "mysql_get_host_info - ", - "mysql_get_proto_info - ", - "mysql_get_server_info - ", - "mysql_insert_id - ", - "mysql_list_dbs - ", - "mysql_list_fields - ", - "mysql_list_tables - ", - "mysql_listdbs - ", - "mysql_listfields - ", - "mysql_listtables - ", - "mysql_num_fields - ", - "mysql_num_rows - ", - "mysql_numfields - ", - "mysql_numrows - ", - "mysql_pconnect - ", - "mysql_query - ", - "mysql_result - ", - "mysql_select_db - ", - "mysql_selectdb - ", - "mysql_tablename - ", - "mysql_unbuffered_query - ", - "natcasesort - ", - "natsort - ", - "new_xmldoc - ", - "next - ", - "nextframe - ", - "nextframe - ", - "nl2br - ", - "notes_body - ", - "notes_copy_db - ", - "notes_create_db - ", - "notes_create_note - ", - "notes_drop_db - ", - "notes_find_note - ", - "notes_header_info - ", - "notes_list_msgs - ", - "notes_mark_read - ", - "notes_mark_unread - ", - "notes_nav_create - ", - "notes_search - ", - "notes_unread - ", - "notes_version - ", - "number_format - ", - "ob_end_clean - ", - "ob_end_flush - ", - "ob_get_contents - ", - "ob_get_length - ", - "ob_gzhandler - ", - "ob_iconv_handler - ", - "ob_implicit_flush - ", - "ob_start - ", - "ocibindbyname - ", - "ocicancel - ", - "ocicollappend - ", - "ocicollassign - ", - "ocicollassignelem - ", - "ocicolldateappendelem - ", - "ocicolldateassignelem - ", - "ocicolldategetelem - ", - "ocicollgetelem - ", - "ocicollmax - ", - "ocicollsize - ", - "ocicolltrim - ", - "ocicolumnisnull - ", - "ocicolumnname - ", - "ocicolumnprecision - ", - "ocicolumnscale - ", - "ocicolumnsize - ", - "ocicolumntype - ", - "ocicolumntyperaw - ", - "ocicommit - ", - "ocidefinebyname - ", - "ocierror - ", - "ociexecute - ", - "ocifetch - ", - "ocifetchinto - ", - "ocifetchstatement - ", - "ocifreecoll - ", - "ocifreecursor - ", - "ocifreedesc - ", - "ocifreestatement - ", - "ociinternaldebug - ", - "ociloadlob - ", - "ocilogoff - ", - "ocilogon - ", - "ocinewcollection - ", - "ocinewcursor - ", - "ocinewdescriptor - ", - "ocinlogon - ", - "ocinumcols - ", - "ociparse - ", - "ociplogon - ", - "ociresult - ", - "ocirollback - ", - "ocirowcount - ", - "ocisavelob - ", - "ocisavelobfile - ", - "ociserverversion - ", - "ocisetprefetch - ", - "ocistatementtype - ", - "ociwritelobtofile - ", - "octdec - ", - "odbc_autocommit - ", - "odbc_binmode - ", - "odbc_close - ", - "odbc_close_all - ", - "odbc_columnprivileges - ", - "odbc_columns - ", - "odbc_commit - ", - "odbc_connect - ", - "odbc_cursor - ", - "odbc_do - ", - "odbc_error - ", - "odbc_errormsg - ", - "odbc_exec - ", - "odbc_execute - ", - "odbc_fetch_array - ", - "odbc_fetch_into - ", - "odbc_fetch_object - ", - "odbc_fetch_row - ", - "odbc_field_len - ", - "odbc_field_name - ", - "odbc_field_num - ", - "odbc_field_precision - ", - "odbc_field_scale - ", - "odbc_field_type - ", - "odbc_foreignkeys - ", - "odbc_free_result - ", - "odbc_gettypeinfo - ", - "odbc_longreadlen - ", - "odbc_next_result - ", - "odbc_num_fields - ", - "odbc_num_rows - ", - "odbc_pconnect - ", - "odbc_prepare - ", - "odbc_primarykeys - ", - "odbc_procedurecolumns - ", - "odbc_procedures - ", - "odbc_result - ", - "odbc_result_all - ", - "odbc_rollback - ", - "odbc_setoption - ", - "odbc_specialcolumns - ", - "odbc_statistics - ", - "odbc_tableprivileges - ", - "odbc_tables - ", - "open_listen_sock - ", - "opendir - ", - "openlog - ", - "openssl_error_string - ", - "openssl_free_key - ", - "openssl_get_privatekey - ", - "openssl_get_publickey - ", - "openssl_open - ", - "openssl_pkcs7_decrypt - ", - "openssl_pkcs7_encrypt - ", - "openssl_pkcs7_sign - ", - "openssl_pkcs7_verify - ", - "openssl_seal - ", - "openssl_sign - ", - "openssl_verify - ", - "openssl_x509_checkpurpose - ", - "openssl_x509_free - ", - "openssl_x509_parse - ", - "openssl_x509_read - ", - "ora_bind - ", - "ora_close - ", - "ora_columnname - ", - "ora_columnsize - ", - "ora_columntype - ", - "ora_commit - ", - "ora_commitoff - ", - "ora_commiton - ", - "ora_do - ", - "ora_error - ", - "ora_errorcode - ", - "ora_exec - ", - "ora_fetch - ", - "ora_fetch_into - ", - "ora_getcolumn - ", - "ora_logoff - ", - "ora_logon - ", - "ora_numcols - ", - "ora_numrows - ", - "ora_open - ", - "ora_parse - ", - "ora_plogon - ", - "ora_rollback - ", - "orbit_caught_exception - ", - "orbit_exception_id - ", - "orbit_exception_value - ", - "orbit_get_repository_id - ", - "orbit_load_idl - ", - "ord - ", - "output - ", - "ovrimos_close - ", - "ovrimos_close_all - ", - "ovrimos_commit - ", - "ovrimos_connect - ", - "ovrimos_cursor - ", - "ovrimos_exec - ", - "ovrimos_execute - ", - "ovrimos_fetch_into - ", - "ovrimos_fetch_row - ", - "ovrimos_field_len - ", - "ovrimos_field_name - ", - "ovrimos_field_num - ", - "ovrimos_field_type - ", - "ovrimos_free_result - ", - "ovrimos_longreadlen - ", - "ovrimos_num_fields - ", - "ovrimos_num_rows - ", - "ovrimos_prepare - ", - "ovrimos_result - ", - "ovrimos_result_all - ", - "ovrimos_rollback - ", - "pack - ", - "parse_ini_file - ", - "parse_str - ", - "parse_url - ", - "passthru - ", - "pathinfo - ", - "pclose - ", - "pdf_add_annotation - ", - "pdf_add_bookmark - ", - "pdf_add_launchlink - ", - "pdf_add_locallink - ", - "pdf_add_note - ", - "pdf_add_outline - ", - "pdf_add_pdflink - ", - "pdf_add_thumbnail - ", - "pdf_add_weblink - ", - "pdf_arc - ", - "pdf_arcn - ", - "pdf_attach_file - ", - "pdf_begin_page - ", - "pdf_begin_pattern - ", - "pdf_begin_template - ", - "pdf_circle - ", - "pdf_clip - ", - "pdf_close - ", - "pdf_close_image - ", - "pdf_close_pdi - ", - "pdf_close_pdi_page - ", - "pdf_closepath - ", - "pdf_closepath_fill_stroke - ", - "pdf_closepath_stroke - ", - "pdf_concat - ", - "pdf_continue_text - ", - "pdf_curveto - ", - "pdf_delete - ", - "pdf_end_page - ", - "pdf_end_pattern - ", - "pdf_end_template - ", - "pdf_endpath - ", - "pdf_fill - ", - "pdf_fill_stroke - ", - "pdf_findfont - ", - "pdf_get_buffer - ", - "pdf_get_font - ", - "pdf_get_fontname - ", - "pdf_get_fontsize - ", - "pdf_get_image_height - ", - "pdf_get_image_width - ", - "pdf_get_parameter - ", - "pdf_get_pdi_parameter - ", - "pdf_get_pdi_value - ", - "pdf_get_value - ", - "pdf_initgraphics - ", - "pdf_lineto - ", - "pdf_makespotcolor - ", - "pdf_moveto - ", - "pdf_new - ", - "pdf_open - ", - "pdf_open_ccitt - ", - "pdf_open_file - ", - "pdf_open_gif - ", - "pdf_open_image - ", - "pdf_open_image_file - ", - "pdf_open_jpeg - ", - "pdf_open_memory_image - ", - "pdf_open_pdi - ", - "pdf_open_pdi_page - ", - "pdf_open_png - ", - "pdf_open_tiff - ", - "pdf_place_image - ", - "pdf_place_pdi_page - ", - "pdf_rect - ", - "pdf_restore - ", - "pdf_rotate - ", - "pdf_save - ", - "pdf_scale - ", - "pdf_set_border_color - ", - "pdf_set_border_dash - ", - "pdf_set_border_style - ", - "pdf_set_char_spacing - ", - "pdf_set_duration - ", - "pdf_set_font - ", - "pdf_set_horiz_scaling - ", - "pdf_set_info - ", - "pdf_set_info_author - ", - "pdf_set_info_creator - ", - "pdf_set_info_keywords - ", - "pdf_set_info_subject - ", - "pdf_set_info_title - ", - "pdf_set_leading - ", - "pdf_set_parameter - ", - "pdf_set_text_pos - ", - "pdf_set_text_rendering - ", - "pdf_set_text_rise - ", - "pdf_set_transition - ", - "pdf_set_value - ", - "pdf_set_word_spacing - ", - "pdf_setcolor - ", - "pdf_setdash - ", - "pdf_setflat - ", - "pdf_setfont - ", - "pdf_setgray - ", - "pdf_setgray_fill - ", - "pdf_setgray_stroke - ", - "pdf_setlinecap - ", - "pdf_setlinejoin - ", - "pdf_setlinewidth - ", - "pdf_setmatrix - ", - "pdf_setmiterlimit - ", - "pdf_setpolydash - ", - "pdf_setrgbcolor - ", - "pdf_setrgbcolor_fill - ", - "pdf_setrgbcolor_stroke - ", - "pdf_show - ", - "pdf_show_boxed - ", - "pdf_show_xy - ", - "pdf_skew - ", - "pdf_stringwidth - ", - "pdf_stroke - ", - "pdf_translate - ", - "pfpro_cleanup - ", - "pfpro_init - ", - "pfpro_process - ", - "pfpro_process_raw - ", - "pfpro_version - ", - "pfsockopen - ", - "pg_client_encoding - ", - "pg_clientencoding - ", - "pg_close - ", - "pg_cmdtuples - ", - "pg_connect - ", - "pg_dbname - ", - "pg_end_copy - ", - "pg_errormessage - ", - "pg_exec - ", - "pg_fetch_array - ", - "pg_fetch_object - ", - "pg_fetch_row - ", - "pg_fieldisnull - ", - "pg_fieldname - ", - "pg_fieldnum - ", - "pg_fieldprtlen - ", - "pg_fieldsize - ", - "pg_fieldtype - ", - "pg_freeresult - ", - "pg_getlastoid - ", - "pg_host - ", - "pg_loclose - ", - "pg_locreate - ", - "pg_loexport - ", - "pg_loimport - ", - "pg_loopen - ", - "pg_loread - ", - "pg_loreadall - ", - "pg_lounlink - ", - "pg_lowrite - ", - "pg_numfields - ", - "pg_numrows - ", - "pg_options - ", - "pg_pconnect - ", - "pg_port - ", - "pg_put_line - ", - "pg_result - ", - "pg_set_client_encoding - ", - "pg_setclientencoding - ", - "pg_trace - ", - "pg_tty - ", - "pg_untrace - ", - "php_logo_guid - ", - "php_sapi_name - ", - "php_uname - ", - "phpcredits - ", - "phpinfo - ", - "phpversion - ", - "pi - ", - "png2wbmp - ", - "popen - ", - "pos - ", - "posix_ctermid - ", - "posix_getcwd - ", - "posix_getegid - ", - "posix_geteuid - ", - "posix_getgid - ", - "posix_getgrgid - ", - "posix_getgrnam - ", - "posix_getgroups - ", - "posix_getlogin - ", - "posix_getpgid - ", - "posix_getpgrp - ", - "posix_getpid - ", - "posix_getppid - ", - "posix_getpwnam - ", - "posix_getpwuid - ", - "posix_getrlimit - ", - "posix_getsid - ", - "posix_getuid - ", - "posix_isatty - ", - "posix_kill - ", - "posix_mkfifo - ", - "posix_setegid - ", - "posix_seteuid - ", - "posix_setgid - ", - "posix_setpgid - ", - "posix_setsid - ", - "posix_setuid - ", - "posix_times - ", - "posix_ttyname - ", - "posix_uname - ", - "pow - ", - "preg_grep - ", - "preg_match - ", - "preg_match_all - ", - "preg_quote - ", - "preg_replace - ", - "preg_replace_callback - ", - "preg_split - ", - "prev - ", - "print_r - ", - "printer_abort - ", - "printer_close - ", - "printer_create_brush - ", - "printer_create_dc - ", - "printer_create_font - ", - "printer_create_pen - ", - "printer_delete_brush - ", - "printer_delete_dc - ", - "printer_delete_font - ", - "printer_delete_pen - ", - "printer_draw_bmp - ", - "printer_draw_chord - ", - "printer_draw_elipse - ", - "printer_draw_line - ", - "printer_draw_pie - ", - "printer_draw_rectangle - ", - "printer_draw_roundrect - ", - "printer_draw_text - ", - "printer_end_doc - ", - "printer_end_page - ", - "printer_get_option - ", - "printer_list - ", - "printer_logical_fontheight - ", - "printer_open - ", - "printer_select_brush - ", - "printer_select_font - ", - "printer_select_pen - ", - "printer_set_option - ", - "printer_start_doc - ", - "printer_start_page - ", - "printer_write - ", - "printf - ", - "pspell_add_to_personal - ", - "pspell_add_to_session - ", - "pspell_check - ", - "pspell_clear_session - ", - "pspell_config_create - ", - "pspell_config_ignore - ", - "pspell_config_mode - ", - "pspell_config_personal - ", - "pspell_config_repl - ", - "pspell_config_runtogether - ", - "pspell_config_save_repl - ", - "pspell_new - ", - "pspell_new_config - ", - "pspell_new_personal - ", - "pspell_save_wordlist - ", - "pspell_store_replacement - ", - "pspell_suggest - ", - "putenv - ", - "putenv - ", - "qdom_error - ", - "qdom_tree - ", - "quoted_printable_decode - ", - "quotemeta - ", - "rad2deg - ", - "rand - ", - "range - ", - "rawurldecode - ", - "rawurlencode - ", - "read - ", - "read_exif_data - ", - "readdir - ", - "readfile - ", - "readgzfile - ", - "readline - ", - "readline_add_history - ", - "readline_clear_history - ", - "readline_completion_function - ", - "readline_info - ", - "readline_list_history - ", - "readline_list_history - ", - "readline_read_history - ", - "readline_write_history - ", - "readlink - ", - "readlink - ", - "readv - ", - "realpath - ", - "realpath - ", - "recode - ", - "recode_file - ", - "recode_string - ", - "recv - ", - "recvfrom - ", - "recvmsg - ", - "register_shutdown_function - ", - "register_tick_function - ", - "remove - ", - "remove - ", - "rename - ", - "reset - ", - "restore_error_handler - ", - "rewind - ", - "rewinddir - ", - "rmdir - ", - "rotate - ", - "rotateto - ", - "rotateto - ", - "round - ", - "rsort - ", - "rtrim - ", - "satellite_caught_exception - ", - "satellite_exception_id - ", - "satellite_exception_value - ", - "satellite_get_repository_id - ", - "satellite_load_idl - ", - "save - ", - "savetofile - ", - "scale - ", - "scaleto - ", - "scaleto - ", - "select - ", - "sem_acquire - ", - "sem_get - ", - "sem_release - ", - "send - ", - "sendmsg - ", - "sendto - ", - "serialize - ", - "session_cache_limiter - ", - "session_decode - ", - "session_destroy - ", - "session_encode - ", - "session_get_cookie_params - ", - "session_id - ", - "session_is_registered - ", - "session_module_name - ", - "session_name - ", - "session_register - ", - "session_save_path - ", - "session_set_cookie_params - ", - "session_set_save_handler - ", - "session_start - ", - "session_unregister - ", - "session_unset - ", - "session_write_close - ", - "set_content - ", - "set_error_handler - ", - "set_file_buffer - ", - "set_iovec - ", - "set_magic_quotes_runtime - ", - "set_nonblock - ", - "set_socket_blocking - ", - "set_time_limit - ", - "setaction - ", - "setbackground - ", - "setbounds - ", - "setcolor - ", - "setcolor - ", - "setcookie - ", - "setdepth - ", - "setdimension - ", - "setdown - ", - "setfont - ", - "setfont - ", - "setframes - ", - "setframes - ", - "setheight - ", - "setheight - ", - "sethit - ", - "setindentation - ", - "setleftfill - ", - "setleftmargin - ", - "setline - ", - "setlinespacing - ", - "setlocale - ", - "setmargins - ", - "setmatrix - ", - "setname - ", - "setname - ", - "setover - ", - "setrate - ", - "setratio - ", - "setrightfill - ", - "setrightmargin - ", - "setsockopt - ", - "setspacing - ", - "settype - ", - "setup - ", - "shell_exec - ", - "shm_attach - ", - "shm_detach - ", - "shm_get_var - ", - "shm_put_var - ", - "shm_remove - ", - "shm_remove_var - ", - "shmop_close - ", - "shmop_delete - ", - "shmop_open - ", - "shmop_read - ", - "shmop_size - ", - "shmop_write - ", - "show_source - ", - "shuffle - ", - "shutdown - ", - "signal - ", - "similar_text - ", - "sin - ", - "sizeof - ", - "skewx - ", - "skewxto - ", - "skewxto - ", - "skewy - ", - "skewyto - ", - "skewyto - ", - "sleep - ", - "snmp_get_quick_print - ", - "snmp_set_quick_print - ", - "snmpget - ", - "snmpget - ", - "snmprealwalk - ", - "snmpset - ", - "snmpwalk - ", - "snmpwalk - ", - "snmpwalkoid - ", - "socket - ", - "socket_get_status - ", - "socket_set_blocking - ", - "socket_set_timeout - ", - "socket_set_timeout - ", - "socketpair - ", - "sort - ", - "soundex - ", - "split - ", - "spliti - ", - "sprintf - ", - "sql_regcase - ", - "sqrt - ", - "srand - ", - "sscanf - ", - "stat - ", - "str_pad - ", - "str_repeat - ", - "str_replace - ", - "strcasecmp - ", - "strchr - ", - "strcmp - ", - "strcoll - ", - "strcoll - ", - "strcspn - ", - "streammp3 - ", - "strerror - ", - "strftime - ", - "strftime - ", - "strip_tags - ", - "stripcslashes - ", - "stripslashes - ", - "stristr - ", - "strlen - ", - "strnatcasecmp - ", - "strnatcmp - ", - "strncasecmp - ", - "strncmp - ", - "strpos - ", - "strrchr - ", - "strrev - ", - "strrpos - ", - "strspn - ", - "strstr - ", - "strtok - ", - "strtolower - ", - "strtotime - ", - "strtoupper - ", - "strtr - ", - "strval - ", - - "string substr(string str, int start [, int length])\n"+ - "Returns part of a string", - - - "substr_count - ", - "substr_replace - ", - "swf_actiongeturl - ", - "swf_actiongotoframe - ", - "swf_actiongotolabel - ", - "swf_actionnextframe - ", - "swf_actionplay - ", - "swf_actionprevframe - ", - "swf_actionsettarget - ", - "swf_actionstop - ", - "swf_actiontogglequality - ", - "swf_actionwaitforframe - ", - "swf_addbuttonrecord - ", - "swf_addcolor - ", - "swf_closefile - ", - "swf_definebitmap - ", - "swf_definefont - ", - "swf_defineline - ", - "swf_definepoly - ", - "swf_definerect - ", - "swf_definetext - ", - "swf_endbutton - ", - "swf_enddoaction - ", - "swf_endshape - ", - "swf_endsymbol - ", - "swf_fontsize - ", - "swf_fontslant - ", - "swf_fonttracking - ", - "swf_getbitmapinfo - ", - "swf_getfontinfo - ", - "swf_getframe - ", - "swf_labelframe - ", - "swf_lookat - ", - "swf_modifyobject - ", - "swf_mulcolor - ", - "swf_nextid - ", - "swf_oncondition - ", - "swf_openfile - ", - "swf_ortho - ", - "swf_ortho2 - ", - "swf_perspective - ", - "swf_placeobject - ", - "swf_polarview - ", - "swf_popmatrix - ", - "swf_posround - ", - "swf_pushmatrix - ", - "swf_removeobject - ", - "swf_rotate - ", - "swf_scale - ", - "swf_setfont - ", - "swf_setframe - ", - "swf_shapearc - ", - "swf_shapecurveto - ", - "swf_shapecurveto3 - ", - "swf_shapefillbitmapclip - ", - "swf_shapefillbitmaptile - ", - "swf_shapefilloff - ", - "swf_shapefillsolid - ", - "swf_shapelinesolid - ", - "swf_shapelineto - ", - "swf_shapemoveto - ", - "swf_showframe - ", - "swf_startbutton - ", - "swf_startdoaction - ", - "swf_startshape - ", - "swf_startsymbol - ", - "swf_textwidth - ", - "swf_translate - ", - "swf_viewport - ", - "swfaction - ", - "swfbitmap - ", - "swfbutton - ", - "swfbutton_keypress - ", - "swffill - ", - "swffont - ", - "swfgradient - ", - "swfmorph - ", - "swfmovie - ", - "swfshape - ", - "swfsprite - ", - "swftext - ", - "swftextfield - ", - "sybase_affected_rows - ", - "sybase_affected_rows - ", - "sybase_close - ", - "sybase_close - ", - "sybase_connect - ", - "sybase_connect - ", - "sybase_data_seek - ", - "sybase_data_seek - ", - "sybase_fetch_array - ", - "sybase_fetch_array - ", - "sybase_fetch_field - ", - "sybase_fetch_field - ", - "sybase_fetch_object - ", - "sybase_fetch_object - ", - "sybase_fetch_row - ", - "sybase_fetch_row - ", - "sybase_field_seek - ", - "sybase_field_seek - ", - "sybase_free_result - ", - "sybase_free_result - ", - "sybase_get_last_message - ", - "sybase_get_last_message - ", - "sybase_min_client_severity - ", - "sybase_min_error_severity - ", - "sybase_min_message_severity - ", - "sybase_min_server_severity - ", - "sybase_num_fields - ", - "sybase_num_fields - ", - "sybase_num_rows - ", - "sybase_num_rows - ", - "sybase_pconnect - ", - "sybase_pconnect - ", - "sybase_query - ", - "sybase_query - ", - "sybase_result - ", - "sybase_result - ", - "sybase_select_db - ", - "sybase_select_db - ", - "symlink - ", - "symlink - ", - "syslog - ", - "system - ", - "tan - ", - "tempnam - ", - "textdomain - ", - "time - ", - "tmpfile - ", - "touch - ", - "trigger_error - ", - "trim - ", - "uasort - ", - "ucfirst - ", - "ucwords - ", - "udm_add_search_limit - ", - "udm_alloc_agent - ", - "udm_api_version - ", - "udm_clear_search_limits - ", - "udm_errno - ", - "udm_error - ", - "udm_find - ", - "udm_free_agent - ", - "udm_free_ispell_data - ", - "udm_free_res - ", - "udm_get_doc_count - ", - "udm_get_res_field - ", - "udm_get_res_param - ", - "udm_load_ispell_data - ", - "udm_set_agent_param - ", - "uksort - ", - "umask - ", - "uniqid - ", - "unixtojd - ", - "unlink - ", - "unpack - ", - "unregister_tick_function - ", - "unserialize - ", - "urldecode - ", - "urlencode - ", - "user_error - ", - "usleep - ", - "usort - ", - "utf8_decode - ", - "utf8_encode - ", - "var_dump - ", - "velocis_autocommit - ", - "velocis_close - ", - "velocis_commit - ", - "velocis_connect - ", - "velocis_exec - ", - "velocis_fetch - ", - "velocis_fieldname - ", - "velocis_fieldnum - ", - "velocis_freeresult - ", - "velocis_off_autocommit - ", - "velocis_result - ", - "velocis_rollback - ", - "virtual - ", - "vpopmail_add_alias_domain - ", - "vpopmail_add_alias_domain_ex - ", - "vpopmail_add_domain - ", - "vpopmail_add_domain_ex - ", - "vpopmail_add_user - ", - "vpopmail_auth_user - ", - "vpopmail_del_domain - ", - "vpopmail_del_domain_ex - ", - "vpopmail_del_user - ", - "vpopmail_error - ", - "vpopmail_passwd - ", - "vpopmail_set_user_quota - ", - "wddx_add_vars - ", - "wddx_deserialize - ", - "wddx_packet_end - ", - "wddx_packet_start - ", - "wddx_serialize_value - ", - "wddx_serialize_vars - ", - "wordwrap - ", - "write - ", - "writev - ", - "xml_error_string - ", - "xml_get_current_byte_index - ", - "xml_get_current_column_number - ", - "xml_get_current_line_number - ", - "xml_get_error_code - ", - "xml_parse - ", - "xml_parse_into_struct - ", - "xml_parser_create - ", - "xml_parser_create_ns - ", - "xml_parser_free - ", - "xml_parser_get_option - ", - "xml_parser_set_option - ", - "xml_set_character_data_handler - ", - "xml_set_default_handler - ", - "xml_set_element_handler - ", - "xml_set_end_namespace_decl_handler - ", - "xml_set_external_entity_ref_handler - ", - "xml_set_notation_decl_handler - ", - "xml_set_object - ", - "xml_set_processing_instruction_handler - ", - "xml_set_start_namespace_decl_handler - ", - "xml_set_unparsed_entity_decl_handler - ", - "xmldoc - ", - "xmldocfile - ", - "xmltree - ", - "xpath_eval - ", - "xpath_eval_expression - ", - "xptr_eval - ", - "xslt_closelog - ", - "xslt_create - ", - "xslt_errno - ", - "xslt_error - ", - "xslt_fetch_result - ", - "xslt_free - ", - "xslt_openlog - ", - "xslt_output_begintransform - ", - "xslt_output_endtransform - ", - "xslt_process - ", - "xslt_run - ", - "xslt_set_base - ", - "xslt_set_encoding - ", - "xslt_set_error_handler - ", - "xslt_set_sax_handler - ", - "xslt_set_scheme_handler - ", - "xslt_transform - ", - "yaz_addinfo - ", - "yaz_ccl_conf - ", - "yaz_ccl_parse - ", - "yaz_close - ", - "yaz_connect - ", - "yaz_database - ", - "yaz_element - ", - "yaz_errno - ", - "yaz_error - ", - "yaz_hits - ", - "yaz_itemorder - ", - "yaz_present - ", - "yaz_range - ", - "yaz_record - ", - "yaz_scan - ", - "yaz_scan_result - ", - "yaz_search - ", - "yaz_syntax - ", - "yaz_wait - ", - "yp_all - ", - "yp_cat - ", - "yp_err_string - ", - "yp_errno - ", - "yp_first - ", - "yp_get_default_domain - ", - "yp_master - ", - "yp_match - ", - "yp_next - ", - "yp_order - ", - "zend_logo_guid - ", - "zend_test_func - ", - "zend_version - ", - "zzip_close - ", - "zzip_closedir - ", - "zzip_entry_compressedsize - ", - "zzip_entry_compressionmethod - ", - "zzip_entry_filesize - ", - "zzip_entry_name - ", - "zzip_open - ", - "zzip_opendir - ", - "zzip_read - ", - "zzip_readdir - " }; - -} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java new file mode 100644 index 0000000..a478a01 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPKeyword.java @@ -0,0 +1,29 @@ +package net.sourceforge.phpeclipse.phpeditor.php; + +/** + * @author Choochter + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class PHPKeyword extends PHPElement{ + private int tokenval; + public void settokenval(String tokenval) { this.tokenval = Integer.parseInt(tokenval);} + public void settokenval(int tokenval) { this.tokenval = tokenval;} + public int gettokenval() { return this.tokenval; } + + public PHPKeyword(String Name, String Description, String tokenval){ + super(Name, Description); + if ((tokenval == null) || (tokenval.equals(""))) + { + //if there is not a tokenval, then not implemented. + settokenval(-1); + } + else { + settokenval(tokenval); + } + //settokenval(tokenval); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java new file mode 100644 index 0000000..c4fb644 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPType.java @@ -0,0 +1,15 @@ +package net.sourceforge.phpeclipse.phpeditor.php; + +/** + * @author Choochter + * + * To change this generated comment edit the template variable "typecomment": + * Window>Preferences>Java>Templates. + * To enable and disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class PHPType extends PHPElement{ + public PHPType(String Name, String Description){ + super(Name, Description); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/phpsyntax.xml b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/phpsyntax.xml new file mode 100644 index 0000000..51ee93c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/phpsyntax.xml @@ -0,0 +1,2416 @@ + + + +=================================================== +*Below this are the various PHP-specific functions * +=================================================== + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +================================================== +*Below this are the various PHP-specific keywords * +================================================== + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +========================================================= +*Below this are the various PHP-specific variable types * +========================================================= + + + + + + + + + + +=================================================== +*Below this are the various PHP-specific constants * +=================================================== + + + + + + + + + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLColorProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLColorProvider.java index f8fa9b0..5bb0a3f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLColorProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/HTMLColorProvider.java @@ -28,7 +28,7 @@ public class HTMLColorProvider { public static final RGB KEYWORD= new RGB(127, 0, 85); public static final RGB VARIABLE= new RGB(127, 159, 191); public static final RGB TYPE= new RGB(0, 0, 128); - public static final RGB STRING= new RGB(0, 128, 0); + public static final RGB STRING= new RGB(42, 0, 255); public static final RGB DEFAULT= new RGB(0, 0, 0); public static final RGB HTML_DEFAULT= new RGB(0, 128, 128); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java index 8e65c5f..38d0238 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/util/PHPColorProvider.java @@ -14,47 +14,50 @@ package net.sourceforge.phpeclipse.phpeditor.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; + import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; - /** * Manager for colors used in the Java editor */ public class PHPColorProvider { - public static final RGB MULTI_LINE_COMMENT= new RGB(63, 127, 95); - public static final RGB SINGLE_LINE_COMMENT= new RGB(63, 127, 95); - public static final RGB KEYWORD= new RGB(127, 0, 85); - public static final RGB VARIABLE= new RGB(127, 159, 191); - public static final RGB FUNCTION_NAME= new RGB(127, 127, 159); - public static final RGB STRING= new RGB(42, 0, 255); - public static final RGB DEFAULT= new RGB(0, 0, 0); - - public static final RGB LINKED_POSITION_COLOR= new RGB(0, 0, 0); - public static final RGB LINE_NUMBER_COLOR= new RGB(0, 0, 0); - public static final RGB BACKGROUND_COLOR= new RGB(255, 255, 255); - - protected Map fColorTable= new HashMap(10); - - /** - * Release all of the color resources held onto by the receiver. - */ - public void dispose() { - Iterator e= fColorTable.values().iterator(); - while (e.hasNext()) - ((Color) e.next()).dispose(); - } - - /** - * Return the Color that is stored in the Color table as rgb. - */ - public Color getColor(RGB rgb) { - Color color= (Color) fColorTable.get(rgb); - if (color == null) { - color= new Color(Display.getCurrent(), rgb); - fColorTable.put(rgb, color); - } - return color; - } + public static final RGB MULTI_LINE_COMMENT = new RGB(63, 127, 95); + public static final RGB SINGLE_LINE_COMMENT = new RGB(63, 127, 95); + public static final RGB KEYWORD = new RGB(127, 0, 85); + public static final RGB VARIABLE = new RGB(127, 159, 191); + public static final RGB FUNCTION_NAME = new RGB(127, 127, 159); + public static final RGB STRING = new RGB(42, 0, 255); + public static final RGB DEFAULT = new RGB(0, 0, 0); + public static final RGB TYPE = new RGB(127, 0, 85); + public static final RGB CONSTANT = new RGB(127, 0, 85); + public static final RGB BACKGROUND = new RGB(255, 255, 255); + + public static final RGB LINKED_POSITION_COLOR = new RGB(0, 0, 0); + + public static final RGB LINE_NUMBER_COLOR = new RGB(0, 0, 0); + public static final RGB BACKGROUND_COLOR = new RGB(255, 255, 255); + protected Map fColorTable = new HashMap(10); + + /** + * Release all of the color resources held onto by the receiver. + */ + public void dispose() { + Iterator e = fColorTable.values().iterator(); + while (e.hasNext()) + ((Color) e.next()).dispose(); + } + + /** + * Return the Color that is stored in the Color table as rgb. + */ + public Color getColor(RGB rgb) { + Color color = (Color) fColorTable.get(rgb); + if (color == null) { + color = new Color(Display.getCurrent(), rgb); + fColorTable.put(rgb, color); + } + return color; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java new file mode 100644 index 0000000..af121ae --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/ColorEditor.java @@ -0,0 +1,116 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ +package net.sourceforge.phpeclipse.preferences; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.ColorDialog; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; + +import org.eclipse.jface.resource.JFaceResources; + +/** + * A "button" of a certain color determined by the color picker. + */ +public class ColorEditor { + + private Point fExtent; + private Image fImage; + private RGB fColorValue; + private Color fColor; + private Button fButton; + + public ColorEditor(Composite parent) { + + fButton= new Button(parent, SWT.PUSH); + fExtent= computeImageSize(parent); + fImage= new Image(parent.getDisplay(), fExtent.x, fExtent.y); + + GC gc= new GC(fImage); + gc.setBackground(fButton.getBackground()); + gc.fillRectangle(0, 0, fExtent.x, fExtent.y); + gc.dispose(); + + fButton.setImage(fImage); + fButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + ColorDialog colorDialog= new ColorDialog(fButton.getShell()); + colorDialog.setRGB(fColorValue); + RGB newColor = colorDialog.open(); + if (newColor != null) { + fColorValue= newColor; + updateColorImage(); + } + } + }); + + fButton.addDisposeListener(new DisposeListener() { + public void widgetDisposed(DisposeEvent event) { + if (fImage != null) { + fImage.dispose(); + fImage= null; + } + if (fColor != null) { + fColor.dispose(); + fColor= null; + } + } + }); + } + + public RGB getColorValue() { + return fColorValue; + } + + public void setColorValue(RGB rgb) { + fColorValue= rgb; + updateColorImage(); + } + + public Button getButton() { + return fButton; + } + + protected void updateColorImage() { + + Display display= fButton.getDisplay(); + + GC gc= new GC(fImage); + gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); + gc.drawRectangle(0, 2, fExtent.x - 1, fExtent.y - 4); + + if (fColor != null) + fColor.dispose(); + + fColor= new Color(display, fColorValue); + gc.setBackground(fColor); + gc.fillRectangle(1, 3, fExtent.x - 2, fExtent.y - 5); + gc.dispose(); + + fButton.setImage(fImage); + } + + protected Point computeImageSize(Control window) { + GC gc= new GC(window); + Font f= JFaceResources.getFontRegistry().get(JFaceResources.DEFAULT_FONT); + gc.setFont(f); + int height= gc.getFontMetrics().getHeight(); + gc.dispose(); + Point p= new Point(height * 3 - 6, height); + return p; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java new file mode 100644 index 0000000..11032cf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/OverlayPreferenceStore.java @@ -0,0 +1,443 @@ +/* + * (c) Copyright IBM Corp. 2000, 2001. + * All Rights Reserved. + */ + +package net.sourceforge.phpeclipse.preferences; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; + +/** + * An overlaying preference store. + */ +public class OverlayPreferenceStore implements IPreferenceStore { + + public static final class TypeDescriptor { + private TypeDescriptor() { + } + }; + + public static final TypeDescriptor BOOLEAN = new TypeDescriptor(); + public static final TypeDescriptor DOUBLE = new TypeDescriptor(); + public static final TypeDescriptor FLOAT = new TypeDescriptor(); + public static final TypeDescriptor INT = new TypeDescriptor(); + public static final TypeDescriptor LONG = new TypeDescriptor(); + public static final TypeDescriptor STRING = new TypeDescriptor(); + + public static class OverlayKey { + + TypeDescriptor fDescriptor; + String fKey; + + public OverlayKey(TypeDescriptor descriptor, String key) { + fDescriptor = descriptor; + fKey = key; + } + }; + + private class PropertyListener implements IPropertyChangeListener { + + /* + * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) + */ + public void propertyChange(PropertyChangeEvent event) { + OverlayKey key = findOverlayKey(event.getProperty()); + if (key != null) + propagateProperty(fParent, key, fStore); + } + }; + + private IPreferenceStore fParent; + private IPreferenceStore fStore; + private OverlayKey[] fOverlayKeys; + + private PropertyListener fPropertyListener; + + public OverlayPreferenceStore(IPreferenceStore parent, OverlayKey[] overlayKeys) { + fParent = parent; + fOverlayKeys = overlayKeys; + fStore = new PreferenceStore(); + } + + private OverlayKey findOverlayKey(String key) { + for (int i = 0; i < fOverlayKeys.length; i++) { + if (fOverlayKeys[i].fKey.equals(key)) + return fOverlayKeys[i]; + } + return null; + } + + private boolean covers(String key) { + return (findOverlayKey(key) != null); + } + + private void propagateProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target) { + + if (orgin.isDefault(key.fKey)) { + if (!target.isDefault(key.fKey)) + target.setToDefault(key.fKey); + return; + } + + TypeDescriptor d = key.fDescriptor; + if (BOOLEAN == d) { + + boolean originValue = orgin.getBoolean(key.fKey); + boolean targetValue = target.getBoolean(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (DOUBLE == d) { + + double originValue = orgin.getDouble(key.fKey); + double targetValue = target.getDouble(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (FLOAT == d) { + + float originValue = orgin.getFloat(key.fKey); + float targetValue = target.getFloat(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (INT == d) { + + int originValue = orgin.getInt(key.fKey); + int targetValue = target.getInt(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (LONG == d) { + + long originValue = orgin.getLong(key.fKey); + long targetValue = target.getLong(key.fKey); + if (targetValue != originValue) + target.setValue(key.fKey, originValue); + + } else if (STRING == d) { + + String originValue = orgin.getString(key.fKey); + String targetValue = target.getString(key.fKey); + if (targetValue != null && originValue != null && !targetValue.equals(originValue)) + target.setValue(key.fKey, originValue); + + } + } + + public void propagate() { + for (int i = 0; i < fOverlayKeys.length; i++) + propagateProperty(fStore, fOverlayKeys[i], fParent); + } + + private void loadProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target, boolean forceInitialization) { + TypeDescriptor d = key.fDescriptor; + if (BOOLEAN == d) { + + if (forceInitialization) + target.setValue(key.fKey, true); + target.setValue(key.fKey, orgin.getBoolean(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultBoolean(key.fKey)); + + } else if (DOUBLE == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1.0D); + target.setValue(key.fKey, orgin.getDouble(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultDouble(key.fKey)); + + } else if (FLOAT == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1.0F); + target.setValue(key.fKey, orgin.getFloat(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultFloat(key.fKey)); + + } else if (INT == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1); + target.setValue(key.fKey, orgin.getInt(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultInt(key.fKey)); + + } else if (LONG == d) { + + if (forceInitialization) + target.setValue(key.fKey, 1L); + target.setValue(key.fKey, orgin.getLong(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultLong(key.fKey)); + + } else if (STRING == d) { + + if (forceInitialization) + target.setValue(key.fKey, "1"); //$NON-NLS-1$ + target.setValue(key.fKey, orgin.getString(key.fKey)); + target.setDefault(key.fKey, orgin.getDefaultString(key.fKey)); + + } + } + + public void load() { + for (int i = 0; i < fOverlayKeys.length; i++) + loadProperty(fParent, fOverlayKeys[i], fStore, true); + } + + public void loadDefaults() { + for (int i = 0; i < fOverlayKeys.length; i++) + setToDefault(fOverlayKeys[i].fKey); + } + + public void start() { + if (fPropertyListener == null) { + fPropertyListener = new PropertyListener(); + fParent.addPropertyChangeListener(fPropertyListener); + } + } + + public void stop() { + if (fPropertyListener != null) { + fParent.removePropertyChangeListener(fPropertyListener); + fPropertyListener = null; + } + } + + /* + * @see IPreferenceStore#addPropertyChangeListener(IPropertyChangeListener) + */ + public void addPropertyChangeListener(IPropertyChangeListener listener) { + fStore.addPropertyChangeListener(listener); + } + + /* + * @see IPreferenceStore#removePropertyChangeListener(IPropertyChangeListener) + */ + public void removePropertyChangeListener(IPropertyChangeListener listener) { + fStore.removePropertyChangeListener(listener); + } + + /* + * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object) + */ + public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { + fStore.firePropertyChangeEvent(name, oldValue, newValue); + } + + /* + * @see IPreferenceStore#contains(String) + */ + public boolean contains(String name) { + return fStore.contains(name); + } + + /* + * @see IPreferenceStore#getBoolean(String) + */ + public boolean getBoolean(String name) { + return fStore.getBoolean(name); + } + + /* + * @see IPreferenceStore#getDefaultBoolean(String) + */ + public boolean getDefaultBoolean(String name) { + return fStore.getDefaultBoolean(name); + } + + /* + * @see IPreferenceStore#getDefaultDouble(String) + */ + public double getDefaultDouble(String name) { + return fStore.getDefaultDouble(name); + } + + /* + * @see IPreferenceStore#getDefaultFloat(String) + */ + public float getDefaultFloat(String name) { + return fStore.getDefaultFloat(name); + } + + /* + * @see IPreferenceStore#getDefaultInt(String) + */ + public int getDefaultInt(String name) { + return fStore.getDefaultInt(name); + } + + /* + * @see IPreferenceStore#getDefaultLong(String) + */ + public long getDefaultLong(String name) { + return fStore.getDefaultLong(name); + } + + /* + * @see IPreferenceStore#getDefaultString(String) + */ + public String getDefaultString(String name) { + return fStore.getDefaultString(name); + } + + /* + * @see IPreferenceStore#getDouble(String) + */ + public double getDouble(String name) { + return fStore.getDouble(name); + } + + /* + * @see IPreferenceStore#getFloat(String) + */ + public float getFloat(String name) { + return fStore.getFloat(name); + } + + /* + * @see IPreferenceStore#getInt(String) + */ + public int getInt(String name) { + return fStore.getInt(name); + } + + /* + * @see IPreferenceStore#getLong(String) + */ + public long getLong(String name) { + return fStore.getLong(name); + } + + /* + * @see IPreferenceStore#getString(String) + */ + public String getString(String name) { + return fStore.getString(name); + } + + /* + * @see IPreferenceStore#isDefault(String) + */ + public boolean isDefault(String name) { + return fStore.isDefault(name); + } + + /* + * @see IPreferenceStore#needsSaving() + */ + public boolean needsSaving() { + return fStore.needsSaving(); + } + + /* + * @see IPreferenceStore#putValue(String, String) + */ + public void putValue(String name, String value) { + if (covers(name)) + fStore.putValue(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, double) + */ + public void setDefault(String name, double value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, float) + */ + public void setDefault(String name, float value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, int) + */ + public void setDefault(String name, int value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, long) + */ + public void setDefault(String name, long value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, String) + */ + public void setDefault(String name, String value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setDefault(String, boolean) + */ + public void setDefault(String name, boolean value) { + if (covers(name)) + fStore.setDefault(name, value); + } + + /* + * @see IPreferenceStore#setToDefault(String) + */ + public void setToDefault(String name) { + fStore.setToDefault(name); + } + + /* + * @see IPreferenceStore#setValue(String, double) + */ + public void setValue(String name, double value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, float) + */ + public void setValue(String name, float value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, int) + */ + public void setValue(String name, int value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, long) + */ + public void setValue(String name, long value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, String) + */ + public void setValue(String name, String value) { + if (covers(name)) + fStore.setValue(name, value); + } + + /* + * @see IPreferenceStore#setValue(String, boolean) + */ + public void setValue(String name, boolean value) { + if (covers(name)) + fStore.setValue(name, value); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java index dfda1e6..6088388 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPPreferencesMessages.java @@ -4,33 +4,43 @@ import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; +import org.eclipse.jface.preference.IPreferenceStore; + +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + public class PHPPreferencesMessages { + static IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + static String resourceBundleName; + static { + resourceBundleName = store.getString(IPreferenceConstants.RESOURCE_BUNDLE); + } + private static ResourceBundle resourceBundle = ResourceBundle.getBundle(resourceBundleName); + + private PHPPreferencesMessages() { + } + + public static String getString(String key) { + try { + return resourceBundle.getString(key); + } catch (MissingResourceException e) { + return '!' + key + '!'; + } + } + public static void setResourceBundle(String newResourceBundle) { + resourceBundle = ResourceBundle.getBundle(newResourceBundle); + } + + public static String getFormattedString(String key, String arg) { + return getFormattedString(key, new String[] { arg }); + } + + public static String getFormattedString(String key, String[] args) { + return MessageFormat.format(getString(key), args); + } - private static final String RESOURCE_BUNDLE= "net.sourceforge.phpeclipse.preferences.PHPPreferencesMessages";//$NON-NLS-1$ - - private static ResourceBundle resourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private PHPPreferencesMessages() { - } - - public static String getString(String key) { - try { - return resourceBundle.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } - - public static String getFormattedString(String key, String arg) { - return getFormattedString(key, new String[] { arg }); - } - - public static String getFormattedString(String key, String[] args) { - return MessageFormat.format(getString(key), args); - } - - public static ResourceBundle getResourceBundle() { - return resourceBundle; - } + public static ResourceBundle getResourceBundle() { + return resourceBundle; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java index 98d1cff..618e810 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectLibraryPage.java @@ -24,124 +24,129 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.ISharedImages; -import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbench; import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.resourcesview.PHPProject; +import net.sourceforge.phpeclipse.resourcesview.PHPProject; public class PHPProjectLibraryPage { - protected PHPProject workingProject; + protected PHPProject workingProject; - protected PHPProjectLibraryPage(PHPProject theWorkingProject) { - super(); - workingProject = theWorkingProject; - } - - protected Control getControl(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(new FillLayout()); - - Table projectsTable = new Table(composite, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); - projectsTable.setHeaderVisible(false); - projectsTable.setLinesVisible(false); - projectsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); - - TableColumn tableColumn = new TableColumn(projectsTable, SWT.NONE); - tableColumn.setWidth(200); - tableColumn.setText(PHPPreferencesMessages.getString("PHPProjectLibraryPage.project")); //$NON-NLS-1$ - - CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer(projectsTable); - projectsTableViewer.addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event) { - projectCheckedUnchecked(event); - } - }); - - projectsTableViewer.setContentProvider(getContentProvider()); - projectsTableViewer.setLabelProvider(getLabelProvider()); - - projectsTableViewer.setInput(getWorkspaceProjects()); - projectsTableViewer.setCheckedElements(workingProject.getReferencedProjects().toArray()); - - return composite; - } - - protected void projectCheckedUnchecked(CheckStateChangedEvent event) { - IProject checkEventProject = (IProject) event.getElement(); - if (event.getChecked()) - getWorkingProject().addLoadPathEntry(checkEventProject); - else - getWorkingProject().removeLoadPathEntry(checkEventProject); - } - - protected PHPProject getWorkingProject() { - return workingProject; - } - - protected List getWorkspaceProjects() { - IWorkspaceRoot root = PHPeclipsePlugin.getWorkspace().getRoot(); - return Arrays.asList(root.getProjects()); - } - - protected ITableLabelProvider getLabelProvider() { - ITableLabelProvider labelProvider = new ITableLabelProvider() { - public Image getColumnImage(Object element, int columnIndex) { - IWorkbench workbench= PHPeclipsePlugin.getDefault().getWorkbench(); - return workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); - } - - public String getColumnText(Object element, int columnIndex) { - if (element instanceof IProject) - return ((IProject) element).getName(); - - return PHPPreferencesMessages.getString("PHPProjectLibraryPage.elementNotIProject"); //$NON-NLS-1$ - } - - public void addListener(ILabelProviderListener listener) {} - - public void dispose() {} - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) {} - }; - - return labelProvider; - } - - protected IContentProvider getContentProvider() { - IStructuredContentProvider contentProvider = new IStructuredContentProvider() { - protected List phpProjects; - - public Object[] getElements(Object inputElement) { - return phpProjects.toArray(); - } - - public void dispose() {} - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - phpProjects = new ArrayList(); - - if (!(newInput instanceof List)) - return; - - Iterator workspaceProjectsIterator = ((List) newInput).iterator(); - while (workspaceProjectsIterator.hasNext()) { - Object anObject = workspaceProjectsIterator.next(); - if (anObject instanceof IProject) { - IProject project = (IProject) anObject; - if (project.getName() != workingProject.getProject().getName()) { - try { - if (project.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) - phpProjects.add(project); - } catch (CoreException e) {} - } - } - } - } - }; - - return contentProvider; - } + protected PHPProjectLibraryPage(PHPProject theWorkingProject) { + super(); + workingProject = theWorkingProject; + } + + protected Control getControl(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new FillLayout()); + + Table projectsTable = new Table(composite, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION); + projectsTable.setHeaderVisible(false); + projectsTable.setLinesVisible(false); + projectsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); + + TableColumn tableColumn = new TableColumn(projectsTable, SWT.NONE); + tableColumn.setWidth(200); + tableColumn.setText(PHPPreferencesMessages.getString("PHPProjectLibraryPage.project")); //$NON-NLS-1$ + + CheckboxTableViewer projectsTableViewer = new CheckboxTableViewer(projectsTable); + projectsTableViewer.addCheckStateListener(new ICheckStateListener() { + public void checkStateChanged(CheckStateChangedEvent event) { + projectCheckedUnchecked(event); + } + }); + + projectsTableViewer.setContentProvider(getContentProvider()); + projectsTableViewer.setLabelProvider(getLabelProvider()); + + projectsTableViewer.setInput(getWorkspaceProjects()); + projectsTableViewer.setCheckedElements(workingProject.getReferencedProjects().toArray()); + + return composite; + } + + protected void projectCheckedUnchecked(CheckStateChangedEvent event) { + IProject checkEventProject = (IProject) event.getElement(); + if (event.getChecked()) + getWorkingProject().addLoadPathEntry(checkEventProject); + else + getWorkingProject().removeLoadPathEntry(checkEventProject); + } + + protected PHPProject getWorkingProject() { + return workingProject; + } + + protected List getWorkspaceProjects() { + IWorkspaceRoot root = PHPeclipsePlugin.getWorkspace().getRoot(); + return Arrays.asList(root.getProjects()); + } + + protected ITableLabelProvider getLabelProvider() { + ITableLabelProvider labelProvider = new ITableLabelProvider() { + public Image getColumnImage(Object element, int columnIndex) { + IWorkbench workbench = PHPeclipsePlugin.getDefault().getWorkbench(); + return workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); + } + + public String getColumnText(Object element, int columnIndex) { + if (element instanceof IProject) + return ((IProject) element).getName(); + + return PHPPreferencesMessages.getString("PHPProjectLibraryPage.elementNotIProject"); //$NON-NLS-1$ + } + + public void addListener(ILabelProviderListener listener) { + } + + public void dispose() { + } + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + public void removeListener(ILabelProviderListener listener) { + } + }; + + return labelProvider; + } + + protected IContentProvider getContentProvider() { + IStructuredContentProvider contentProvider = new IStructuredContentProvider() { + protected List phpProjects; + + public Object[] getElements(Object inputElement) { + return phpProjects.toArray(); + } + + public void dispose() { + } + + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + phpProjects = new ArrayList(); + + if (!(newInput instanceof List)) + return; + + Iterator workspaceProjectsIterator = ((List) newInput).iterator(); + while (workspaceProjectsIterator.hasNext()) { + Object anObject = workspaceProjectsIterator.next(); + if (anObject instanceof IProject) { + IProject project = (IProject) anObject; + if (project.getName() != workingProject.getProject().getName()) { + try { + if (project.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) + phpProjects.add(project); + } catch (CoreException e) { + } + } + } + } + } + }; + + return contentProvider; + } } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java index fa07e17..55e6f90 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/preferences/PHPProjectPropertyPage.java @@ -20,78 +20,78 @@ import org.eclipse.ui.IWorkbenchPropertyPage; import org.eclipse.ui.dialogs.PropertyPage; public class PHPProjectPropertyPage extends PropertyPage implements IWorkbenchPropertyPage { - protected PHPProjectLibraryPage projectsPage; - protected PHPProject workingProject; - - public PHPProjectPropertyPage() { - } - - protected Control createContents(Composite parent) { - noDefaultAndApplyButton(); - - workingProject = getPHPProject(); - if (workingProject == null || !workingProject.getProject().isOpen()) - return createClosedProjectPageContents(parent); - - return createProjectPageContents(parent); - } - - protected PHPProject getPHPProject() { - IAdaptable selectedElement = getElement(); - if (selectedElement == null) - return null; - - if (selectedElement instanceof PHPProject) - return (PHPProject) selectedElement; - - if (selectedElement instanceof IProject) { - IProject simpleProject = (IProject) selectedElement; - try { - if (simpleProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { - PHPProject phpProject = new PHPProject(); - phpProject.setProject(simpleProject); - return phpProject; - } - } catch(CoreException e) { - PHPeclipsePlugin.log(e); - } - } - - return null; - } - - protected Control createClosedProjectPageContents(Composite parent) { - Label label = new Label(parent, SWT.NONE); - label.setText(PHPPreferencesMessages.getString("PHPProjectPropertyPage.phpProjectClosed")); //$NON-NLS-1$ - - return label; - } - - protected Control createProjectPageContents(Composite parent) { - TabFolder tabFolder = new TabFolder(parent, SWT.NONE); - tabFolder.setLayout(new GridLayout()); - tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); - tabFolder.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - //tabChanged(e.item); - } - }); - - projectsPage = new PHPProjectLibraryPage(workingProject); - TabItem tabItem = new TabItem(tabFolder, SWT.NONE); - tabItem.setText(PHPPreferencesMessages.getString("PHPProjectLibraryPage.tabName")); //$NON-NLS-1$ -// tabItem.setData(projectsPage); - tabItem.setControl(projectsPage.getControl(tabFolder)); - - return tabFolder; - } - public boolean performOk() { - try { - projectsPage.getWorkingProject().save(); - } catch (CoreException e) { + protected PHPProjectLibraryPage projectsPage; + protected PHPProject workingProject; + + public PHPProjectPropertyPage() { + } + + protected Control createContents(Composite parent) { + noDefaultAndApplyButton(); + + workingProject = getPHPProject(); + if (workingProject == null || !workingProject.getProject().isOpen()) + return createClosedProjectPageContents(parent); + + return createProjectPageContents(parent); + } + + protected PHPProject getPHPProject() { + IAdaptable selectedElement = getElement(); + if (selectedElement == null) + return null; + + if (selectedElement instanceof PHPProject) + return (PHPProject) selectedElement; + + if (selectedElement instanceof IProject) { + IProject simpleProject = (IProject) selectedElement; + try { + if (simpleProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) { + PHPProject phpProject = new PHPProject(); + phpProject.setProject(simpleProject); + return phpProject; + } + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + } + + return null; + } + + protected Control createClosedProjectPageContents(Composite parent) { + Label label = new Label(parent, SWT.NONE); + label.setText(PHPPreferencesMessages.getString("PHPProjectPropertyPage.phpProjectClosed")); //$NON-NLS-1$ + + return label; + } + + protected Control createProjectPageContents(Composite parent) { + TabFolder tabFolder = new TabFolder(parent, SWT.NONE); + tabFolder.setLayout(new GridLayout()); + tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); + tabFolder.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + //tabChanged(e.item); + } + }); + + projectsPage = new PHPProjectLibraryPage(workingProject); + TabItem tabItem = new TabItem(tabFolder, SWT.NONE); + tabItem.setText(PHPPreferencesMessages.getString("PHPProjectLibraryPage.tabName")); //$NON-NLS-1$ + // tabItem.setData(projectsPage); + tabItem.setControl(projectsPage.getControl(tabFolder)); + + return tabFolder; + } + public boolean performOk() { + try { + projectsPage.getWorkingProject().save(); + } catch (CoreException e) { PHPeclipsePlugin.log(e); - } - return super.performOk(); - } + } + return super.performOk(); + } } -- 1.7.1 From ad828400fd91ae0cb6ead3d98fbf4633c670713c Mon Sep 17 00:00:00 2001 From: khartlage Date: Mon, 27 Jan 2003 18:33:54 +0000 Subject: [PATCH 02/16] added "icons/obj16/impc_obj.gif" for includes in the outline view --- .../icons/obj16/impc_obj.gif | Bin 0 -> 97 bytes .../sourceforge/phpdt/internal/ui/PHPUiImages.java | 2 +- 2 files changed, 1 insertions(+), 1 deletions(-) create mode 100644 net.sourceforge.phpeclipse/icons/obj16/impc_obj.gif diff --git a/net.sourceforge.phpeclipse/icons/obj16/impc_obj.gif b/net.sourceforge.phpeclipse/icons/obj16/impc_obj.gif new file mode 100644 index 0000000000000000000000000000000000000000..e5b867569acbcda35f6124bb66561fd092ccb9a3 GIT binary patch literal 97 zcmZ?wbhEHb6krfwSi}GX{}~t>?CtkAG&ID=$AkF)fg%iwKUo+V7}yweKuSPr8JN{F tcHPm_lM+Z_UKBO8`QBLr0hh$46-twy&CJV=+>>$V(g%&*7IPUGtO58f9xea? literal 0 HcmV?d00001 diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java index 2b5181b..636b54e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUiImages.java @@ -34,7 +34,7 @@ public class PHPUiImages { public static final String IMG_CLASS = NAME_PREFIX + "class_obj.gif"; public static final String IMG_BUILTIN = NAME_PREFIX + "builtin_obj.gif"; public static final String IMG_FUN = NAME_PREFIX + "fun_obj.gif"; - public static final String IMG_INC = NAME_PREFIX + "java.gif"; + public static final String IMG_INC = NAME_PREFIX + "impc_obj.gif"; public static final String IMG_VAR = NAME_PREFIX + "var_obj.gif"; public static final String IMG_OBJS_ERROR = NAME_PREFIX + "error_obj.gif"; public static final String IMG_OBJS_WARNING = NAME_PREFIX + "warning_obj.gif"; -- 1.7.1 From 31514655c00b2841fb5a39d91f7988876cdd63a4 Mon Sep 17 00:00:00 2001 From: khartlage Date: Mon, 27 Jan 2003 18:42:22 +0000 Subject: [PATCH 03/16] bug fix: String are always in BOLD fonts --- .../phpeclipse/phpeditor/php/PHPCodeScanner.java | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java index e3ca314..6a5040c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCodeScanner.java @@ -146,13 +146,13 @@ public class PHPCodeScanner extends RuleBasedScanner implements IPreferenceConst provider.getColor(PreferenceConverter.getColor(store, PHP_STRING)), BackgroundColor, //SWT.NONE)); - (store.getBoolean(PHP_STRING_BOLD) ? SWT.NONE : SWT.BOLD) + (store.getBoolean(PHP_STRING_ITALIC) ? SWT.ITALIC : SWT.NONE))); + (store.getBoolean(PHP_STRING_BOLD) ? SWT.BOLD : SWT.NONE ) + (store.getBoolean(PHP_STRING_ITALIC) ? SWT.ITALIC : SWT.NONE))); comment = new Token(new TextAttribute( provider.getColor(PreferenceConverter.getColor(store, PHP_SINGLELINE_COMMENT)), BackgroundColor, //SWT.NONE)); - (store.getBoolean(PHP_SINGLELINE_COMMENT_BOLD) ? SWT.NONE : SWT.BOLD) + (store.getBoolean(PHP_SINGLELINE_COMMENT_BOLD) ? SWT.BOLD : SWT.NONE ) + (store.getBoolean(PHP_SINGLELINE_COMMENT_ITALIC) ? SWT.ITALIC : SWT.NONE))); multi_comment = new Token(new TextAttribute( -- 1.7.1 From 364acf17278a10df6b856f79614f6a80d298eda9 Mon Sep 17 00:00:00 2001 From: kpouer Date: Tue, 28 Jan 2003 14:42:38 +0000 Subject: [PATCH 04/16] Some text modified --- .../newPHPPreferencesMessages_FR.properties | 76 ++++++++++---------- 1 files changed, 38 insertions(+), 38 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties index 2963607..fdcfe17 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_FR.properties @@ -2,64 +2,64 @@ # PHPProjectLibraryPage ######################################### -PHPProjectLibraryPage.elementNotIProject=ERROR: Element not IProject -PHPProjectLibraryPage.project=Project -PHPProjectLibraryPage.tabName=Projects +PHPProjectLibraryPage.elementNotIProject=ERREUR: L'élément n'est pas un IProject +PHPProjectLibraryPage.project=Projet +PHPProjectLibraryPage.tabName=Projets ######################################### # Property Pages ######################################### -PHPProjectPropertyPage.phpProjectClosed=The project selected is a PHP project, but is closed. -PHPProjectPropertyPage.performOkExceptionDialogTitle=Unable to save -PHPProjectPropertyPage.performOkExceptionDialogMessage=ERROR: Unable to save project properties. +PHPProjectPropertyPage.phpProjectClosed=Le project choisi est un projet PHP, mais est fermé. +PHPProjectPropertyPage.performOkExceptionDialogTitle=Impossible de sauver +PHPProjectPropertyPage.performOkExceptionDialogMessage=ERREUR: Impossible de sauver les propriétés du projet. ######################################### # Preference Pages ######################################### PHPBasePreferencePage.description=PHP Preferences -PHPBasePreferencePage.websettingsGroup=Webserver Settings +PHPBasePreferencePage.websettingsGroup=Configuration du serveur Web PHPBasePreferencePage.websettingsGroup.localhost=Localhost PHPBasePreferencePage.websettingsGroup.docroot=DocumentRoot -PHPBasePreferencePage.websettingsGroup.browser=External browser command -PHPBasePreferencePage.websettingsGroup.useexternal=Use external browser -PHPBasePreferencePage.apacheGroup=Apache Settings -PHPBasePreferencePage.apacheGroup.start=Start Apache -PHPBasePreferencePage.apacheGroup.stop=Stop Apache -PHPBasePreferencePage.apacheGroup.restart=Restart Apache -PHPBasePreferencePage.mySQLGroup=MySQL Settings -PHPBasePreferencePage.mySQLGroup.command=MySQL command -PHPBasePreferencePage.parsers=Parsing settings -PHPBasePreferencePage.parsers.pos=Parse on save -PHPBasePreferencePage.parsers.external=External -PHPBasePreferencePage.parsers.internal=Internal -PHPBasePreferencePage.parsers.choose=Choose PHP Parser +PHPBasePreferencePage.websettingsGroup.browser=Commande du navigateur externe +PHPBasePreferencePage.websettingsGroup.useexternal=Utiliser navigateur externe +PHPBasePreferencePage.apacheGroup=Configuration Apache +PHPBasePreferencePage.apacheGroup.start=Lancer Apache +PHPBasePreferencePage.apacheGroup.stop=Stopper Apache +PHPBasePreferencePage.apacheGroup.restart=Relancer Apache +PHPBasePreferencePage.mySQLGroup=Configuration MySQL +PHPBasePreferencePage.mySQLGroup.command=Commande MySQL +PHPBasePreferencePage.parsers=Configuration de parsing +PHPBasePreferencePage.parsers.pos=Parser à la sauvegarde +PHPBasePreferencePage.parsers.external=Externe +PHPBasePreferencePage.parsers.internal=Interne +PHPBasePreferencePage.parsers.choose=Choisissez un parseur PHP -PHPEditorSyntaxPreferencePage.description:PHP Editor Preferences +PHPEditorSyntaxPreferencePage.description:Configuration de l'éditeur PHP PHPEditorSyntaxPreferencePage.foreground:Foreground settings -PHPEditorSyntaxPreferencePage.syntax:Syntax highlighting -PHPEditorSyntaxPreferencePage.color:Colour -PHPEditorSyntaxPreferencePage.bold:Bold -PHPEditorSyntaxPreferencePage.italic:Italic -PHPEditorSyntaxPreferencePage.underline:Underline -PHPEditorSyntaxPreferencePage.multiLineComment=Multi-line comment -PHPEditorSyntaxPreferencePage.singleLineComment=Single-line comment -PHPEditorSyntaxPreferencePage.keywords=Keywords +PHPEditorSyntaxPreferencePage.syntax:Coloration syntaxique +PHPEditorSyntaxPreferencePage.color:Couleur +PHPEditorSyntaxPreferencePage.bold:Gras +PHPEditorSyntaxPreferencePage.italic:Italique +PHPEditorSyntaxPreferencePage.underline:Sousligné +PHPEditorSyntaxPreferencePage.multiLineComment=Commentaire Multi-ligne +PHPEditorSyntaxPreferencePage.singleLineComment=Commenaire Mono-ligne +PHPEditorSyntaxPreferencePage.keywords=Mots clef PHPEditorSyntaxPreferencePage.variables=Variables PHPEditorSyntaxPreferencePage.types=Types -PHPEditorSyntaxPreferencePage.functions=Functions -PHPEditorSyntaxPreferencePage.constants=Constants +PHPEditorSyntaxPreferencePage.functions=Fonctions +PHPEditorSyntaxPreferencePage.constants=Constantes PHPEditorSyntaxPreferencePage.strings=Strings -PHPEditorSyntaxPreferencePage.others=Others -PHPEditorSyntaxPreferencePage.syntaxdialog=Custom PHP Syntax File: -PHPEditorSyntaxPreferencePage.browse=Browse.. +PHPEditorSyntaxPreferencePage.others=Autres +PHPEditorSyntaxPreferencePage.syntaxdialog=Fichier de syntaxe PHP personnalisé : +PHPEditorSyntaxPreferencePage.browse=Parcourir.. PHPEditorSyntaxPreferencePage.textfont=Text font -PHPLanguagePreferencePage.description=PHP Editor Language -PHPLanguagePreferencePage.preflingo=PHP Language Preference -PHPLanguagePreferencePage.choose=Choose Language -PHPLanguagePreferencePage.english=Anglase +PHPLanguagePreferencePage.description=PHP Langue de l'éditeur +PHPLanguagePreferencePage.preflingo=PHP Configuration de langue +PHPLanguagePreferencePage.choose=Choisissez une langue +PHPLanguagePreferencePage.english=English PHPLanguagePreferencePage.german=Deutsch PHPLanguagePreferencePage.french=Francais -- 1.7.1 From 225fd9205caaf9aa4853a811625e8a2b0b86027e Mon Sep 17 00:00:00 2001 From: kpouer Date: Tue, 28 Jan 2003 14:44:58 +0000 Subject: [PATCH 05/16] The parser will now recognize mixed case in php tag Date: Tue, 28 Jan 2003 20:11:10 +0000 Subject: [PATCH 06/16] fixed version to 1.0.6 --- net.sourceforge.phpeclipse/plugin.xml | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) diff --git a/net.sourceforge.phpeclipse/plugin.xml b/net.sourceforge.phpeclipse/plugin.xml index 5725887..1a47b48 100644 --- a/net.sourceforge.phpeclipse/plugin.xml +++ b/net.sourceforge.phpeclipse/plugin.xml @@ -2,7 +2,7 @@ -- 1.7.1 From d695a56371d1068179d77933add5b05adb81cc94 Mon Sep 17 00:00:00 2001 From: khartlage Date: Tue, 28 Jan 2003 20:49:28 +0000 Subject: [PATCH 07/16] misc changes --- .../phpeclipse/phpeditor/PHPSyntaxRdr.java | 16 ++++++++-------- 1 files changed, 8 insertions(+), 8 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java index fc456a4..00e287c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java @@ -44,14 +44,14 @@ public class PHPSyntaxRdr { private static final String PHPSYNTAX_FILE = "phpsyntax.xml"; //$NON-NLS-1$ private static final String USERSYNTAX_FILE = "usersyntax.xml"; //$NON-NLS-1$ private static final String USERDEFAULT_FILE = "default-usersyntax.xml"; //$NON-NLS-1$ - private static final String PHPSYNTAX_TAG = "phpsyntax"; - private static final String KEYWORD_ATTR = "keyword"; - private static final String TYPE_ATTR = "type"; - private static final String CONSTANT_ATTR = "constant"; - private static final String FN_ATTR = "function"; - private static final String DESCRIPTION = "description"; - private static final String USAGE_ATTR = "usage"; - private static final String TOKENVAL_ATTR = "tokenval"; + private static final String PHPSYNTAX_TAG = "phpsyntax"; //$NON-NLS-1$ + private static final String KEYWORD_ATTR = "keyword"; //$NON-NLS-1$ + private static final String TYPE_ATTR = "type"; //$NON-NLS-1$ + private static final String CONSTANT_ATTR = "constant"; //$NON-NLS-1$ + private static final String FN_ATTR = "function"; //$NON-NLS-1$ + private static final String DESCRIPTION = "description"; //$NON-NLS-1$ + private static final String USAGE_ATTR = "usage"; //$NON-NLS-1$ + private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$ private static IPreferenceStore store; private static boolean hasXMLFileBeenRead = true; -- 1.7.1 From 065287ccd6364491b4177af08e22b9e2928de252 Mon Sep 17 00:00:00 2001 From: khartlage Date: Tue, 28 Jan 2003 20:58:27 +0000 Subject: [PATCH 08/16] misc changes --- .../phpeclipse/phpeditor/php/PHPFunction.java | 23 ++++++++++++------- 1 files changed, 14 insertions(+), 9 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java index 2e45bdb..fe1e11e 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java @@ -8,13 +8,18 @@ package net.sourceforge.phpeclipse.phpeditor.php; * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ -public class PHPFunction extends PHPElement{ - private String FunctionUsage; - public void setUsage(String Usage) {this.FunctionUsage = Usage;} - public String getUsage() { return this.FunctionUsage; } - - public PHPFunction(String Name, String Description, String Usage){ - super(Name, Description); - setUsage(Usage); - } +public class PHPFunction extends PHPElement { + private String FunctionUsage; + + public void setUsage(String Usage) { + this.FunctionUsage = Usage; + } + public String getUsage() { + return this.FunctionUsage; + } + + public PHPFunction(String Name, String Description, String Usage) { + super(Name, Description); + setUsage(Usage); + } } -- 1.7.1 From fbec1e1afed949a8c67122743fcefc942dd40246 Mon Sep 17 00:00:00 2001 From: khartlage Date: Tue, 28 Jan 2003 21:54:20 +0000 Subject: [PATCH 09/16] changed the "description" attribute in phpsyntax.xml into multi-line text between the tags --- .../phpeclipse/phpeditor/php/PHPElement.java | 61 ++++++++++++-------- .../phpeclipse/phpeditor/php/PHPFunction.java | 10 ++- 2 files changed, 43 insertions(+), 28 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java index be19656..455b979 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPElement.java @@ -5,29 +5,40 @@ package net.sourceforge.phpeclipse.phpeditor.php; */ public abstract class PHPElement { - private String ElementName; - private String ElementDescription; - - //Setters - public final void setName(String ElementName) - { this.ElementName = ElementName; } - public final void setDescription(String ElementDescription) - { this.ElementDescription = ElementDescription; } - - //Getters - public final String getName() { return ElementName; } - public final String getDescription() { return ElementDescription; } - - public PHPElement(){} - public PHPElement(String Name, String Description){ - setName(Name); - if ((Description == null) || (Description.equals(""))) - { - setDescription(Name +" - "); - } - else { - setDescription(Description); - } - } - + private String ElementName; + private String ElementUsage; + + //Setters + public final void setName(String ElementName) { + this.ElementName = ElementName; + } + public final void setUsage(String ElementDescription) { + this.ElementUsage = ElementDescription; + } + + //Getters + public final String getName() { + return ElementName; + } + + public final String getUsage() { + return ElementUsage; + } + + public String getHoverText() { + return getUsage(); + } + + public PHPElement() { + } + + public PHPElement(String Name, String Usage) { + setName(Name); + if ((Usage == null) || (Usage.equals(""))) { + setUsage(Name + " - "); + } else { + setUsage(Usage); + } + } + } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java index fe1e11e..be5fb49 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPFunction.java @@ -11,15 +11,19 @@ package net.sourceforge.phpeclipse.phpeditor.php; public class PHPFunction extends PHPElement { private String FunctionUsage; - public void setUsage(String Usage) { + public void setDescription(String Usage) { this.FunctionUsage = Usage; } - public String getUsage() { + public String getDescription() { return this.FunctionUsage; } + public String getHoverText() { + return super.getHoverText()+"\n\n"+getDescription(); + } + public PHPFunction(String Name, String Description, String Usage) { super(Name, Description); - setUsage(Usage); + setDescription(Usage); } } -- 1.7.1 From 0e5a231df3cd18b017d93d6014744bd96a596d84 Mon Sep 17 00:00:00 2001 From: khartlage Date: Tue, 28 Jan 2003 22:02:01 +0000 Subject: [PATCH 10/16] changed the "description" attribute in phpsyntax.xml into multi-line text between the tags --- .../phpeclipse/phpeditor/PHPSyntaxRdr.java | 49 ++++++++++++-------- .../phpeclipse/phpeditor/PHPTextHover.java | 12 ++-- .../sourceforge/phpeclipse/phpeditor/phpsyntax.xml | 24 +++++----- 3 files changed, 47 insertions(+), 38 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java index 00e287c..ed67b53 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSyntaxRdr.java @@ -13,6 +13,13 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import net.sourceforge.phpeclipse.IPreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; +import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; +import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword; +import net.sourceforge.phpeclipse.phpeditor.php.PHPType; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.Serializer; import org.apache.xml.serialize.SerializerFactory; @@ -24,17 +31,10 @@ import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import net.sourceforge.phpeclipse.IPreferenceConstants; -import net.sourceforge.phpeclipse.PHPeclipsePlugin; -import net.sourceforge.phpeclipse.phpeditor.php.PHPConstant; -import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; -import net.sourceforge.phpeclipse.phpeditor.php.PHPFunction; -import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword; -import net.sourceforge.phpeclipse.phpeditor.php.PHPType; - /** * PHPSyntaxRdr reads PHP specifics from an XML file (eg. keywords) */ @@ -49,7 +49,6 @@ public class PHPSyntaxRdr { private static final String TYPE_ATTR = "type"; //$NON-NLS-1$ private static final String CONSTANT_ATTR = "constant"; //$NON-NLS-1$ private static final String FN_ATTR = "function"; //$NON-NLS-1$ - private static final String DESCRIPTION = "description"; //$NON-NLS-1$ private static final String USAGE_ATTR = "usage"; //$NON-NLS-1$ private static final String TOKENVAL_ATTR = "tokenval"; //$NON-NLS-1$ private static IPreferenceStore store; @@ -136,21 +135,29 @@ public class PHPSyntaxRdr { String Type = getAttributeValue(attributes, TYPE_ATTR); String Function = getAttributeValue(attributes, FN_ATTR); String Constant = getAttributeValue(attributes, CONSTANT_ATTR); - String Description = getAttributeValue(attributes, DESCRIPTION); - String Usage = getAttributeValue(attributes, USAGE_ATTR); + String usage = getAttributeValue(attributes, USAGE_ATTR); String Tokenval = getAttributeValue(attributes, TOKENVAL_ATTR); + StringBuffer buffer= new StringBuffer(); + NodeList children= node.getChildNodes(); + for (int j= 0; j != children.getLength(); j++) { + String value= children.item(j).getNodeValue(); + if (value != null) + buffer.append(value); + } + String description = buffer.toString().trim(); + if (Keyword == null && Type == null && Function == null && Constant == null) { //ignore as it is not a valid phpsyntax tag } else { if (Keyword != null) { - syntaxdata.addElement(new PHPKeyword(Keyword, Description, Tokenval)); + syntaxdata.addElement(new PHPKeyword(Keyword, usage, Tokenval)); } else if (Type != null) { - syntaxdata.addElement(new PHPType(Type, Description)); + syntaxdata.addElement(new PHPType(Type, usage)); } else if (Function != null) { - syntaxdata.addElement(new PHPFunction(Function, Description, Usage)); + syntaxdata.addElement(new PHPFunction(Function, usage, description)); } else if (Constant != null) { - syntaxdata.addElement(new PHPConstant(Constant, Description)); + syntaxdata.addElement(new PHPConstant(Constant, usage)); } } } @@ -229,8 +236,8 @@ public class PHPSyntaxRdr { name = document.createAttribute(CONSTANT_ATTR); name.setValue(((PHPElement) bufferobj).getName()); attributes.setNamedItem(name); - Attr description = document.createAttribute(DESCRIPTION); - description.setValue(((PHPElement) bufferobj).getDescription()); + Attr description = document.createAttribute(USAGE_ATTR); + description.setValue(((PHPElement) bufferobj).getUsage()); attributes.setNamedItem(description); if (bufferobj instanceof PHPKeyword) { Attr tokenval = document.createAttribute(TOKENVAL_ATTR); @@ -238,9 +245,11 @@ public class PHPSyntaxRdr { attributes.setNamedItem(tokenval); } if (bufferobj instanceof PHPFunction) { - Attr usage = document.createAttribute(USAGE_ATTR); - usage.setValue(((PHPFunction) bufferobj).getUsage()); - attributes.setNamedItem(usage); + // Attr usage = document.createAttribute(USAGE_ATTR); + Text usage = document.createTextNode(((PHPFunction) bufferobj).getDescription()); + node.appendChild(usage); +// usage.setValue(((PHPFunction) bufferobj).getUsage()); +// attributes.setNamedItem(usage); } } OutputFormat format = new OutputFormat(); diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java index 4851296..878629c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPTextHover.java @@ -14,16 +14,14 @@ package net.sourceforge.phpeclipse.phpeditor; import java.util.HashMap; import java.util.Vector; +import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; import net.sourceforge.phpeclipse.phpeditor.php.PHPWordExtractor; - import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.swt.graphics.Point; -import net.sourceforge.phpeclipse.phpeditor.php.PHPElement; - /** * Example implementation for an ITextHover * which hovers over PHP code. @@ -32,6 +30,7 @@ public class PHPTextHover implements ITextHover { public static HashMap functionDescriptions = null; private static PHPWordExtractor phpWordDetector = new PHPWordExtractor(); + /* (non-Javadoc) * Method declared on ITextHover */ @@ -50,13 +49,14 @@ public class PHPTextHover implements ITextHover { String strbuffer = null; PHPElement elbuffer = null; while ((syntaxbuffer != null) - && (!syntaxbuffer.isEmpty() && ((elbuffer = (PHPElement) syntaxbuffer.remove(0)) != null))) { - functionDescriptions.put(elbuffer.getName(), elbuffer.getDescription()); + && (!syntaxbuffer.isEmpty() && + ((elbuffer = (PHPElement) syntaxbuffer.remove(0)) != null))) { + functionDescriptions.put(elbuffer.getName(), elbuffer.getHoverText()); } // functionDescriptions = new HashMap(997); // for (int i=0; i - - + Invokes a COM module + Loads a COM module + Return the absolute value of the number - + Return the arc cosine of the number in radians @@ -123,10 +123,10 @@ - + bool class_exists(string classname) - + void closedir([resource dir_handle]) @@ -223,7 +223,7 @@ - + string create_function(string args, string code) @@ -315,13 +315,13 @@ - + bool define(string constant_name, mixed value, case_sensitive=true) - + bool defined(string constant_name) - + class dir(string directory) @@ -1120,7 +1120,7 @@ - + @@ -2052,7 +2052,7 @@ - + string substr(string str, int start [, int length]) -- 1.7.1 From cf13a4195db402f13d742d3043643455ec27e216 Mon Sep 17 00:00:00 2001 From: khartlage Date: Wed, 29 Jan 2003 18:34:11 +0000 Subject: [PATCH 11/16] spanish translation --- .../newPHPPreferencesMessages_es_ES.properties | 65 ++++++++++++++++++++ 1 files changed, 65 insertions(+), 0 deletions(-) create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_es_ES.properties diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_es_ES.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_es_ES.properties new file mode 100644 index 0000000..5796d75 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/newPHPPreferencesMessages_es_ES.properties @@ -0,0 +1,65 @@ +######################################### +# PHPProjectLibraryPage +######################################### + +PHPProjectLibraryPage.elementNotIProject=ERROR: El elemento no es IProject +PHPProjectLibraryPage.project=Proyecto +PHPProjectLibraryPage.tabName=Proyectos + + +######################################### +# Property Pages +######################################### + +PHPProjectPropertyPage.phpProjectClosed=El proyecto seleccionado es un proyecto PHP, pero está cerrado. +PHPProjectPropertyPage.performOkExceptionDialogTitle=No se pudo guardar. +PHPProjectPropertyPage.performOkExceptionDialogMessage=ERROR: No se pudo guardar las propiedades del proyecto. + +######################################### +# Preference Pages +######################################### +PHPBasePreferencePage.description=Preferencias PHP +PHPBasePreferencePage.websettingsGroup=Configuración Webserver +PHPBasePreferencePage.websettingsGroup.localhost=Localhost +PHPBasePreferencePage.websettingsGroup.docroot=DocumentRoot +PHPBasePreferencePage.websettingsGroup.browser=Comando navegador externo +PHPBasePreferencePage.websettingsGroup.useexternal=Usar navegador externo +PHPBasePreferencePage.apacheGroup=Configuración Apache +PHPBasePreferencePage.apacheGroup.start=Arrancar Apache +PHPBasePreferencePage.apacheGroup.stop=Parar Apache +PHPBasePreferencePage.apacheGroup.restart=Reiniciar Apache +PHPBasePreferencePage.mySQLGroup=Configuración MySQL +PHPBasePreferencePage.mySQLGroup.command=comando MySQL +PHPBasePreferencePage.parsers=Configuración Parser +PHPBasePreferencePage.parsers.pos=Parsear al guardar +PHPBasePreferencePage.parsers.external=Externo +PHPBasePreferencePage.parsers.internal=Interno +PHPBasePreferencePage.parsers.choose=Escoja Parser PHP + +PHPEditorSyntaxPreferencePage.description:Preferencias Editor PHP +PHPEditorSyntaxPreferencePage.foreground:Preferencias primer plano +PHPEditorSyntaxPreferencePage.syntax:Resaltar sintaxis +PHPEditorSyntaxPreferencePage.color:Color +PHPEditorSyntaxPreferencePage.bold:Negrita +PHPEditorSyntaxPreferencePage.italic:Cursiva +PHPEditorSyntaxPreferencePage.underline:Subrayado +PHPEditorSyntaxPreferencePage.multiLineComment=Comentario varias líneas +PHPEditorSyntaxPreferencePage.singleLineComment=Comentario una línia +PHPEditorSyntaxPreferencePage.keywords=Palabras clave +PHPEditorSyntaxPreferencePage.variables=Variables +PHPEditorSyntaxPreferencePage.types=Tipos +PHPEditorSyntaxPreferencePage.functions=Funciones +PHPEditorSyntaxPreferencePage.constants=Constantes +PHPEditorSyntaxPreferencePage.strings=Cadenas +PHPEditorSyntaxPreferencePage.others=Otros +PHPEditorSyntaxPreferencePage.syntaxdialog=Fichero de sintaxis personalizado: +PHPEditorSyntaxPreferencePage.browse=Examinar.. +PHPEditorSyntaxPreferencePage.textfont=Fuente del texto + +PHPLanguagePreferencePage.description=Idioma editor PHP +PHPLanguagePreferencePage.preflingo=Configuración idioma PHP +PHPLanguagePreferencePage.choose=Escoja idioma +PHPLanguagePreferencePage.english=Inglés +PHPLanguagePreferencePage.german=Alemán +PHPLanguagePreferencePage.french=Francés +PHPLanguagePreferencePage.spanish=Español \ No newline at end of file -- 1.7.1 From 6db042a70c5b6ab2938b33920ed8d5d9ca8df7b7 Mon Sep 17 00:00:00 2001 From: khartlage Date: Thu, 30 Jan 2003 19:37:22 +0000 Subject: [PATCH 12/16] *** empty log message *** --- .../net/sourceforge/phpeclipse/LoadPathEntry.java | 62 ++++++------ .../phpeclipse/PHPLanguagePreferencePage.java | 107 ++++++++++---------- .../phpeclipse/PHPPerspectiveFactory.java | 53 +++++----- .../phpeclipse/PHPSyntaxEditorPreferencePage.java | 6 +- .../sourceforge/phpeclipse/PHPeclipsePlugin.java | 2 +- 5 files changed, 114 insertions(+), 116 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java index 9008abf..e908153 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/LoadPathEntry.java @@ -4,35 +4,35 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; public class LoadPathEntry { - public static final String TYPE_PROJECT = "project"; - - protected IProject project; - protected String type; - - public LoadPathEntry(IProject aProjectEntry) { - project = aProjectEntry; - type = TYPE_PROJECT; - } - - public IPath getPath() { - return project.getFullPath(); - } - - public IProject getProject() { - return project; - } - - public String getType() { - return type; - } - - public String toXML() { - StringBuffer buffer = new StringBuffer(); - - buffer.append(""); - - return buffer.toString(); - } + public static final String TYPE_PROJECT = "project"; + + protected IProject project; + protected String type; + + public LoadPathEntry(IProject aProjectEntry) { + project = aProjectEntry; + type = TYPE_PROJECT; + } + + public IPath getPath() { + return project.getFullPath(); + } + + public IProject getProject() { + return project; + } + + public String getType() { + return type; + } + + public String toXML() { + StringBuffer buffer = new StringBuffer(); + + buffer.append(""); + + return buffer.toString(); + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java index fed2faf..e7f13b3 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPLanguagePreferencePage.java @@ -17,60 +17,59 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; -public class PHPLanguagePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - private ArrayList RadioButtons = new ArrayList(); +public class PHPLanguagePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { + private ArrayList RadioButtons = new ArrayList(); - protected Control createContents(Composite parent) { - Composite lingoComposite= new Composite(parent, SWT.NULL); - lingoComposite.setLayout(new GridLayout()); - Group lingoGroup= new Group(lingoComposite, SWT.NONE); - lingoGroup.setText(PHPPreferencesMessages.getString("PHPLanguagePreferencePage.preflingo")); - lingoGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - lingoGroup.setLayout(new GridLayout()); - Label lg = new Label(lingoGroup, SWT.WRAP); - lg.setText(PHPPreferencesMessages.getString("PHPLanguagePreferencePage.choose")); - addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.english"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_EN_GB); //$NON-NLS-1$ - addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.german"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_DE); //$NON-NLS-1$ - addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.french"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_FR); //$NON-NLS-1$ - return lingoComposite; - } - public void init(IWorkbench arg0) { - } - private Button addRadioButton(Composite parent, String label, String key, String value) { - GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); - Button button= new Button(parent, SWT.RADIO); - button.setText(label); - button.setData(new String[] { key, value }); - button.setLayoutData(gd); - button.setSelection(value.equals(PHPeclipsePlugin.getDefault().getPreferenceStore().getString(key))); - RadioButtons.add(button); - return button; - } - - protected void performDefaults() { - IPreferenceStore store= getPreferenceStore(); - for (int i= 0; i < RadioButtons.size(); i++) { - Button button= (Button) RadioButtons.get(i); - String[] info= (String[]) button.getData(); - button.setSelection(info[1].equals(store.getDefaultString(info[0]))); - } - super.performDefaults(); - } + protected Control createContents(Composite parent) { + Composite lingoComposite = new Composite(parent, SWT.NULL); + lingoComposite.setLayout(new GridLayout()); + Group lingoGroup = new Group(lingoComposite, SWT.NONE); + lingoGroup.setText(PHPPreferencesMessages.getString("PHPLanguagePreferencePage.preflingo")); + lingoGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + lingoGroup.setLayout(new GridLayout()); + Label lg = new Label(lingoGroup, SWT.WRAP); + lg.setText(PHPPreferencesMessages.getString("PHPLanguagePreferencePage.choose")); + addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.english"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_EN_GB); //$NON-NLS-1$ + addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.german"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_DE); //$NON-NLS-1$ + addRadioButton(lingoGroup, PHPPreferencesMessages.getString("PHPLanguagePreferencePage.french"), IPreferenceConstants.RESOURCE_BUNDLE, IPreferenceConstants.RESOURCE_BUNDLE_FR); //$NON-NLS-1$ + return lingoComposite; + } + public void init(IWorkbench arg0) { + } + private Button addRadioButton(Composite parent, String label, String key, String value) { + GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); + Button button = new Button(parent, SWT.RADIO); + button.setText(label); + button.setData(new String[] { key, value }); + button.setLayoutData(gd); + button.setSelection(value.equals(PHPeclipsePlugin.getDefault().getPreferenceStore().getString(key))); + RadioButtons.add(button); + return button; + } - public boolean performOk() { - IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); - for (int i= 0; i < RadioButtons.size(); i++) { - Button button= (Button) RadioButtons.get(i); - if (button.getSelection()) { - String[] info= (String[]) button.getData(); - store.setValue(info[0], info[1]); - } - } - PHPeclipsePlugin.getDefault().savePluginPreferences(); - PHPPreferencesMessages.setResourceBundle( - PHPeclipsePlugin.getDefault().getPreferenceStore().getString(IPreferenceConstants.RESOURCE_BUNDLE)); - - return super.performOk(); - } -} + protected void performDefaults() { + IPreferenceStore store = getPreferenceStore(); + for (int i = 0; i < RadioButtons.size(); i++) { + Button button = (Button) RadioButtons.get(i); + String[] info = (String[]) button.getData(); + button.setSelection(info[1].equals(store.getDefaultString(info[0]))); + } + super.performDefaults(); + } + + public boolean performOk() { + IPreferenceStore store = PHPeclipsePlugin.getDefault().getPreferenceStore(); + for (int i = 0; i < RadioButtons.size(); i++) { + Button button = (Button) RadioButtons.get(i); + if (button.getSelection()) { + String[] info = (String[]) button.getData(); + store.setValue(info[0], info[1]); + } + } + PHPeclipsePlugin.getDefault().savePluginPreferences(); + PHPPreferencesMessages.setResourceBundle( + PHPeclipsePlugin.getDefault().getPreferenceStore().getString(IPreferenceConstants.RESOURCE_BUNDLE)); + return super.performOk(); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java index cc41bb1..0278f22 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java @@ -1,4 +1,3 @@ - package net.sourceforge.phpeclipse; import org.eclipse.debug.ui.IDebugUIConstants; @@ -8,41 +7,41 @@ import org.eclipse.ui.IPerspectiveFactory; public class PHPPerspectiveFactory implements IPerspectiveFactory { - public PHPPerspectiveFactory() { - super(); - } + public PHPPerspectiveFactory() { + super(); + } + + public void createInitialLayout(IPageLayout layout) { + String editorArea = layout.getEditorArea(); - public void createInitialLayout(IPageLayout layout) { - String editorArea = layout.getEditorArea(); - -// IFolderLayout phpResourcesArea = layout.createFolder("phpresourcesarea", IPageLayout.LEFT, (float)0.25, editorArea); -// phpResourcesArea.addView(PHPeclipsePlugin.PHP_RESOURCES_VIEW_ID); - IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.25, editorArea); //$NON-NLS-1$ + // IFolderLayout phpResourcesArea = layout.createFolder("phpresourcesarea", IPageLayout.LEFT, (float)0.25, editorArea); + // phpResourcesArea.addView(PHPeclipsePlugin.PHP_RESOURCES_VIEW_ID); + IFolderLayout folder = layout.createFolder("left", IPageLayout.LEFT, (float) 0.25, editorArea); //$NON-NLS-1$ folder.addView(IPageLayout.ID_RES_NAV); folder.addPlaceholder(IPageLayout.ID_RES_NAV); - - IFolderLayout consoleArea = layout.createFolder("consoleArea", IPageLayout.BOTTOM, (float)0.75, editorArea); - - consoleArea.addView(IPageLayout.ID_TASK_LIST); + + IFolderLayout consoleArea = layout.createFolder("consoleArea", IPageLayout.BOTTOM, (float) 0.75, editorArea); + + consoleArea.addView(IPageLayout.ID_TASK_LIST); consoleArea.addView(IDebugUIConstants.ID_CONSOLE_VIEW); consoleArea.addView(IPageLayout.ID_BOOKMARKS); - - layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float)0.75, editorArea); - - layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET); - - layout.addShowViewShortcut(IDebugUIConstants.ID_CONSOLE_VIEW); - - layout.addShowViewShortcut(PHPeclipsePlugin.PHP_RESOURCES_VIEW_ID); - + + layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, (float) 0.75, editorArea); + + layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET); + + layout.addShowViewShortcut(IDebugUIConstants.ID_CONSOLE_VIEW); + + layout.addShowViewShortcut(PHPeclipsePlugin.PHP_RESOURCES_VIEW_ID); + // views - standard workbench layout.addShowViewShortcut(IPageLayout.ID_OUTLINE); layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST); layout.addShowViewShortcut(IPageLayout.ID_BOOKMARKS); - + // new actions - PHP project creation wizards - layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$ - layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$ - } + layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder"); //$NON-NLS-1$ + layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file"); //$NON-NLS-1$ + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java index 22b06ff..55c03c5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java @@ -196,7 +196,7 @@ public class PHPSyntaxEditorPreferencePage extends PreferencePage implements IWo gd.horizontalAlignment = GridData.BEGINNING; gd.horizontalSpan = 2; BoldCheckBox.setLayoutData(gd); - + ItalicCheckBox = new Button(stylesComposite, SWT.CHECK); ItalicCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.italic")); //$NON-NLS-1$ ItalicCheckBox.setEnabled(false); @@ -204,7 +204,7 @@ public class PHPSyntaxEditorPreferencePage extends PreferencePage implements IWo gd.horizontalAlignment = GridData.BEGINNING; gd.horizontalSpan = 2; ItalicCheckBox.setLayoutData(gd); - + UnderlineCheckBox = new Button(stylesComposite, SWT.CHECK); UnderlineCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.underline")); //$NON-NLS-1$ UnderlineCheckBox.setEnabled(false); @@ -353,7 +353,7 @@ public class PHPSyntaxEditorPreferencePage extends PreferencePage implements IWo syntaxGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); syntaxGroup.setLayout(layout); createSyntaxPage(syntaxGroup); - + initialize(); return composite; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java index 0cb4ae8..b7c6173 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java @@ -313,7 +313,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon store.setDefault(PHP_OUTLINE_CLASS, "true"); //$NON-NLS-1$ store.setDefault(PHP_OUTLINE_FUNC, "true"); //$NON-NLS-1$ store.setDefault(PHP_OUTLINE_VAR, "true"); //$NON-NLS-1$ - + TemplatePreferencePage.initDefaults(store); new PHPSyntaxRdr(); //this will initialize the static fields in the syntaxrdr class } -- 1.7.1 From 2e72ecbdb19911ca7e39e1b46632fd6e1bd20b94 Mon Sep 17 00:00:00 2001 From: khartlage Date: Thu, 30 Jan 2003 19:45:33 +0000 Subject: [PATCH 13/16] JDT codeassist module, nothing changed yet --- .../sourceforge/phpdt/core/BufferChangedEvent.java | 109 + .../src/net/sourceforge/phpdt/core/IBuffer.java | 263 ++ .../phpdt/core/IBufferChangedListener.java | 30 + .../net/sourceforge/phpdt/core/IBufferFactory.java | 33 + .../net/sourceforge/phpdt/core/ICodeAssist.java | 81 + .../net/sourceforge/phpdt/core/ICodeFormatter.java | 43 + .../sourceforge/phpdt/core/ICompilationUnit.java | 208 ++ .../phpdt/core/ICompletionRequestor.java | 405 +++ .../src/net/sourceforge/phpdt/core/IField.java | 47 + .../net/sourceforge/phpdt/core/IInitializer.java | 20 + .../net/sourceforge/phpdt/core/IJavaElement.java | 275 ++ .../src/net/sourceforge/phpdt/core/IJavaModel.java | 221 ++ .../sourceforge/phpdt/core/IJavaModelStatus.java | 82 + .../phpdt/core/IJavaModelStatusConstants.java | 252 ++ .../net/sourceforge/phpdt/core/IJavaProject.java | 503 ++++ .../src/net/sourceforge/phpdt/core/IMember.java | 81 + .../src/net/sourceforge/phpdt/core/IMethod.java | 145 ++ .../src/net/sourceforge/phpdt/core/IOpenable.java | 168 ++ .../src/net/sourceforge/phpdt/core/IParent.java | 40 + .../sourceforge/phpdt/core/IProblemRequestor.java | 54 + .../phpdt/core/ISourceManipulation.java | 113 + .../net/sourceforge/phpdt/core/ISourceRange.java | 38 + .../sourceforge/phpdt/core/ISourceReference.java | 73 + .../src/net/sourceforge/phpdt/core/IType.java | 569 ++++ .../net/sourceforge/phpdt/core/IWorkingCopy.java | 349 +++ .../sourceforge/phpdt/core/JavaModelException.java | 132 + .../src/net/sourceforge/phpdt/core/Signature.java | 1384 ++++++++++ .../internal/codeassist/CompletionEngine.java | 2702 ++++++++++++++++++++ .../internal/codeassist/ISearchRequestor.java | 60 + .../codeassist/ISearchableNameEnvironment.java | 48 + .../internal/codeassist/ISelectionRequestor.java | 145 ++ .../internal/codeassist/RelevanceConstants.java | 21 + .../phpdt/internal/codeassist/SelectionEngine.java | 739 ++++++ .../codeassist/complete/CompletionNodeFound.java | 32 + .../complete/CompletionOnArgumentName.java | 50 + .../complete/CompletionOnClassLiteralAccess.java | 59 + .../complete/CompletionOnClassReference.java | 20 + .../complete/CompletionOnExceptionReference.java | 46 + .../CompletionOnExplicitConstructorCall.java | 76 + .../codeassist/complete/CompletionOnFieldName.java | 42 + .../codeassist/complete/CompletionOnFieldType.java | 58 + .../complete/CompletionOnImportReference.java | 55 + .../complete/CompletionOnInterfaceReference.java | 20 + .../codeassist/complete/CompletionOnLocalName.java | 42 + .../complete/CompletionOnMemberAccess.java | 58 + .../complete/CompletionOnMessageSend.java | 70 + .../complete/CompletionOnMethodName.java | 61 + .../complete/CompletionOnMethodReturnType.java | 34 + .../complete/CompletionOnPackageReference.java | 53 + .../CompletionOnQualifiedAllocationExpression.java | 69 + .../CompletionOnQualifiedClassReference.java | 28 + .../CompletionOnQualifiedExceptionReference.java | 55 + .../CompletionOnQualifiedInterfaceReference.java | 28 + .../CompletionOnQualifiedNameReference.java | 78 + .../CompletionOnQualifiedTypeReference.java | 66 + .../complete/CompletionOnSingleNameReference.java | 47 + .../complete/CompletionOnSingleTypeReference.java | 63 + .../codeassist/complete/CompletionParser.java | 1386 ++++++++++ .../codeassist/complete/CompletionScanner.java | 707 +++++ .../codeassist/complete/InvalidCursorLocation.java | 30 + .../internal/codeassist/impl/AssistOptions.java | 72 + .../internal/codeassist/impl/AssistParser.java | 1009 ++++++++ .../phpdt/internal/codeassist/impl/Engine.java | 192 ++ .../codeassist/select/SelectionNodeFound.java | 23 + .../codeassist/select/SelectionOnArgumentName.java | 44 + .../select/SelectionOnExplicitConstructorCall.java | 71 + .../select/SelectionOnFieldReference.java | 60 + .../codeassist/select/SelectionOnFieldType.java | 27 + .../select/SelectionOnImportReference.java | 52 + .../codeassist/select/SelectionOnLocalName.java | 38 + .../codeassist/select/SelectionOnMessageSend.java | 72 + .../select/SelectionOnPackageReference.java | 50 + .../SelectionOnQualifiedAllocationExpression.java | 77 + .../select/SelectionOnQualifiedNameReference.java | 89 + .../select/SelectionOnQualifiedSuperReference.java | 60 + .../select/SelectionOnQualifiedTypeReference.java | 67 + .../select/SelectionOnSingleNameReference.java | 74 + .../select/SelectionOnSingleTypeReference.java | 65 + .../select/SelectionOnSuperReference.java | 58 + .../codeassist/select/SelectionParser.java | 686 +++++ .../codeassist/select/SelectionScanner.java | 68 + .../phpdt/internal/core/BasicCompilationUnit.java | 70 + .../phpdt/internal/core/JavaElementInfo.java | 128 + .../phpdt/internal/core/JavaModelStatus.java | 327 +++ .../phpdt/internal/core/TypeConverter.java | 245 ++ 85 files changed, 16490 insertions(+), 0 deletions(-) create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IInitializer.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/CompletionEngine.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISelectionRequestor.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/RelevanceConstants.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/SelectionEngine.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionNodeFound.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnArgumentName.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnClassLiteralAccess.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnClassReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExceptionReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnFieldName.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnFieldType.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnImportReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnInterfaceReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnLocalName.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMemberAccess.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMessageSend.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMethodName.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMethodReturnType.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnPackageReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedClassReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedExceptionReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedInterfaceReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleNameReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionParser.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionScanner.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/InvalidCursorLocation.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistParser.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/Engine.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionNodeFound.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnArgumentName.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnExplicitConstructorCall.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnFieldReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnFieldType.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnImportReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnLocalName.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnMessageSend.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnPackageReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedSuperReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleNameReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleTypeReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSuperReference.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionParser.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionScanner.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeConverter.java diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java new file mode 100644 index 0000000..7422223 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/BufferChangedEvent.java @@ -0,0 +1,109 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import java.util.EventObject; + +/** + * A buffer changed event describes how a buffer has changed. These events are + * used in IBufferChangedListener notifications. + *

+ * For text insertions, getOffset is the offset + * of the first inserted character, getText is the + * inserted text, and getLength is 0. + *

+ *

+ * For text removals, getOffset is the offset + * of the first removed character, getText is null, + * and getLength is the length of the text that was removed. + *

+ *

+ * For replacements (including IBuffer.setContents), + * getOffset is the offset + * of the first replaced character, getText is the replacement + * text, and getLength is the length of the original text + * that was replaced. + *

+ *

+ * When a buffer is closed, getOffset is 0, getLength + * is 0, and getText is null. + *

+ *

+ * This class is not intended to be instantiated or subclassed by clients. + * Instances of this class are automatically created by the Java model. + *

+ * + * @see IBuffer + */ +public class BufferChangedEvent extends EventObject { + + /** + * The length of text that has been modified in the buffer. + */ + private int length; + + /** + * The offset into the buffer where the modification took place. + */ + private int offset; + + /** + * The text that was modified. + */ + private String text; + +/** + * Creates a new buffer changed event indicating that the given buffer has changed. + */ +public BufferChangedEvent(IBuffer buffer, int offset, int length, String text) { + super(buffer); + this.offset = offset; + this.length = length; + this.text = text; +} +/** + * Returns the buffer which has changed. + * + * @return the buffer affected by the change + */ +public IBuffer getBuffer() { + return (IBuffer) source; +} +/** + * Returns the length of text removed or replaced in the buffer, or + * 0 if text has been inserted into the buffer. + * + * @return the length of the original text fragment modified by the + * buffer change ( 0 in case of insertion). + */ +public int getLength() { + return this.length; +} +/** + * Returns the index of the first character inserted, removed, or replaced + * in the buffer. + * + * @return the source offset of the textual manipulation in the buffer + */ +public int getOffset() { + return this.offset; +} +/** + * Returns the text that was inserted, the replacement text, + * or null if text has been removed. + * + * @return the text corresponding to the buffer change ( null + * in case of deletion). + */ +public String getText() { + return this.text; +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java new file mode 100644 index 0000000..01660ae --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBuffer.java @@ -0,0 +1,263 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * A buffer contains the text contents of a resource. It is not language-specific. + * The contents may be in the process of being edited, differing from the actual contents of the + * underlying resource. A buffer has an owner, which is an IOpenable. + * If a buffer does not have an underlying resource, saving the buffer has no effect. + * Buffers can be read-only. + *

+ * Note that java model operations that manipulate an IBuffer (e.g. + * IType.createMethod(...)) ensures that the same line delimiter + * (i.e. either "\n" or "\r" or "\r\n") is + * used across the whole buffer. Thus these operations may change the line delimiter(s) + * included in the string to be append, or replaced. + * However implementers of this interface should be aware that other clients of IBuffer + * might not do such transformations beforehand. + *

+ * This interface may be implemented by clients. + *

+ */ +public interface IBuffer { + +/** + * Adds the given listener for changes to this buffer. + * Has no effect if an identical listener is already registered or if the buffer + * is closed. + * + * @param listener the listener of buffer changes + */ +public void addBufferChangedListener(IBufferChangedListener listener); +/** + * Appends the given character array to the contents of the buffer. + * This buffer will now have unsaved changes. + * Any client can append to the contents of the buffer, not just the owner of the buffer. + * Reports a buffer changed event. + *

+ * Has no effect if this buffer is read-only. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param text the given character array to append to contents of the buffer + */ +public void append(char[] text); +/** + * Appends the given string to the contents of the buffer. + * This buffer will now have unsaved changes. + * Any client can append to the contents of the buffer, not just the owner of the buffer. + * Reports a buffer changed event. + *

+ * Has no effect if this buffer is read-only. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param text the String to append to the contents of the buffer + */ +public void append(String text); +/** + * Closes the buffer. Any unsaved changes are lost. Reports a buffer changed event + * with a 0 offset and a 0 length. When this event is fired, the buffer should already + * be closed. + *

+ * Further operations on the buffer are not allowed, except for close. If an + * attempt is made to close an already closed buffer, the second attempt has no effect. + */ +public void close(); +/** + * Returns the character at the given position in this buffer. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param position a zero-based source offset in this buffer + * @return the character at the given position in this buffer + */ +public char getChar(int position); +/** + * Returns the contents of this buffer as a character array, or null if + * the buffer has not been initialized. + *

+ * Callers should make no assumption about whether the returned character array + * is or is not the genuine article or a copy. In other words, if the client + * wishes to change this array, they should make a copy. Likewise, if the + * client wishes to hang on to the array in its current state, they should + * make a copy. + *

+ *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @return the characters contained in this buffer + */ +public char[] getCharacters(); +/** + * Returns the contents of this buffer as a String. Like all strings, + * the result is an immutable value object., It can also answer null if + * the buffer has not been initialized. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @return the contents of this buffer as a String + */ +public String getContents(); +/** + * Returns number of characters stored in this buffer. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @return the number of characters in this buffer + */ +public int getLength(); +/** + * Returns the Java openable element owning of this buffer. + * + * @return the openable element owning this buffer + */ +public IOpenable getOwner(); +/** + * Returns the given range of text in this buffer. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param offset the zero-based starting offset + * @param length the number of characters to retrieve + * @return the given range of text in this buffer + */ +public String getText(int offset, int length); +/** + * Returns the underlying resource for which this buffer was opened, + * or null if this buffer was not opened on a resource. + * + * @return the underlying resource for this buffer, or null + * if none. + */ +public IResource getUnderlyingResource(); +/** + * Returns whether this buffer has been modified since it + * was opened or since it was last saved. + * If a buffer does not have an underlying resource, this method always + * returns true. + * + * @return a boolean indicating presence of unsaved changes (in + * the absence of any underlying resource, it will always return true). + */ +public boolean hasUnsavedChanges(); +/** + * Returns whether this buffer has been closed. + * + * @return a boolean indicating whether this buffer is closed. + */ +public boolean isClosed(); +/** + * Returns whether this buffer is read-only. + * + * @return a boolean indicating whether this buffer is read-only + */ +public boolean isReadOnly(); +/** + * Removes the given listener from this buffer. + * Has no affect if an identical listener is not registered or if the buffer is closed. + * + * @param listener the listener + */ +public void removeBufferChangedListener(IBufferChangedListener listener); +/** + * Replaces the given range of characters in this buffer with the given text. + * position and position + length must be in the range [0, getLength()]. + * length must not be negative. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param position the zero-based starting position of the affected text range in this buffer + * @param length the length of the affected text range in this buffer + * @param text the replacing text as a character array + */ +public void replace(int position, int length, char[] text); +/** + * Replaces the given range of characters in this buffer with the given text. + * position and position + length must be in the range [0, getLength()]. + * length must not be negative. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param position the zero-based starting position of the affected text range in this buffer + * @param length the length of the affected text range in this buffer + * @param text the replacing text as a String + */ +public void replace(int position, int length, String text); +/** + * Saves the contents of this buffer to its underlying resource. If + * successful, this buffer will have no unsaved changes. + * The buffer is left open. Saving a buffer with no unsaved + * changes has no effect - the underlying resource is not changed. + * If the buffer does not have an underlying resource or is read-only, this + * has no effect. + *

+ * The force parameter controls how this method deals with + * cases where the workbench is not completely in sync with the local file system. + * If false is specified, this method will only attempt + * to overwrite a corresponding file in the local file system provided + * it is in sync with the workbench. This option ensures there is no + * unintended data loss; it is the recommended setting. + * However, if true is specified, an attempt will be made + * to write a corresponding file in the local file system, + * overwriting any existing one if need be. + * In either case, if this method succeeds, the resource will be marked + * as being local (even if it wasn't before). + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param progress the progress monitor to notify + * @param force a boolean flag indicating how to deal with resource + * inconsistencies. + * + * @exception JavaModelException if an error occurs writing the buffer + * to the underlying resource + * + * @see org.eclipse.core.resources.IFile#setContents(java.io.InputStream, boolean, boolean, org.eclipse.core.runtime.IProgressMonitor) + */ +public void save(IProgressMonitor progress, boolean force) throws JavaModelException; +/** + * Sets the contents of this buffer to the given character array. + * This buffer will now have unsaved changes. + * Any client can set the contents of the buffer, not just the owner of the buffer. + * Reports a buffer changed event. + *

+ * Equivalent to replace(0,getLength(),contents). + *

+ *

+ * Has no effect if this buffer is read-only. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param contents the new contents of this buffer as a character array + */ +public void setContents(char[] contents); +/** + * Sets the contents of this buffer to the given String. + * This buffer will now have unsaved changes. + * Any client can set the contents of the buffer, not just the owner of the buffer. + * Reports a buffer changed event. + *

+ * Equivalent to replace(0,getLength(),contents). + *

+ *

+ * Has no effect if this buffer is read-only. + *

+ * A RuntimeException might be thrown if the buffer is closed. + * + * @param contents the new contents of this buffer as a String + */ +public void setContents(String contents); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java new file mode 100644 index 0000000..1cfe50d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferChangedListener.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * A listener, which gets notified when the contents of a specific buffer + * have changed, or when the buffer is closed. + * When a buffer is closed, the listener is notified after the buffer has been closed. + * A listener is not notified when a buffer is saved. + *

+ * This interface may be implemented by clients. + *

+ */ +public interface IBufferChangedListener { + + /** + * Notifies that the given event has occurred. + * + * @param event the change event + */ + public void bufferChanged(BufferChangedEvent event); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java new file mode 100644 index 0000000..38c45db --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * A factory that creates IBuffers for openables. + *

+ * This interface may be implemented by clients. + *

+ * @since 2.0 + */ +public interface IBufferFactory { + + /** + * Creates a buffer for the given owner. + * The new buffer will be initialized with the contents of the owner + * if and only if it was not already initialized by the factory (a buffer is uninitialized if + * its content is null). + * + * @param owner the owner of the buffer + * @see IBuffer + */ + IBuffer createBuffer(IOpenable owner); +} + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java new file mode 100644 index 0000000..5f3c04c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeAssist.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Common protocol for Java elements that support source code assist and code + * resolve. + *

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

+ */ +public interface ICodeAssist { + + /** + * Performs code completion at the given offset position in this compilation unit, + * reporting results to the given completion requestor. The offset + * is the 0-based index of the character, after which code assist is desired. + * An offset of -1 indicates to code assist at the beginning of this + * compilation unit. + * + * @param offset the given offset position + * @param requestor the given completion requestor + * @exception JavaModelException if code assist could not be performed. Reasons include:
    + *
  • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
  • + *
  • The position specified is < -1 or is greater than this compilation unit's + * source length (INDEX_OUT_OF_BOUNDS) + *
+ * + * @exception IllegalArgumentException if requestor is null + * @since 2.0 + * */ + void codeComplete(int offset, ICompletionRequestor requestor) + throws JavaModelException; + /** + * Performs code selection on the given selected text in this compilation unit, + * reporting results to the given selection requestor. The offset + * is the 0-based index of the first selected character. The length + * is the number of selected characters. + * + * @param offset the given offset position + * @param length the number of selected characters + * + * @exception JavaModelException if code resolve could not be performed. Reasons include: + *
  • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
  • + *
  • The range specified is not within this element's + * source range (INDEX_OUT_OF_BOUNDS) + * + * + */ + IJavaElement[] codeSelect(int offset, int length) throws JavaModelException; + + /** + * Performs code completion at the given offset position in this compilation unit, + * reporting results to the given completion requestor. The offset + * is the 0-based index of the character, after which code assist is desired. + * An offset of -1 indicates to code assist at the beginning of this + * compilation unit. + * + * @param offset the given offset position + * @param requestor the given completion requestor + * + * @exception JavaModelException if code assist could not be performed. Reasons include:
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The position specified is < -1 or is greater than this compilation unit's + * source length (INDEX_OUT_OF_BOUNDS) + *
    + * + * @exception IllegalArgumentException if requestor is null + * @deprecated - use codeComplete(int, ICompletionRequestor) instead + */ +// void codeComplete(int offset, ICodeCompletionRequestor requestor) +// throws JavaModelException; +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java new file mode 100644 index 0000000..15d6dcb --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICodeFormatter.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Specification for a generic source code formatter. Client plug-ins can contribute + * an implementation for an ICodeFormatter, through the extension point "net.sourceforge.phpdt.core.codeFormatter". + * In case none is found, a default formatter can be provided through the ToolFactory. + * + * @see ToolFactory#createCodeFormatter() + * @see ToolFactory#createDefaultCodeFormatter(Map options) + * @since 2.0 + */ +public interface ICodeFormatter { + + /** + * Formats the String sourceString, + * and returns a string containing the formatted version. + * + * @param string the string to format + * @param indentationLevel the initial indentation level, used + * to shift left/right the entire source fragment. An initial indentation + * level of zero has no effect. + * @param positions an array of positions to map. These are + * character-based source positions inside the original source, + * for which corresponding positions in the formatted source will + * be computed (so as to relocate elements associated with the original + * source). It updates the positions array with updated positions. + * If set to null, then no positions are mapped. + * @param lineSeparator the line separator to use in formatted source, + * if set to null, then the platform default one will be used. + * @return the formatted output string. + */ + String format(String string, int indentationLevel, int[] positions, String lineSeparator); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java new file mode 100644 index 0000000..4d44420 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java @@ -0,0 +1,208 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Represents an entire Java compilation unit (.java source file). + * Compilation unit elements need to be opened before they can be navigated or manipulated. + * The children are of type IPackageDeclaration, + * IImportContainer, and IType, + * and appear in the order in which they are declared in the source. + * If a .java file cannot be parsed, its structure remains unknown. + * Use IJavaElement.isStructureKnown to determine whether this is + * the case. + *

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

    + */ +public interface ICompilationUnit extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation, ICodeAssist { +/** + * Creates and returns an import declaration in this compilation unit + * with the given name. + *

    + * Optionally, the new element can be positioned before the specified + * sibling. If no sibling is specified, the element will be inserted + * as the last import declaration in this compilation unit. + *

    + * If the compilation unit already includes the specified import declaration, + * the import is not generated (it does not generate duplicates). + * Note that it is valid to specify both a single-type import and an on-demand import + * for the same package, for example "java.io.File" and + * "java.io.*", in which case both are preserved since the semantics + * of this are not the same as just importing "java.io.*". + * Importing "java.lang.*", or the package in which the compilation unit + * is defined, are not treated as special cases. If they are specified, they are + * included in the result. + * + * @param name the name of the import declaration to add as defined by JLS2 7.5. (For example: "java.io.File" or + * "java.awt.*") + * @param sibling the existing element which the import declaration will be inserted immediately before (if + * null , then this import will be inserted as the last import declaration. + * @param monitor the progress monitor to notify + * @return the newly inserted import declaration (or the previously existing one in case attempting to create a duplicate) + * + * @exception JavaModelException if the element could not be created. Reasons include: + *

      + *
    • This Java element does not exist or the specified sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The specified sibling is not a child of this compilation unit (INVALID_SIBLING) + *
    • The name is not a valid import name (INVALID_NAME) + *
    + */ +//IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException; +/** + * Creates and returns a package declaration in this compilation unit + * with the given package name. + * + *

    If the compilation unit already includes the specified package declaration, + * it is not generated (it does not generate duplicates). + * + * @param name the name of the package declaration to add as defined by JLS2 7.4. (For example, "java.lang") + * @param monitor the progress monitor to notify + * @return the newly inserted package declaration (or the previously existing one in case attempting to create a duplicate) + * + * @exception JavaModelException if the element could not be created. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The name is not a valid package name (INVALID_NAME) + *
    + */ + //IPackageDeclaration createPackageDeclaration(String name, IProgressMonitor monitor) throws JavaModelException; +/** + * Creates and returns a type in this compilation unit with the + * given contents. If this compilation unit does not exist, one + * will be created with an appropriate package declaration. + *

    + * Optionally, the new type can be positioned before the specified + * sibling. If sibling is null, the type will be appended + * to the end of this compilation unit. + * + *

    It is possible that a type with the same name already exists in this compilation unit. + * The value of the force parameter effects the resolution of + * such a conflict:

      + *
    • true - in this case the type is created with the new contents
    • + *
    • false - in this case a JavaModelException is thrown
    • + *
    + * + * @param contents the source contents of the type declaration to add. + * @param sibling the existing element which the type will be inserted immediately before (if + * null , then this type will be inserted as the last type declaration. + * @param force a boolean flag indicating how to deal with duplicates + * @param monitor the progress monitor to notify + * @return the newly inserted type + * + * @exception JavaModelException if the element could not be created. Reasons include: + *
      + *
    • The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The specified sibling is not a child of this compilation unit (INVALID_SIBLING) + *
    • The contents could not be recognized as a type declaration (INVALID_CONTENTS) + *
    • There was a naming collision with an existing type (NAME_COLLISION) + *
    + */ +IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException; +/** + * Returns all types declared in this compilation unit in the order + * in which they appear in the source. + * This includes all top-level types and nested member types. + * It does NOT include local types (types defined in methods). + * + * @return the array of top-level and member types defined in a compilation unit, in declaration order. + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +IType[] getAllTypes() throws JavaModelException; +/** + * Returns the smallest element within this compilation unit that + * includes the given source position (that is, a method, field, etc.), or + * null if there is no element other than the compilation + * unit itself at the given position, or if the given position is not + * within the source range of this compilation unit. + * + * @param position a source position inside the compilation unit + * @return the innermost Java element enclosing a given source position or null + * if none (excluding the compilation unit). + * @exception JavaModelException if the compilation unit does not exist or if an + * exception occurs while accessing its corresponding resource + */ +IJavaElement getElementAt(int position) throws JavaModelException; +/** + * Returns the first import declaration in this compilation unit with the given name. + * This is a handle-only method. The import declaration may or may not exist. This + * is a convenience method - imports can also be accessed from a compilation unit's + * import container. + * + * @param name the name of the import to find as defined by JLS2 7.5. (For example: "java.io.File" + * or "java.awt.*") + * @return a handle onto the corresponding import declaration. The import declaration may or may not exist. + */ +// IImportDeclaration getImport(String name) ; +/** + * Returns the import container for this compilation unit. + * This is a handle-only method. The import container may or + * may not exist. The import container can used to access the + * imports. + * @return a handle onto the corresponding import container. The + * import contain may or may not exist. + */ +// IImportContainer getImportContainer(); +/** + * Returns the import declarations in this compilation unit + * in the order in which they appear in the source. This is + * a convenience method - import declarations can also be + * accessed from a compilation unit's import container. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +// IImportDeclaration[] getImports() throws JavaModelException; +/** + * Returns the first package declaration in this compilation unit with the given package name + * (there normally is at most one package declaration). + * This is a handle-only method. The package declaration may or may not exist. + * + * @param name the name of the package declaration as defined by JLS2 7.4. (For example, "java.lang") + */ +// IPackageDeclaration getPackageDeclaration(String name); +/** + * Returns the package declarations in this compilation unit + * in the order in which they appear in the source. + * There normally is at most one package declaration. + * + * @return an array of package declaration (normally of size one) + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +// IPackageDeclaration[] getPackageDeclarations() throws JavaModelException; +/** + * Returns the top-level type declared in this compilation unit with the given simple type name. + * The type name has to be a valid compilation unit name. + * This is a handle-only method. The type may or may not exist. + * + * @param name the simple name of the requested type in the compilation unit + * @return a handle onto the corresponding type. The type may or may not exist. + * @see JavaConventions#validateCompilationUnitName(String name) + */ +IType getType(String name); +/** + * Returns the top-level types declared in this compilation unit + * in the order in which they appear in the source. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +IType[] getTypes() throws JavaModelException; + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java new file mode 100644 index 0000000..4586a1d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompletionRequestor.java @@ -0,0 +1,405 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import net.sourceforge.phpdt.core.compiler.IProblem; + +/** + * A completion requestor accepts results as they are computed and is aware + * of source positions to complete the various different results. + *

    + * This interface may be implemented by clients. + *

    + * + * @see ICodeAssist + * @since 2.0 + */ +public interface ICompletionRequestor { +/** + * Code assist notification of an anonymous type declaration completion. + * @param superTypePackageName Name of the package that contains the super type of this + * new anonymous type declaration . + * + * @param superTypeName Name of the super type of this new anonymous type declaration. + * + * @param parameterPackageNames Names of the packages in which the parameter types are declared. + * Should contain as many elements as parameterTypeNames. + * + * @param parameterTypeNames Names of the parameters types. + * Should contain as many elements as parameterPackageNames. + * + * @param completionName The completion for the anonymous type declaration. + * Can include zero, one or two brackets. If the closing bracket is included, + * then the cursor should be placed before it. + * + * @param modifiers The modifiers of the constructor. + * + * @param completionStart The start position of insertion of the name of this new anonymous type declaration. + * + * @param completionEnd The end position of insertion of the name of this new anonymous type declaration. + * + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. + */ +void acceptAnonymousType( + char[] superTypePackageName, + char[] superTypeName, + char[][] parameterPackageNames, + char[][] parameterTypeNames, + char[][] parameterNames, + char[] completionName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of a class completion. + * + * @param packageName Declaring package name of the class. + * @param className Name of the class. + * @param completionName The completion for the class. Can include ';' for imported classes. + * @param modifiers The modifiers of the class. + * @param completionStart The start position of insertion of the name of the class. + * @param completionEnd The end position of insertion of the name of the class. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ +void acceptClass( + char[] packageName, + char[] className, + char[] completionName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of a compilation error detected during completion. + * @param error Only problems which are categorized as non-syntax errors are notified to the + * requestor, warnings are silently ignored. + * In case an error got signalled, no other completions might be available, + * therefore the problem message should be presented to the user. + * The source positions of the problem are related to the source where it was + * detected (might be in another compilation unit, if it was indirectly requested + * during the code assist process). + * Note: the problem knows its originating file name. + */ +void acceptError(IProblem error); +/** + * Code assist notification of a field completion. + * + * @param declaringTypePackageName Name of the package in which the type that contains this field is declared. + * @param declaringTypeName Name of the type declaring this new field. + * @param name Name of the field. + * @param typePackageName Name of the package in which the type of this field is declared. + * @param typeName Name of the type of this field. + * @param completionName The completion for the field. + * @param modifiers The modifiers of this field. + * @param completionStart The start position of insertion of the name of this field. + * @param completionEnd The end position of insertion of the name of this field. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ +void acceptField( + char[] declaringTypePackageName, + char[] declaringTypeName, + char[] name, + char[] typePackageName, + char[] typeName, + char[] completionName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of an interface completion. + * + * @param packageName Declaring package name of the interface. + * @param className Name of the interface. + * @param completionName The completion for the interface. Can include ';' for imported interfaces. + * @param modifiers The modifiers of the interface. + * @param completionStart The start position of insertion of the name of the interface. + * @param completionEnd The end position of insertion of the name of the interface. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ +void acceptInterface( + char[] packageName, + char[] interfaceName, + char[] completionName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of a keyword completion. + * @param keywordName The keyword source. + * @param completionStart The start position of insertion of the name of this keyword. + * @param completionEnd The end position of insertion of the name of this keyword. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + */ +void acceptKeyword(char[] keywordName, int completionStart, int completionEnd, int relevance); +/** + * Code assist notification of a label completion. + * + * @param labelName The label source. + * @param completionStart The start position of insertion of the name of this label. + * @param completionEnd The end position of insertion of the name of this label. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + */ +void acceptLabel(char[] labelName, int completionStart, int completionEnd, int relevance); +/** + * Code assist notification of a local variable completion. + * + * @param name Name of the new local variable. + * @param typePackageName Name of the package in which the type of this new local variable is declared. + * @param typeName Name of the type of this new local variable. + * @param modifiers The modifiers of this new local variable. + * @param completionStart The start position of insertion of the name of this new local variable. + * @param completionEnd The end position of insertion of the name of this new local variable. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ +void acceptLocalVariable( + char[] name, + char[] typePackageName, + char[] typeName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of a method completion. + * + * @param declaringTypePackageName Name of the package in which the type that contains this new method is declared. + * @param declaringTypeName Name of the type declaring this new method. + * @param selector Name of the new method. + * @param parameterPackageNames Names of the packages in which the parameter types are declared. + * Should contain as many elements as parameterTypeNames. + * @param parameterTypeNames Names of the parameters types. + * Should contain as many elements as parameterPackageNames. + * @param returnTypePackageName Name of the package in which the return type is declared. + * @param returnTypeName Name of the return type of this new method, should be null for a constructor. + * @param completionName The completion for the method. Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it. + * @param modifiers The modifiers of this new method. + * @param completionStart The start position of insertion of the name of this new method. + * @param completionEnd The end position of insertion of the name of this new method. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. + */ +void acceptMethod( + char[] declaringTypePackageName, + char[] declaringTypeName, + char[] selector, + char[][] parameterPackageNames, + char[][] parameterTypeNames, + char[][] parameterNames, + char[] returnTypePackageName, + char[] returnTypeName, + char[] completionName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); + +/** + * Code assist notification of a method completion. + * + * @param declaringTypePackageName Name of the package in which the type that contains this new method is declared. + * @param declaringTypeName Name of the type declaring this new method. + * @param selector Name of the new method. + * @param parameterPackageNames Names of the packages in which the parameter types are declared. + * Should contain as many elements as parameterTypeNames. + * @param parameterTypeNames Names of the parameters types. + * Should contain as many elements as parameterPackageNames. + * @param returnTypePackageName Name of the package in which the return type is declared. + * @param returnTypeName Name of the return type of this new method, should be null for a constructor. + * @param completionName The completion for the method. Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it. + * @param modifiers The modifiers of this new method. + * @param completionStart The start position of insertion of the name of this new method. + * @param completionEnd The end position of insertion of the name of this new method. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + * + * NOTE: parameter names can be retrieved from the source model after the user selects a specific method. + */ +void acceptMethodDeclaration( + char[] declaringTypePackageName, + char[] declaringTypeName, + char[] selector, + char[][] parameterPackageNames, + char[][] parameterTypeNames, + char[][] parameterNames, + char[] returnTypePackageName, + char[] returnTypeName, + char[] completionName, + int modifiers, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of a modifier completion. + * + * @param modifierName The new modifier. + * @param completionStart The start position of insertion of the name of this new modifier. + * @param completionEnd The end position of insertion of the name of this new modifier. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + */ +void acceptModifier(char[] modifierName, int completionStart, int completionEnd, int relevance); +/** + * Code assist notification of a package completion. + * + * @param packageName The package name. + * @param completionName The completion for the package. Can include '.*;' for imports. + * @param completionStart The start position of insertion of the name of this new package. + * @param completionEnd The end position of insertion of the name of this new package. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package names are presented in their readable form: + * Package names are in the form "a.b.c". + * The default package is represented by an empty array. + */ +void acceptPackage( + char[] packageName, + char[] completionName, + int completionStart, + int completionEnd, + int relevance); +/** + * Code assist notification of a type completion. + * + * @param packageName Declaring package name of the type. + * @param typeName Name of the type. + * @param completionName The completion for the type. Can include ';' for imported types. + * @param completionStart The start position of insertion of the name of the type. + * @param completionEnd The end position of insertion of the name of the type. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ +void acceptType( + char[] packageName, + char[] typeName, + char[] completionName, + int completionStart, + int completionEnd, + int relevance); + +/** + * Code assist notification of a variable name completion. + * + * @param typePackageName Name of the package in which the type of this variable is declared. + * @param typeName Name of the type of this variable. + * @param name Name of the variable. + * @param completionName The completion for the variable. + * @param completionStart The start position of insertion of the name of this variable. + * @param completionEnd The end position of insertion of the name of this variable. + * @param relevance The relevance of the completion proposal + * It is a positive integer which are used for determine if this proposal is more relevant than another proposal. + * This value can only be used for compare relevance. A proposal is more relevant than another if his relevance + * value is higher. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ +void acceptVariableName( + char[] typePackageName, + char[] typeName, + char[] name, + char[] completionName, + int completionStart, + int completionEnd, + int relevance); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java new file mode 100644 index 0000000..51facdc --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IField.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Represents a field declared in a type. + *

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

    + */ +public interface IField extends IMember { +/** + * Returns the constant value associated with this field + * or null if this field has none. + * Returns either a subclass of Number, or a String, + * depending on the type of the field. + * For example, if the field is of type short, this returns + * a Short. + * + * @return the constant value associated with this field or null if this field has none. + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +public Object getConstant() throws JavaModelException; +/** + * Returns the simple name of this field. + * @return the simple name of this field. + */ +String getElementName(); +/** + * Returns the type signature of this field. + * + * @see Signature + * @return the type signature of this field. + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +String getTypeSignature() throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IInitializer.java new file mode 100644 index 0000000..5614f8d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IInitializer.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Represents a stand-alone instance or class (static) initializer in a type. + *

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

    + */ +public interface IInitializer extends IMember { +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java new file mode 100644 index 0000000..ef4851d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java @@ -0,0 +1,275 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IPath; + +/** + * Common protocol for all elements provided by the Java model. + * Java model elements are exposed to clients as handles to the actual underlying element. + * The Java model may hand out any number of handles for each element. Handles + * that refer to the same element are guaranteed to be equal, but not necessarily identical. + *

    + * Methods annotated as "handle-only" do not require underlying elements to exist. + * Methods that require underlying elements to exist throw + * a JavaModelException when an underlying element is missing. + * JavaModelException.isDoesNotExist can be used to recognize + * this common special case. + *

    + *

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

    + */ +public interface IJavaElement extends IAdaptable { + + /** + * Constant representing a Java model (workspace level object). + * A Java element with this type can be safely cast to IJavaModel. + */ + public static final int JAVA_MODEL = 1; + + /** + * Constant representing a Java project. + * A Java element with this type can be safely cast to IJavaProject. + */ + public static final int JAVA_PROJECT = 2; + + /** + * Constant representing a package fragment root. + * A Java element with this type can be safely cast to IPackageFragmentRoot. + */ + public static final int PACKAGE_FRAGMENT_ROOT = 3; + + /** + * Constant representing a package fragment. + * A Java element with this type can be safely cast to IPackageFragment. + */ + public static final int PACKAGE_FRAGMENT = 4; + + /** + * Constant representing a Java compilation unit. + * A Java element with this type can be safely cast to ICompilationUnit. + */ + public static final int COMPILATION_UNIT = 5; + + /** + * Constant representing a class file. + * A Java element with this type can be safely cast to IClassFile. + */ + public static final int CLASS_FILE = 6; + + /** + * Constant representing a type (a class or interface). + * A Java element with this type can be safely cast to IType. + */ + public static final int TYPE = 7; + + /** + * Constant representing a field. + * A Java element with this type can be safely cast to IField. + */ + public static final int FIELD = 8; + + /** + * Constant representing a method or constructor. + * A Java element with this type can be safely cast to IMethod. + */ + public static final int METHOD = 9; + + /** + * Constant representing a stand-alone instance or class initializer. + * A Java element with this type can be safely cast to IInitializer. + */ + public static final int INITIALIZER = 10; + + /** + * Constant representing a package declaration within a compilation unit. + * A Java element with this type can be safely cast to IPackageDeclaration. + */ + public static final int PACKAGE_DECLARATION = 11; + + /** + * Constant representing all import declarations within a compilation unit. + * A Java element with this type can be safely cast to IImportContainer. + */ + public static final int IMPORT_CONTAINER = 12; + + /** + * Constant representing an import declaration within a compilation unit. + * A Java element with this type can be safely cast to IImportDeclaration. + */ + public static final int IMPORT_DECLARATION = 13; + +/** + * Returns whether this Java element exists in the model. + * + * @return true if this element exists in the Java model + */ +boolean exists(); +/** + * Returns the first ancestor of this Java element that has the given type. + * Returns null if no such an ancestor can be found. + * This is a handle-only method. + * + * @param ancestorType the given type + * @return the first ancestor of this Java element that has the given type, null if no such an ancestor can be found + * @since 2.0 + */ +IJavaElement getAncestor(int ancestorType); +/** + * Returns the resource that corresponds directly to this element, + * or null if there is no resource that corresponds to + * this element. + *

    + * For example, the corresponding resource for an ICompilationUnit + * is its underlying IFile. The corresponding resource for + * an IPackageFragment that is not contained in an archive + * is its underlying IFolder. An IPackageFragment + * contained in an archive has no corresponding resource. Similarly, there + * are no corresponding resources for IMethods, + * IFields, etc. + *

    + * + * @return the corresponding resource, or null if none + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +IResource getCorrespondingResource() throws JavaModelException; +/** + * Returns the name of this element. This is a handle-only method. + * + * @return the element name + */ +String getElementName(); +/** + * Returns this element's kind encoded as an integer. + * This is a handle-only method. + * + * @return the kind of element; one of the constants declared in + * IJavaElement + * @see IJavaElement + */ +public int getElementType(); +/** + * Returns a string representation of this element handle. The format of + * the string is not specified; however, the identifier is stable across + * workspace sessions, and can be used to recreate this handle via the + * JavaCore.create(String) method. + * + * @return the string handle identifier + * @see JavaCore#create(java.lang.String) + */ +String getHandleIdentifier(); +/** + * Returns the Java model. + * This is a handle-only method. + * + * @return the Java model + */ +IJavaModel getJavaModel(); +/** + * Returns the Java project this element is contained in, + * or null if this element is not contained in any Java project + * (for instance, the IJavaModel is not contained in any Java + * project). + * This is a handle-only method. + * + * @return the containing Java project, or null if this element is + * not contained in a Java project + */ +IJavaProject getJavaProject(); +/** + * Returns the first openable parent. If this element is openable, the element + * itself is returned. Returns null if this element doesn't have + * an openable parent. + * This is a handle-only method. + * + * @return the first openable parent or null if this element doesn't have + * an openable parent. + * @since 2.0 + */ +IOpenable getOpenable(); +/** + * Returns the element directly containing this element, + * or null if this element has no parent. + * This is a handle-only method. + * + * @return the parent element, or null if this element has no parent + */ +IJavaElement getParent(); +/** + * Returns the path to the innermost resource enclosing this element. + * If this element is not included in an external archive, + * the path returned is the full, absolute path to the underlying resource, + * relative to the workbench. + * If this element is included in an external archive, + * the path returned is the absolute path to the archive in the file system. + * This is a handle-only method. + * + * @return the path to the innermost resource enclosing this element + * @since 2.0 + */ +IPath getPath(); +/** + * Returns the innermost resource enclosing this element. + * If this element is included in an archive and this archive is not external, + * this is the underlying resource corresponding to the archive. + * If this element is included in an external archive, null + * is returned. + * If this element is a working copy, null is returned. + * This is a handle-only method. + * + * @return the innermost resource enclosing this element, null if this + * element is a working copy or is included in an external archive + * @since 2.0 + */ +IResource getResource(); +/** + * Returns the smallest underlying resource that contains + * this element, or null if this element is not contained + * in a resource. + * + * @return the underlying resource, or null if none + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its underlying resource + */ +IResource getUnderlyingResource() throws JavaModelException; +/** + * Returns whether this Java element is read-only. An element is read-only + * if its structure cannot be modified by the java model. + *

    + * Note this is different from IResource.isReadOnly(). For example, .jar + * files are read-only as the java model doesn't know how to add/remove + * elements in this file, but the underlying IFile can be writable. + *

    + * This is a handle-only method. + * + * @return true if this element is read-only + */ +boolean isReadOnly(); +/** + * Returns whether the structure of this element is known. For example, for a + * compilation unit that could not be parsed, false is returned. + * If the structure of an element is unknown, navigations will return reasonable + * defaults. For example, getChildren will return an empty collection. + *

    + * Note: This does not imply anything about consistency with the + * underlying resource/buffer contents. + *

    + * + * @return true if the structure of this element is known + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +boolean isStructureKnown() throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java new file mode 100644 index 0000000..a9858d4 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java @@ -0,0 +1,221 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Represent the root Java element corresponding to the workspace. + * Since there is only one such root element, it is commonly referred to as + * the Java model element. + * The Java model element needs to be opened before it can be navigated or manipulated. + * The Java model element has no parent (it is the root of the Java element + * hierarchy). Its children are IJavaProjects. + *

    + * This interface provides methods for performing copy, move, rename, and + * delete operations on multiple Java elements. + *

    + *

    + * This interface is not intended to be implemented by clients. An instance + * of one of these handles can be created via + * JavaCore.create(workspace.getRoot()). + *

    + * + * @see JavaCore#create(org.eclipse.core.resources.IWorkspaceRoot) + */ +public interface IJavaModel extends IJavaElement, IOpenable, IParent { +/** + * Copies the given elements to the specified container(s). + * If one container is specified, all elements are copied to that + * container. If more than one container is specified, the number of + * elements and containers must match, and each element is copied to + * its associated container. + *

    + * Optionally, each copy can positioned before a sibling + * element. If null is specified for a given sibling, the copy + * is inserted as the last child of its associated container. + *

    + *

    + * Optionally, each copy can be renamed. If + * null is specified for the new name, the copy + * is not renamed. + *

    + *

    + * Optionally, any existing child in the destination container with + * the same name can be replaced by specifying true for + * force. Otherwise an exception is thrown in the event that a name + * collision occurs. + *

    + * + * @param elements the elements to copy + * @param containers the container, or list of containers + * @param siblings the list of siblings element any of which may be + * null; or null + * @param renamings the list of new names any of which may be + * null; or null + * @param replace true if any existing child in a target container + * with the target name should be replaced, and false to throw an + * exception in the event of a name collision + * @param monitor a progress monitor + * @exception JavaModelException if an element could not be copied. Reasons include: + *
      + *
    • A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • A container is of an incompatible type (INVALID_DESTINATION) + *
    • A sibling is not a child of it associated container (INVALID_SIBLING) + *
    • A new name is invalid (INVALID_NAME) + *
    • A child in its associated container already exists with the same + * name and replace has been specified as false (NAME_COLLISION) + *
    • A container or element is read-only (READ_ONLY) + *
    + */ +void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException; +/** + * Deletes the given elements, forcing the operation if necessary and specified. + * + * @param elements the elements to delete + * @param force a flag controlling whether underlying resources that are not + * in sync with the local file system will be tolerated + * @param monitor a progress monitor + * @exception JavaModelException if an element could not be deleted. Reasons include: + *
      + *
    • A specified element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • An element is read-only (READ_ONLY) + *
    + */ +void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException; +/** + * Returns the Java project with the given name. This is a handle-only method. + * The project may or may not exist. + * + * @return the Java project with the given name + */ +IJavaProject getJavaProject(String name); +/** + * Returns the Java projects in this Java model, or an empty array if there + * are none. + * + * @return the Java projects in this Java model, or an empty array if there + * are none + * @exception JavaModelException if this request fails. + */ +IJavaProject[] getJavaProjects() throws JavaModelException; +/** + * Returns the workspace associated with this Java model. + * + * @return the workspace associated with this Java model + */ +IWorkspace getWorkspace(); +/** + * Moves the given elements to the specified container(s). + * If one container is specified, all elements are moved to that + * container. If more than one container is specified, the number of + * elements and containers must match, and each element is moved to + * its associated container. + *

    + * Optionally, each element can positioned before a sibling + * element. If null is specified for sibling, the element + * is inserted as the last child of its associated container. + *

    + *

    + * Optionally, each element can be renamed. If + * null is specified for the new name, the element + * is not renamed. + *

    + *

    + * Optionally, any existing child in the destination container with + * the same name can be replaced by specifying true for + * force. Otherwise an exception is thrown in the event that a name + * collision occurs. + *

    + * + * @param elements the elements to move + * @param containers the container, or list of containers + * @param siblings the list of siblings element any of which may be + * null; or null + * @param renamings the list of new names any of which may be + * null; or null + * @param replace true if any existing child in a target container + * with the target name should be replaced, and false to throw an + * exception in the event of a name collision + * @param monitor a progress monitor + * @exception JavaModelException if an element could not be moved. Reasons include: + *
      + *
    • A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • A container is of an incompatible type (INVALID_DESTINATION) + *
    • A sibling is not a child of it associated container (INVALID_SIBLING) + *
    • A new name is invalid (INVALID_NAME) + *
    • A child in its associated container already exists with the same + * name and replace has been specified as false (NAME_COLLISION) + *
    • A container or element is read-only (READ_ONLY) + *
    + * + * @exception IllegalArgumentException any element or container is null + */ +void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException; + +/** + * Triggers an update of the JavaModel with respect to the referenced external archives. + * This operation will issue a JavaModel delta describing the discovered changes, in term + * of Java element package fragment roots added, removed or changed. + * Note that a collection of elements can be passed so as to narrow the set of archives + * to refresh (passing null along is equivalent to refreshing the entire mode). + * The elements can be: + *
      + *
    • package fragment roots corresponding to external archives + *
    • Java projects, which referenced external archives will be refreshed + *
    • Java model, all referenced external archives will be refreshed. + *
    + *

    In case an archive is used by multiple projects, the delta issued will account for + * all of them. This means that even if a project was not part of the elements scope, it + * may still be notified of changes if it is referencing a library comprised in the scope. + *

    + * @param elementsScope - a collection of elements defining the scope of the refresh + * @param monitor - a progress monitor used to report progress + * @exception JavaModelException in one of the corresponding situation: + *

      + *
    • an exception occurs while accessing project resources
    • + *
    + * + * @see IJavaElementDelta + * @since 2.0 + */ +void refreshExternalArchives(IJavaElement[] elementsScope, IProgressMonitor monitor) throws JavaModelException; + +/** + * Renames the given elements as specified. + * If one container is specified, all elements are renamed within that + * container. If more than one container is specified, the number of + * elements and containers must match, and each element is renamed within + * its associated container. + * + * @param elements the elements to rename + * @param destinations the container, or list of containers + * @param names the list of new names + * @param replace true if an existing child in a target container + * with the target name should be replaced, and false to throw an + * exception in the event of a name collision + * @param monitor a progress monitor + * @exception JavaModelException if an element could not be renamed. Reasons include: + *
      + *
    • A specified element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • A new name is invalid (INVALID_NAME) + *
    • A child already exists with the same name and replace has been specified as false (NAME_COLLISION) + *
    • An element is read-only (READ_ONLY) + *
    + */ +void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] names, boolean replace, IProgressMonitor monitor) throws JavaModelException; + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java new file mode 100644 index 0000000..27a8452 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatus.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; + +/** + * Represents the outcome of an Java model operation. Status objects are + * used inside JavaModelException objects to indicate what went + * wrong. + *

    + * Java model status object are distinguished by their plug-in id: + * getPlugin returns "net.sourceforge.phpdt.core". + * getCode returns one of the status codes declared in + * IJavaModelStatusConstants. + *

    + *

    + * A Java model status may also carry additional information (that is, in + * addition to the information defined in IStatus): + *

      + *
    • elements - optional handles to Java elements associated with the failure
    • + *
    • string - optional string associated with the failure
    • + *
    + *

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

    + * + * @see org.eclipse.core.runtime.IStatus + * @see IJavaModelStatusConstants + */ +public interface IJavaModelStatus extends IStatus { +/** + * Returns any Java elements associated with the failure (see specification + * of the status code), or an empty array if no elements are related to this + * particular status code. + * + * @return the list of Java element culprits + * @see IJavaModelStatusConstants + */ +IJavaElement[] getElements(); +/** + * Returns the path associated with the failure (see specification + * of the status code), or null if the failure is not + * one of DEVICE_PATH, INVALID_PATH, + * PATH_OUTSIDE_PROJECT, or RELATIVE_PATH. + * + * @return the path that caused the failure, or null if none + * @see IJavaModelStatusConstants#DEVICE_PATH + * @see IJavaModelStatusConstants#INVALID_PATH + * @see IJavaModelStatusConstants#PATH_OUTSIDE_PROJECT + * @see IJavaModelStatusConstants#RELATIVE_PATH + */ +IPath getPath(); +/** + * Returns the string associated with the failure (see specification + * of the status code), or null if no string is related to this + * particular status code. + * + * @return the string culprit, or null if none + * @see IJavaModelStatusConstants + */ +String getString(); +/** + * Returns whether this status indicates that a Java model element does not exist. + * This convenience method is equivalent to + * getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST. + * + * @return true if the status code indicates that a Java model + * element does not exist + * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST + */ +boolean isDoesNotExist(); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java new file mode 100644 index 0000000..7eea239 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelStatusConstants.java @@ -0,0 +1,252 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Status codes used with Java model status objects. + *

    + * This interface declares constants only; it is not intended to be implemented + * or extended. + *

    + * + * @see IJavaModelStatus + * @see org.eclipse.core.runtime.IStatus#getCode() + */ +public interface IJavaModelStatusConstants { + + /** + * Status constant indicating that a container path was resolved + * to invalid entries (null or container). + * + * @since 2.0 + */ + public static final int INVALID_CP_CONTAINER_ENTRY = 962; + + /** + * Status constant indicating that a container path was not resolvable + * indicating either the referred container is undefined, unbound. + * + * @since 2.0 + */ + public static final int CP_CONTAINER_PATH_UNBOUND = 963; + + /** + * Status constant indicating that a classpath entry was invalid + */ + public static final int INVALID_CLASSPATH = 964; + + /** + * Status constant indicating that a variable path was not resolvable + * indicating either the referred variable is undefined, unbound or the resolved + * variable path does not correspond to an existing file or folder. + */ + public static final int CP_VARIABLE_PATH_UNBOUND = 965; + + /** + * Status constant indicating a core exception occurred. + * Use getException to retrieve a CoreException. + */ + public static final int CORE_EXCEPTION = 966; + + /** + * Status constant indicating one or more of the elements + * supplied are not of a valid type for the operation to + * process. + * The element(s) can be retrieved using getElements on the status object. + */ + public static final int INVALID_ELEMENT_TYPES = 967; + + /** + * Status constant indicating that no elements were + * provided to the operation for processing. + */ + public static final int NO_ELEMENTS_TO_PROCESS = 968; + + /** + * Status constant indicating that one or more elements + * supplied do not exist. + * The element(s) can be retrieved using getElements on the status object. + * + * @see IJavaModelStatus#isDoesNotExist + */ + public static final int ELEMENT_DOES_NOT_EXIST = 969; + + /** + * Status constant indicating that a null path was + * supplied to the operation. + */ + public static final int NULL_PATH = 970; + + /** + * Status constant indicating that a path outside of the + * project was supplied to the operation. The path can be retrieved using + * getPath on the status object. + */ + public static final int PATH_OUTSIDE_PROJECT = 971; + + /** + * Status constant indicating that a relative path + * was supplied to the operation when an absolute path is + * required. The path can be retrieved using getPath on the + * status object. + */ + public static final int RELATIVE_PATH = 972; + + /** + * Status constant indicating that a path specifying a device + * was supplied to the operation when a path with no device is + * required. The path can be retrieved using getPath on the + * status object. + */ + public static final int DEVICE_PATH = 973; + + /** + * Status constant indicating that a string + * was supplied to the operation that was null. + */ + public static final int NULL_STRING = 974; + + /** + * Status constant indicating that the operation encountered + * a read-only element. + * The element(s) can be retrieved using getElements on the status object. + */ + public static final int READ_ONLY = 976; + + /** + * Status constant indicating that a naming collision would occur + * if the operation proceeded. + */ + public static final int NAME_COLLISION = 977; + + /** + * Status constant indicating that a destination provided for a copy/move/rename operation + * is invalid. + * The destination element can be retrieved using getElements on the status object. + */ + public static final int INVALID_DESTINATION = 978; + + /** + * Status constant indicating that a path provided to an operation + * is invalid. The path can be retrieved using getPath on the + * status object. + */ + public static final int INVALID_PATH = 979; + + /** + * Status constant indicating the given source position is out of bounds. + */ + public static final int INDEX_OUT_OF_BOUNDS = 980; + + /** + * Status constant indicating there is an update conflict + * for a working copy. The compilation unit on which the + * working copy is based has changed since the working copy + * was created. + */ + public static final int UPDATE_CONFLICT = 981; + + /** + * Status constant indicating that null was specified + * as a name argument. + */ + public static final int NULL_NAME = 982; + + /** + * Status constant indicating that a name provided is not syntactically correct. + * The name can be retrieved from getString. + */ + public static final int INVALID_NAME = 983; + + /** + * Status constant indicating that the specified contents + * are not valid. + */ + public static final int INVALID_CONTENTS = 984; + + /** + * Status constant indicating that an java.io.IOException + * occurred. + */ + public static final int IO_EXCEPTION = 985; + + /** + * Status constant indicating that a DOMException + * occurred. + */ + public static final int DOM_EXCEPTION = 986; + + /** + * Status constant indicating that a TargetException + * occurred. + */ + public static final int TARGET_EXCEPTION = 987; + + /** + * Status constant indicating that the Java builder + * could not be initialized. + */ + public static final int BUILDER_INITIALIZATION_ERROR = 990; + + /** + * Status constant indicating that the Java builder's last built state + * could not be serialized or deserialized. + */ + public static final int BUILDER_SERIALIZATION_ERROR = 991; + + /** + * Status constant indicating that an error was encountered while + * trying to evaluate a code snippet, or other item. + */ + public static final int EVALUATION_ERROR = 992; + + /** + * Status constant indicating that a sibling specified is not valid. + */ + public static final int INVALID_SIBLING = 993; + + /** + * Status indicating that a Java element could not be created because + * the underlying resource is invalid. + * @see JavaCore + */ + public static final int INVALID_RESOURCE = 995; + + /** + * Status indicating that a Java element could not be created because + * the underlying resource is not of an appropriate type. + * @see JavaCore + */ + public static final int INVALID_RESOURCE_TYPE = 996; + + /** + * Status indicating that a Java element could not be created because + * the project owning underlying resource does not have the Java nature. + * @see JavaCore + */ + public static final int INVALID_PROJECT = 997; + + /** + * Status indicating that the package declaration in a ICompilationUnit + * does not correspond to the IPackageFragment it belongs to. + * The getString method of the associated status object + * gives the name of the package in which the ICompilationUnit is + * declared. + */ + public static final int INVALID_PACKAGE = 998; + + /** + * Status indicating that the corresponding resource has no local contents yet. + * This might happen when attempting to use a resource before its contents + * has been made locally available. + */ + public static final int NO_LOCAL_CONTENTS = 999; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java new file mode 100644 index 0000000..c9e71e7 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java @@ -0,0 +1,503 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IPath; + +//import net.sourceforge.phpdt.core.eval.IEvaluationContext; + +/** + * A Java project represents a view of a project resource in terms of Java + * elements such as package fragments, types, methods and fields. + * A project may contain several package roots, which contain package fragments. + * A package root corresponds to an underlying folder or JAR. + *

    + * Each Java project has a classpath, defining which folders contain source code and + * where required libraries are located. Each Java project also has an output location, + * defining where the builder writes .class files. A project that + * references packages in another project can access the packages by including + * the required project in a classpath entry. The Java model will present the + * source elements in the required project, and when building, the compiler will + * use the binaries from that project (that is, the output location of the + * required project is used as a library). The classpath format is a sequence + * of classpath entries describing the location and contents of package fragment + * roots. + *

    + * Java project elements need to be opened before they can be navigated or manipulated. + * The children of a Java project are the package fragment roots that are + * defined by the classpath and contained in this project (in other words, it + * does not include package fragment roots for other projects). + *

    + *

    + * This interface is not intended to be implemented by clients. An instance + * of one of these handles can be created via + * JavaCore.create(project). + *

    + * + * @see JavaCore#create(org.eclipse.core.resources.IProject) + * @see IClasspathEntry + */ +public interface IJavaProject extends IParent, IJavaElement, IOpenable { + + /** + * Returns the IJavaElement corresponding to the given + * classpath-relative path, or null if no such + * IJavaElement is found. The result is one of an + * ICompilationUnit, IClassFile, or + * IPackageFragment. + *

    + * When looking for a package fragment, there might be several potential + * matches; only one of them is returned. + * + *

    For example, the path "java/lang/Object.java", would result in the + * ICompilationUnit or IClassFile corresponding to + * "java.lang.Object". The path "java/lang" would result in the + * IPackageFragment for "java.lang". + * @param path the given classpath-relative path + * @exception JavaModelException if the given path is null + * or absolute + * @return the IJavaElement corresponding to the given + * classpath-relative path, or null if no such + * IJavaElement is found + */ + IJavaElement findElement(IPath path) throws JavaModelException; + + /** + * Returns the first existing package fragment on this project's classpath + * whose path matches the given (absolute) path, or null if none + * exist. + * The path can be: + * - internal to the workbench: "/Project/src" + * - external to the workbench: "c:/jdk/classes.zip/java/lang" + * @param path the given absolute path + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return the first existing package fragment on this project's classpath + * whose path matches the given (absolute) path, or null if none + * exist + */ + //IPackageFragment findPackageFragment(IPath path) throws JavaModelException; + + /** + * Returns the existing package fragment root on this project's classpath + * whose path matches the given (absolute) path, or null if + * one does not exist. + * The path can be: + * - internal to the workbench: "/Compiler/src" + * - external to the workbench: "c:/jdk/classes.zip" + * @param path the given absolute path + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return the existing package fragment root on this project's classpath + * whose path matches the given (absolute) path, or null if + * one does not exist + */ + // IPackageFragmentRoot findPackageFragmentRoot(IPath path) + // throws JavaModelException; + /** + * Returns the first type found following this project's classpath + * with the given fully qualified name or null if none is found. + * The fully qualified name is a dot-separated name. For example, + * a class B defined as a member type of a class A in package x.y should have a + * the fully qualified name "x.y.A.B". + * + * @param fullyQualifiedName the given fully qualified name + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return the first type found following this project's classpath + * with the given fully qualified name or null if none is found + * @see IType#getFullyQualifiedName(char) + * @since 2.0 + */ + IType findType(String fullyQualifiedName) throws JavaModelException; + /** + * Returns the first type found following this project's classpath + * with the given package name and type qualified name + * or null if none is found. + * The package name is a dot-separated name. + * The type qualified name is also a dot-separated name. For example, + * a class B defined as a member type of a class A should have the + * type qualified name "A.B". + * + * @param packageName the given package name + * @param typeQualifiedName the given type qualified name + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return the first type found following this project's classpath + * with the given package name and type qualified name + * or null if none is found + * @see IType#getTypeQualifiedName(char) + * @since 2.0 + */ + IType findType(String packageName, String typeQualifiedName) throws JavaModelException; + + /** + * Returns all of the existing package fragment roots that exist + * on the classpath, in the order they are defined by the classpath. + * + * @return all of the existing package fragment roots that exist + * on the classpath + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ + // IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException; + + /** + * Returns an array of non-Java resources directly contained in this project. + * It does not transitively answer non-Java resources contained in folders; + * these would have to be explicitly iterated over. + * @return an array of non-Java resources directly contained in this project + */ + Object[] getNonJavaResources() throws JavaModelException; + + /** + * Returns the full path to the location where the builder writes + * .class files. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return the full path to the location where the builder writes + * .class files + */ + IPath getOutputLocation() throws JavaModelException; + + /** + * Returns a package fragment root for the JAR at the specified file system path. + * This is a handle-only method. The underlying java.io.File + * may or may not exist. No resource is associated with this local JAR + * package fragment root. + * + * @param jarPath the jars's file system path + * @return a package fragment root for the JAR at the specified file system path + */ + // IPackageFragmentRoot getPackageFragmentRoot(String jarPath); + + /** + * Returns a package fragment root for the given resource, which + * must either be a folder representing the top of a package hierarchy, + * or a .jar or .zip file. + * This is a handle-only method. The underlying resource may or may not exist. + * + * @param resource the given resource + * @return a package fragment root for the given resource, which + * must either be a folder representing the top of a package hierarchy, + * or a .jar or .zip file + */ + // IPackageFragmentRoot getPackageFragmentRoot(IResource resource); + + /** + * Returns all of the package fragment roots contained in this + * project, identified on this project's resolved classpath. The result + * does not include package fragment roots in other projects referenced + * on this project's classpath. + * + *

    NOTE: This is equivalent to getChildren(). + * + * @return all of the package fragment roots contained in this + * project, identified on this project's resolved classpath + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ + // IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException; + + /** + * Returns the existing package fragment roots identified by the given entry. + * Note that a classpath entry that refers to another project may + * have more than one root (if that project has more than on root + * containing source), and classpath entries within the current + * project identify a single root. + *

    + * If the classpath entry denotes a variable, it will be resolved and return + * the roots of the target entry (empty if not resolvable). + *

    + * If the classpath entry denotes a container, it will be resolved and return + * the roots corresponding to the set of container entries (empty if not resolvable). + * + * @param entry the given entry + * @return the existing package fragment roots identified by the given entry + * @see IClasspathContainer + */ + // IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry); + + /** + * Returns all package fragments in all package fragment roots contained + * in this project. This is a convenience method. + * + * Note that the package fragment roots corresponds to the resolved + * classpath of the project. + * + * @return all package fragments in all package fragment roots contained + * in this project + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ + // IPackageFragment[] getPackageFragments() throws JavaModelException; + + /** + * Returns the IProject on which this IJavaProject + * was created. This is handle-only method. + * + * @return the IProject on which this IJavaProject + * was created + */ + IProject getProject(); + + /** + * This is a helper method returning the resolved classpath for the project, as a list of classpath entries, + * where all classpath variable entries have been resolved and substituted with their final target entries. + *

    + * A resolved classpath corresponds to a particular instance of the raw classpath bound in the context of + * the current values of the referred variables, and thus should not be persisted. + *

    + * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows + * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath + * can simply refer to some variables defining the proper locations of these external JARs. + *

    + * The boolean argument ignoreUnresolvedVariable allows to specify how to handle unresolvable variables, + * when set to true, missing variables are simply ignored, the resulting path is then only formed of the + * resolvable entries, without any indication about which variable(s) was ignored. When set to false, a + * JavaModelException will be thrown for the first unresolved variable (from left to right). + * + * @exception JavaModelException in one of the corresponding situation: + *

      + *
    • this element does not exist
    • + *
    • an exception occurs while accessing its corresponding resource
    • + *
    • a classpath variable was not resolvable and ignoreUnresolvedVariable was set to false.
    • + *
    + * @return + * @see IClasspathEntry + */ + // IClasspathEntry[] getExpandedClasspath(boolean ignoreUnresolvedVariable) + // throws JavaModelException; + + /** + * Returns the raw classpath for the project, as a list of classpath entries. This corresponds to the exact set + * of entries which were assigned using setRawClasspath, in particular such a classpath may contain + * classpath variable entries. Classpath variable entries can be resolved individually (see JavaCore#getClasspathVariable), + * or the full classpath can be resolved at once using the helper method getResolvedClasspath. + *

    + * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows + * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath + * can simply refer to some variables defining the proper locations of these external JARs. + *

    + * Note that in case the project isn't yet opened, the classpath will directly be read from the associated .classpath file. + *

    + * + * @return the raw classpath for the project, as a list of classpath entries + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @see IClasspathEntry + */ + // IClasspathEntry[] getRawClasspath() throws JavaModelException; + + /** + * Returns the names of the projects that are directly required by this + * project. A project is required if it is in its classpath. + * + * @return the names of the projects that are directly required by this + * project + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ + String[] getRequiredProjectNames() throws JavaModelException; + + /** + * This is a helper method returning the resolved classpath for the project, as a list of classpath entries, + * where all classpath variable entries have been resolved and substituted with their final target entries. + *

    + * A resolved classpath corresponds to a particular instance of the raw classpath bound in the context of + * the current values of the referred variables, and thus should not be persisted. + *

    + * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows + * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath + * can simply refer to some variables defining the proper locations of these external JARs. + *

    + * The boolean argument ignoreUnresolvedVariable allows to specify how to handle unresolvable variables, + * when set to true, missing variables are simply ignored, the resulting path is then only formed of the + * resolvable entries, without any indication about which variable(s) was ignored. When set to false, a + * JavaModelException will be thrown for the first unresolved variable (from left to right). + * + * @param ignoreUnresolvedVariable specify how to handle unresolvable variables + * @return the resolved classpath for the project, as a list of classpath entries, + * where all classpath variable entries have been resolved and substituted with their final target entries + * @exception JavaModelException in one of the corresponding situation: + *

      + *
    • this element does not exist
    • + *
    • an exception occurs while accessing its corresponding resource
    • + *
    • a classpath variable was not resolvable and ignoreUnresolvedVariable was set to false.
    • + *
    + * @see IClasspathEntry + */ + // IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedVariable) throws JavaModelException; + + /** + * Returns whether this project has been built at least once and thus whether it has a build state. + * @return true if this project has been built at least once, false otherwise + */ + boolean hasBuildState(); + + /** + * Returns whether setting this project's classpath to the given classpath entries + * would result in a cycle. + * + * If the set of entries contains some variables, those are resolved in order to determine + * cycles. + * + * @param entries the given classpath entries + * @return true if the given classpath entries would result in a cycle, false otherwise + */ + // boolean hasClasspathCycle(IClasspathEntry[] entries); + /** + * Returns whether the given element is on the classpath of this project. + * + * @param element the given element + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return true if the given element is on the classpath of this project, false otherwise + * @since 2.0 + */ + boolean isOnClasspath(IJavaElement element) throws JavaModelException; + + /** + * Creates a new evaluation context. + * @return a new evaluation context. + */ + // IEvaluationContext newEvaluationContext(); + + /** + * Creates and returns a type hierarchy for all types in the given + * region, considering subtypes within that region. + * + * @param monitor the given progress monitor + * @param region the given region + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @exception IllegalArgumentException if region is null + * @return a type hierarchy for all types in the given + * region, considering subtypes within that region + */ + // ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor) + // throws JavaModelException; + + /** + * Creates and returns a type hierarchy for the given type considering + * subtypes in the specified region. + * + * @param monitor the given monitor + * @param region the given region + * @param type the given type + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * + * @exception IllegalArgumentException if type or region is null + * @return a type hierarchy for the given type considering + * subtypes in the specified region + */ + // ITypeHierarchy newTypeHierarchy( + // IType type, + // IRegion region, + // IProgressMonitor monitor) + // throws JavaModelException; + + /** + * Sets the output location of this project to the location + * described by the given absolute path. + *

    + * + * @param path the given absolute path + * @param monitor the given progress monitor + * + * @exception JavaModelException if the classpath could not be set. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The path refers to a location not contained in this project (PATH_OUTSIDE_PROJECT) + *
    • The path is not an absolute path (RELATIVE_PATH) + *
    • The path is nested inside a package fragment root of this project (INVALID_PATH) + *
    • The output location is being modified during resource change event notification (CORE_EXCEPTION) + *
    + */ + void setOutputLocation(IPath path, IProgressMonitor monitor) throws JavaModelException; + + /** + * Sets the classpath of this project using a list of classpath entries. In particular such a classpath may contain + * classpath variable entries. Classpath variable entries can be resolved individually (see JavaCore#getClasspathVariable), + * or the full classpath can be resolved at once using the helper method getResolvedClasspath. + *

    + * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows + * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath + * can simply refer to some variables defining the proper locations of these external JARs. + *

    + * Setting the classpath to null specifies a default classpath + * (the project root). Setting the classpath to an empty array specifies an + * empty classpath. + *

    + * If a cycle is detected while setting this classpath, an error marker will be added + * to the project closing the cycle. + * To avoid this problem, use hasClasspathCycle(IClasspathEntry[] entries) + * before setting the classpath. + * + * @param entries a list of classpath entries + * @param monitor the given progress monitor + * @exception JavaModelException if the classpath could not be set. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The classpath is being modified during resource change event notification (CORE_EXCEPTION) + *
    • The classpath failed the validation check as defined by JavaConventions#validateClasspath + *
    + * @see IClasspathEntry + */ + // void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) + // throws JavaModelException; + + /** + * Sets the both the classpath of this project and its output location at once. + * The classpath is defined using a list of classpath entries. In particular such a classpath may contain + * classpath variable entries. Classpath variable entries can be resolved individually (see JavaCore#getClasspathVariable), + * or the full classpath can be resolved at once using the helper method getResolvedClasspath. + *

    + * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows + * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath + * can simply refer to some variables defining the proper locations of these external JARs. + *

    + * Setting the classpath to null specifies a default classpath + * (the project root). Setting the classpath to an empty array specifies an + * empty classpath. + *

    + * If a cycle is detected while setting this classpath, an error marker will be added + * to the project closing the cycle. + * To avoid this problem, use hasClasspathCycle(IClasspathEntry[] entries) + * before setting the classpath. + * + * @param entries a list of classpath entries + * @param monitor the given progress monitor + * @param outputLocation the given output location + * + * @exception JavaModelException if the classpath could not be set. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • Two or more entries specify source roots with the same or overlapping paths (NAME_COLLISION) + *
    • A entry of kind CPE_PROJECT refers to this project (INVALID_PATH) + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • The output location path refers to a location not contained in this project (PATH_OUTSIDE_PROJECT) + *
    • The output location path is not an absolute path (RELATIVE_PATH) + *
    • The output location path is nested inside a package fragment root of this project (INVALID_PATH) + *
    • The classpath is being modified during resource change event notification (CORE_EXCEPTION) + *
    + * @see IClasspathEntry + * @since 2.0 + */ + // void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, IProgressMonitor monitor) + // throws JavaModelException; +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java new file mode 100644 index 0000000..7e532ec --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Common protocol for Java elements that can be members of types. + * This set consists of IType, IMethod, + * IField, and IInitializer. + *

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

    + */ +public interface IMember extends IJavaElement, ISourceReference, ISourceManipulation { +/** + * Returns the class file in which this member is declared, or null + * if this member is not declared in a class file (for example, a source type). + * This is a handle-only method. + * + * @return the class file in which this member is declared, or null + * if this member is not declared in a class file (for example, a source type) + */ +// IClassFile getClassFile(); +/** + * Returns the compilation unit in which this member is declared, or null + * if this member is not declared in a compilation unit (for example, a binary type). + * This is a handle-only method. + * + * @return the compilation unit in which this member is declared, or null + * if this member is not declared in a compilation unit (for example, a binary type) + */ +ICompilationUnit getCompilationUnit(); +/** + * Returns the type in which this member is declared, or null + * if this member is not declared in a type (for example, a top-level type). + * This is a handle-only method. + * + * @return the type in which this member is declared, or null + * if this member is not declared in a type (for example, a top-level type) + */ +IType getDeclaringType(); +/** + * Returns the modifier flags for this member. The flags can be examined using class + * Flags. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the modifier flags for this member + * @see Flags + */ +int getFlags() throws JavaModelException; +/** + * Returns the source range of this member's simple name, + * or null if this member does not have a name + * (for example, an initializer), or if this member does not have + * associated source code (for example, a binary type). + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the source range of this member's simple name, + * or null if this member does not have a name + * (for example, an initializer), or if this member does not have + * associated source code (for example, a binary type) + */ +ISourceRange getNameRange() throws JavaModelException; +/** + * Returns whether this member is from a class file. + * This is a handle-only method. + * + * @return true if from a class file, and false if + * from a compilation unit + */ +boolean isBinary(); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java new file mode 100644 index 0000000..2dd7cc3 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMethod.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Represents a method (or constructor) declared in a type. + *

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

    + */ +public interface IMethod extends IMember { +/** + * Returns the simple name of this method. + * For a constructor, this returns the simple name of the declaring type. + * Note: This holds whether the constructor appears in a source or binary type + * (even though class files internally define constructor names to be "<init>"). + * For the class initialization methods in binary types, this returns + * the special name "<clinit>". + * This is a handle-only method. + */ +String getElementName(); +/** + * Returns the type signatures of the exceptions this method throws, + * in the order declared in the source. Returns an empty array + * if this method throws no exceptions. + * + *

    For example, a source method declaring "throws IOException", + * would return the array {"QIOException;"}. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the type signatures of the exceptions this method throws, + * in the order declared in the source, an empty array if this method throws no exceptions + * @see Signature + */ +String[] getExceptionTypes() throws JavaModelException; +/** + * Returns the number of parameters of this method. + * This is a handle-only method. + * + * @return the number of parameters of this method + */ +int getNumberOfParameters(); +/** + * Returns the names of parameters in this method. + * For binary types, these names are invented as "arg"+i, where i starts at 1 + * (even if source is associated with the binary). + * Returns an empty array if this method has no parameters. + * + *

    For example, a method declared as public void foo(String text, int length) + * would return the array {"text","length"}. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the names of parameters in this method, an empty array if this method has no parameters + */ +String[] getParameterNames() throws JavaModelException; +/** + * Returns the type signatures for the parameters of this method. + * Returns an empty array if this method has no parameters. + * This is a handle-only method. + * + *

    For example, a source method declared as public void foo(String text, int length) + * would return the array {"QString;","I"}. + * + * @return the type signatures for the parameters of this method, an empty array if this method has no parameters + * @see Signature + */ +String[] getParameterTypes(); +/** + * Returns the type signature of the return value of this method. + * For constructors, this returns the signature for void. + * + *

    For example, a source method declared as public String getName() + * would return "QString;". + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the type signature of the return value of this method, void for constructors + * @see Signature + */ +String getReturnType() throws JavaModelException; +/** + * Returns the signature of the method. This includes the signatures for the parameter + * types and return type, but does not include the method name or exception types. + * + *

    For example, a source method declared as public void foo(String text, int length) + * would return "(QString;I)V". + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * + * @see Signature + */ +String getSignature() throws JavaModelException; +/** + * Returns whether this method is a constructor. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * + * @return true if this method is a constructor, false otherwise + */ +boolean isConstructor() throws JavaModelException; +/** + * Returns whether this method is a main method. + * It is a main method if: + *

      + *
    • its name is equal to "main"
    • + *
    • its return type is void
    • + *
    • it is static and public
    • + *
    • it defines one parameter whose type's simple name is String[]
    • + *
    + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @since 2.0 + * @return true if this method is a main method, false otherwise + */ +boolean isMainMethod() throws JavaModelException; +/** + * Returns whether this method is similar to the given method. + * Two methods are similar if: + *
      + *
    • their element names are equal
    • + *
    • they have the same number of parameters
    • + *
    • the simple names of their parameter types are equal
    • + *
    + * This is a handle-only method. + * + * @param method the given method + * @return true if this method is similar to the given method. + * @see Signature#getSimpleName + * @since 2.0 + */ +boolean isSimilar(IMethod method); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java new file mode 100644 index 0000000..e0e17e3 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java @@ -0,0 +1,168 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Common protocol for Java elements that must be opened before they can be + * navigated or modified. Opening a textual element (such as a compilation unit) + * involves opening a buffer on its contents. While open, any changes to the buffer + * can be reflected in the element's structure; + * see isConsistent and makeConsistent(IProgressMonitor). + *

    + * To reduce complexity in clients, elements are automatically opened + * by the Java model as element properties are accessed. The Java model maintains + * an LRU cache of open elements, and automatically closes elements as they + * are swapped out of the cache to make room for other elements. Elements with + * unsaved changes are never removed from the cache, and thus, if the client + * maintains many open elements with unsaved + * changes, the LRU cache can grow in size (in this case the cache is not + * bounded). However, as elements are saved, the cache will shrink back to its + * original bounded size. + *

    + *

    + * To open an element, all openable parent elements must be open. + * The Java model automatically opens parent elements, as it automatically opens elements. + * Opening an element may provide access to direct children and other descendants, + * but does not automatically open any descendents which are themselves IOpenable. + * For example, opening a compilation unit provides access to all its constituent elements, + * but opening a package fragment does not open all compilation units in the package fragment. + *

    + *

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

    + */ +public interface IOpenable { + +/** + * Closes this element and its buffer (if any). + * Closing an element which is not open has no effect. + * + *

    Note: although close is exposed in the API, clients are + * not expected to open and close elements - the Java model does this automatically + * as elements are accessed. + * + * @exception JavaModelException if an error occurs closing this element + */ +public void close() throws JavaModelException; +/** + * Returns the buffer opened for this element, or null + * if this element does not have a buffer. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the buffer opened for this element, or null + * if this element does not have a buffer + */ +public IBuffer getBuffer() throws JavaModelException; +/** + * Returns true if this element is open and: + *

      + *
    • its buffer has unsaved changes, or + *
    • one of its descendants has unsaved changes, or + *
    • a working copy has been created on one of this + * element's children and has not yet destroyed + *
    + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if this element is open and: + *
      + *
    • its buffer has unsaved changes, or + *
    • one of its descendants has unsaved changes, or + *
    • a working copy has been created on one of this + * element's children and has not yet destroyed + *
    + */ +boolean hasUnsavedChanges() throws JavaModelException; +/** + * Returns whether the element is consistent with its underlying resource or buffer. + * The element is consistent when opened, and is consistent if the underlying resource + * or buffer has not been modified since it was last consistent. + * + *

    NOTE: Child consistency is not considered. For example, a package fragment + * responds true when it knows about all of its + * compilation units present in its underlying folder. However, one or more of + * the compilation units could be inconsistent. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if the element is consistent with its underlying resource or buffer, false otherwise. + * @see IOpenable#makeConsistent + */ +boolean isConsistent() throws JavaModelException; +/** + * Returns whether this openable is open. This is a handle-only method. + * @return true if this openable is open, false otherwise + */ +boolean isOpen(); +/** + * Makes this element consistent with its underlying resource or buffer + * by updating the element's structure and properties as necessary. + * + * @param progress the given progress monitor + * @exception JavaModelException if the element is unable to access the contents + * of its underlying resource. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @see IOpenable#isConsistent + */ +void makeConsistent(IProgressMonitor progress) throws JavaModelException; +/** + * Opens this element and all parent elements that are not already open. + * For compilation units, a buffer is opened on the contents of the underlying resource. + * + *

    Note: although open is exposed in the API, clients are + * not expected to open and close elements - the Java model does this automatically + * as elements are accessed. + * + * @param progress the given progress monitor + * @exception JavaModelException if an error occurs accessing the contents + * of its underlying resource. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + */ +public void open(IProgressMonitor progress) throws JavaModelException; +/** + * Saves any changes in this element's buffer to its underlying resource + * via a workspace resource operation. This has no effect if the element has no underlying + * buffer, or if there are no unsaved changed in the buffer. + *

    + * The force parameter controls how this method deals with + * cases where the workbench is not completely in sync with the local file system. + * If false is specified, this method will only attempt + * to overwrite a corresponding file in the local file system provided + * it is in sync with the workbench. This option ensures there is no + * unintended data loss; it is the recommended setting. + * However, if true is specified, an attempt will be made + * to write a corresponding file in the local file system, + * overwriting any existing one if need be. + * In either case, if this method succeeds, the resource will be marked + * as being local (even if it wasn't before). + *

    + * As a result of this operation, the element is consistent with its underlying + * resource or buffer. + * + * @param progress the given progress monitor + * @param force it controls how this method deals with + * cases where the workbench is not completely in sync with the local file system + * @exception JavaModelException if an error occurs accessing the contents + * of its underlying resource. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • This Java element is read-only (READ_ONLY)
    • + *
    + */ +public void save(IProgressMonitor progress, boolean force) throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java new file mode 100644 index 0000000..cb37b5d --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Common protocol for Java elements that contain other Java elements. + *

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

    + */ +public interface IParent { +/** + * Returns the immediate children of this element. + * Unless otherwise specified by the implementing element, + * the children are in no particular order. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return the immediate children of this element + */ +IJavaElement[] getChildren() throws JavaModelException; +/** + * Returns whether this element has one or more immediate children. + * This is a convenience method, and may be more efficient than + * testing whether getChildren is an empty array. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + * @return true if the immediate children of this element, false otherwise + */ +boolean hasChildren() throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java new file mode 100644 index 0000000..5f3fff2 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IProblemRequestor.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import net.sourceforge.phpdt.core.compiler.IProblem; + +/** + * A callback interface for receiving java problem as they are discovered + * by some Java operation. + * + * @see IProblem + * @since 2.0 + */ +public interface IProblemRequestor { + + /** + * Notification of a Java problem. + * + * @param problem IProblem - The discovered Java problem. + */ + void acceptProblem(IProblem problem); + + /** + * Notification sent before starting the problem detection process. + * Typically, this would tell a problem collector to clear previously recorded problems. + */ + void beginReporting(); + + /** + * Notification sent after having completed problem detection process. + * Typically, this would tell a problem collector that no more problems should be expected in this + * iteration. + */ + void endReporting(); + + /** + * Predicate allowing the problem requestor to signal whether or not it is currently + * interested by problem reports. When answering false, problem will + * not be discovered any more until the next iteration. + * + * This predicate will be invoked once prior to each problem detection iteration. + * + * @return boolean - indicates whether the requestor is currently interested by problems. + */ + boolean isActive(); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java new file mode 100644 index 0000000..e829cfe --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Common protocol for Java elements that support source code manipulations such + * as copy, move, rename, and delete. + *

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

    + */ +public interface ISourceManipulation { +/** + * Copies this element to the given container. + * + * @param container the container + * @param sibling the sibling element before which the copy should be inserted, + * or null if the copy should be inserted as the last child of + * the container + * @param rename the new name for the element, or null if the copy + * retains the name of this element + * @param replace true if any existing child in the container with + * the target name should be replaced, and false to throw an + * exception in the event of a name collision + * @param monitor a progress monitor + * @exception JavaModelException if this element could not be copied. Reasons include: + *
      + *
    • This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The container is of an incompatible type (INVALID_DESTINATION) + *
    • The sibling is not a child of the given container (INVALID_SIBLING) + *
    • The new name is invalid (INVALID_NAME) + *
    • A child in the container already exists with the same name (NAME_COLLISION) + * and replace has been specified as false + *
    • The container or this element is read-only (READ_ONLY) + *
    + * + * @exception IllegalArgumentException if container is null + */ +void copy(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException; +/** + * Deletes this element, forcing if specified and necessary. + * + * @param force a flag controlling whether underlying resources that are not + * in sync with the local file system will be tolerated (same as the force flag + * in IResource operations). + * @param monitor a progress monitor + * @exception JavaModelException if this element could not be deleted. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource (CORE_EXCEPTION)
    • + *
    • This element is read-only (READ_ONLY)
    • + *
    + */ +void delete(boolean force, IProgressMonitor monitor) throws JavaModelException; +/** + * Moves this element to the given container. + * + * @param container the container + * @param sibling the sibling element before which the element should be inserted, + * or null if the element should be inserted as the last child of + * the container + * @param rename the new name for the element, or null if the + * element retains its name + * @param replace true if any existing child in the container with + * the target name should be replaced, and false to throw an + * exception in the event of a name collision + * @param monitor a progress monitor + * @exception JavaModelException if this element could not be moved. Reasons include: + *
      + *
    • This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The container is of an incompatible type (INVALID_DESTINATION) + *
    • The sibling is not a child of the given container (INVALID_SIBLING) + *
    • The new name is invalid (INVALID_NAME) + *
    • A child in the container already exists with the same name (NAME_COLLISION) + * and replace has been specified as false + *
    • The container or this element is read-only (READ_ONLY) + *
    + * + * @exception IllegalArgumentException if container is null + */ +void move(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException; +/** + * Renames this element to the given name. + * + * @param name the new name for the element + * @param replace true if any existing element with the target name + * should be replaced, and false to throw an exception in the + * event of a name collision + * @param monitor a progress monitor + * @exception JavaModelException if this element could not be renamed. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The new name is invalid (INVALID_NAME) + *
    • A child in the container already exists with the same name (NAME_COLLISION) + * and replace has been specified as false + *
    • This element is read-only (READ_ONLY) + *
    + */ +void rename(String name, boolean replace, IProgressMonitor monitor) throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java new file mode 100644 index 0000000..02d4da8 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceRange.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * A source range defines an element's source coordinates relative to + * its source buffer. + *

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

    + */ +public interface ISourceRange { + +/** + * Returns the number of characters of the source code for this element, + * relative to the source buffer in which this element is contained. + * + * @return the number of characters of the source code for this element, + * relative to the source buffer in which this element is contained + */ +int getLength(); +/** + * Returns the 0-based index of the first character of the source code for this element, + * relative to the source buffer in which this element is contained. + * + * @return the 0-based index of the first character of the source code for this element, + * relative to the source buffer in which this element is contained + */ +int getOffset(); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java new file mode 100644 index 0000000..09ef815 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceReference.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +/** + * Common protocol for Java elements that have associated source code. + * This set consists of IClassFile, ICompilationUnit, + * IPackageDeclaration, IImportDeclaration, + * IImportContainer, IType, IField, + * IMethod, and IInitializer. + * + *

    + * Note: For IClassFile, IType and other members + * derived from a binary type, the implementation returns source iff the + * element has attached source code. + *

    + *

    + * Source reference elements may be working copies if they were created from + * a compilation unit that is a working copy. + *

    + *

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

    + * + * @see IPackageFragmentRoot#attachSource + */ +public interface ISourceReference { +/** + * Returns whether this element exists in the model. + * + * @return true if this element exists in the Java model + * @since 2.0 + */ +boolean exists(); + +/** + * Returns the source code associated with this element. + * This extracts the substring from the source buffer containing this source + * element. This corresponds to the source range that would be returned by + * getSourceRange. + *

    + * For class files, this returns the source of the entire compilation unit + * associated with the class file (if there is one). + *

    + * + * @return the source code, or null if this element has no + * associated source code + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +String getSource() throws JavaModelException; +/** + * Returns the source range associated with this element. + *

    + * For class files, this returns the range of the entire compilation unit + * associated with the class file (if there is one). + *

    + * + * @return the source range, or null if this element has no + * associated source code + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource + */ +ISourceRange getSourceRange() throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java new file mode 100644 index 0000000..1a69299 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IType.java @@ -0,0 +1,569 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Represents either a source type in a compilation unit (either a top-level + * type or a member type) or a binary type in a class file. + *

    + * If a binary type cannot be parsed, its structure remains unknown. + * Use IJavaElement.isStructureKnown to determine whether this + * is the case. + *

    + *

    + * The children are of type IMember, which includes IField, + * IMethod, IInitializer and IType. + * The children are listed in the order in which they appear in the source or class file. + *

    + *

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

    + */ +public interface IType extends IMember, IParent { + /** + * Do code completion inside a code snippet in the context of the current type. + * + * If the type can access to his source code and the insertion position is valid, + * then completion is performed against source. Otherwise the completion is performed + * against type structure and given locals variables. + * + * @param snippet the code snippet + * @param insertion the position with in source where the snippet + * is inserted. This position must not be in comments. + * A possible value is -1, if the position is not known. + * @param position the position with in snippet where the user + * is performing code assist. + * @param localVariableTypesNames an array (possibly empty) of fully qualified + * type names of local variables visible at the current scope + * @param localVariableNames an array (possibly empty) of local variable names + * that are visible at the current scope + * @param localVariableModifiers an array (possible empty) of modifiers for + * local variables + * @param isStatic whether the current scope is in a static context + * @param requestor the completion requestor + * @since 2.0 + */ + void codeComplete( + char[] snippet, + int insertion, + int position, + char[][] localVariableTypeNames, + char[][] localVariableNames, + int[] localVariableModifiers, + boolean isStatic, + ICompletionRequestor requestor) + throws JavaModelException; + + /** + * Creates and returns a field in this type with the + * given contents. + *

    + * Optionally, the new element can be positioned before the specified + * sibling. If no sibling is specified, the element will be inserted + * as the last field declaration in this type.

    + * + *

    It is possible that a field with the same name already exists in this type. + * The value of the force parameter effects the resolution of + * such a conflict:

      + *
    • true - in this case the field is created with the new contents
    • + *
    • false - in this case a JavaModelException is thrown
    • + *

    + * + * @param contents the given contents + * @param sibling the given sibling + * @param force a flag in case the same name already exists in this type + * @param monitor the given progress monitor + * @exception JavaModelException if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The specified sibling is not a child of this type (INVALID_SIBLING) + *
    • The contents could not be recognized as a field declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    • There was a naming collision with an existing field (NAME_COLLISION) + *
    + * @return a field in this type with the given contents + */ + IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) + throws JavaModelException; + + /** + * Creates and returns a static initializer in this type with the + * given contents. + *

    + * Optionally, the new element can be positioned before the specified + * sibling. If no sibling is specified, the new initializer is positioned + * after the last existing initializer declaration, or as the first member + * in the type if there are no initializers.

    + * + * @param contents the given contents + * @param sibling the given sibling + * @param monitor the given progress monitor + * @exception JavaModelException if the element could not be created. Reasons include: + *
      + *
    • This element does not exist + *
    • A CoreException occurred while updating an underlying resource + *
    • The specified sibling is not a child of this type (INVALID_SIBLING) + *
    • The contents could not be recognized as an initializer declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    + * @return a static initializer in this type with the given contents + */ + IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) + throws JavaModelException; + + /** + * Creates and returns a method or constructor in this type with the + * given contents. + *

    + * Optionally, the new element can be positioned before the specified + * sibling. If no sibling is specified, the element will be appended + * to this type. + * + *

    It is possible that a method with the same signature already exists in this type. + * The value of the force parameter effects the resolution of + * such a conflict:

      + *
    • true - in this case the method is created with the new contents
    • + *
    • false - in this case a JavaModelException is thrown
    • + *

    + * + * @param contents the given contents + * @param sibling the given sibling + * @param force a flag in case the same name already exists in this type + * @param monitor the given progress monitor + * @exception JavaModelException if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The specified sibling is not a child of this type (INVALID_SIBLING) + *
    • The contents could not be recognized as a method or constructor + * declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    • There was a naming collision with an existing method (NAME_COLLISION) + *
    + * @return a method or constructor in this type with the given contents + */ + IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) + throws JavaModelException; + + /** + * Creates and returns a type in this type with the + * given contents. + *

    + * Optionally, the new type can be positioned before the specified + * sibling. If no sibling is specified, the type will be appended + * to this type. + * + *

    It is possible that a type with the same name already exists in this type. + * The value of the force parameter effects the resolution of + * such a conflict:

      + *
    • true - in this case the type is created with the new contents
    • + *
    • false - in this case a JavaModelException is thrown
    • + *

    + * + * @param contents the given contents + * @param sibling the given sibling + * @param force a flag in case the same name already exists in this type + * @param monitor the given progress monitor + * @exception JavaModelException if the element could not be created. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • The specified sibling is not a child of this type (INVALID_SIBLING) + *
    • The contents could not be recognized as a type declaration (INVALID_CONTENTS) + *
    • This type is read-only (binary) (READ_ONLY) + *
    • There was a naming collision with an existing field (NAME_COLLISION) + *
    + * @return a type in this type with the given contents + */ + IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) + throws JavaModelException; + + /** + * Finds the methods in this type that correspond to + * the given method. + * A method m1 corresponds to another method m2 if: + *
      + *
    • m1 has the same element name as m2. + *
    • m1 has the same number of arguments as m2 and + * the simple names of the argument types must be equals. + *
    • m1 exists. + *
    + * @param method the given method + * @return the found method or null if no such methods can be found. + * + * @since 2.0 + */ + IMethod[] findMethods(IMethod method); + + /** + * Returns the simple name of this type, unqualified by package or enclosing type. + * This is a handle-only method. + * + * @return the simple name of this type + */ + String getElementName(); + + /** + * Returns the field with the specified name + * in this type (for example, "bar"). + * This is a handle-only method. The field may or may not exist. + * + * @param name the given name + * @return the field with the specified name in this type + */ + IField getField(String name); + + /** + * Returns the fields declared by this type. + * If this is a source type, the results are listed in the order + * in which they appear in the source, otherwise, the results are + * in no particular order. For binary types, this includes synthetic fields. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the fields declared by this type + */ + IField[] getFields() throws JavaModelException; + + /** + * Returns the fully qualified name of this type, + * including qualification for any containing types and packages. + * This is the name of the package, followed by '.', + * followed by the type-qualified name. + * This is a handle-only method. + * + * @see IType#getTypeQualifiedName() + * @return the fully qualified name of this type + */ + String getFullyQualifiedName(); + + /** + * Returns the fully qualified name of this type, + * including qualification for any containing types and packages. + * This is the name of the package, followed by '.', + * followed by the type-qualified name using the enclosingTypeSeparator. + * + * For example: + *
      + *
    • the fully qualified name of a class B defined as a member of a class A in a compilation unit A.java + * in a package x.y using the '.' separator is "x.y.A.B"
    • + *
    • the fully qualified name of a class B defined as a member of a class A in a compilation unit A.java + * in a package x.y using the '$' separator is "x.y.A$B"
    • + *
    • the fully qualified name of a binary type whose class file is x/y/A$B.class + * using the '.' separator is "x.y.A.B"
    • + *
    • the fully qualified name of a binary type whose class file is x/y/A$B.class + * using the '$' separator is "x.y.A$B"
    • + *
    • the fully qualified name of an anonymous binary type whose class file is x/y/A$1.class + * using the '.' separator is "x.y.A$1"
    • + *
    + * + * This is a handle-only method. + * + * @param enclosingTypeSeparator the given enclosing type separator + * @return the fully qualified name of this type, including qualification for any containing types and packages + * @see IType#getTypeQualifiedName(char) + * @since 2.0 + */ + String getFullyQualifiedName(char enclosingTypeSeparator); + + /** + * Returns the initializer with the specified position relative to + * the order they are defined in the source. + * Numbering starts at 1 (i.e. the first occurrence is occurrence 1, not occurrence 0). + * This is a handle-only method. The initializer may or may not be present. + * + * @param occurrenceCount the specified position + * @return the initializer with the specified position relative to the order they are defined in the source + */ + IInitializer getInitializer(int occurrenceCount); + + /** + * Returns the initializers declared by this type. + * For binary types this is an empty collection. + * If this is a source type, the results are listed in the order + * in which they appear in the source. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the initializers declared by this type + */ + IInitializer[] getInitializers() throws JavaModelException; + + /** + * Returns the method with the specified name and parameter types + * in this type (for example, "foo", {"I", "QString;"}). To get the + * handle for a constructor, the name specified must be the simple + * name of the enclosing type. + * This is a handle-only method. The method may or may not be present. + * + * @param name the given name + * @param parameterTypeSignatures the given parameter types + * @return the method with the specified name and parameter types in this type + */ + IMethod getMethod(String name, String[] parameterTypeSignatures); + + /** + * Returns the methods and constructors declared by this type. + * For binary types, this may include the special <clinit>; method + * and synthetic methods. + * If this is a source type, the results are listed in the order + * in which they appear in the source, otherwise, the results are + * in no particular order. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the methods and constructors declared by this type + */ + IMethod[] getMethods() throws JavaModelException; + + /** + * Returns the package fragment in which this element is defined. + * This is a handle-only method. + * + * @return the package fragment in which this element is defined + */ + //IPackageFragment getPackageFragment(); + + /** + * Returns the name of this type's superclass, or null + * for source types that do not specify a superclass. + * For interfaces, the superclass name is always "java.lang.Object". + * For source types, the name as declared is returned, for binary types, + * the resolved, qualified name is returned. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the name of this type's superclass, or null for source types that do not specify a superclass + */ + String getSuperclassName() throws JavaModelException; + + /** + * Returns the names of interfaces that this type implements or extends, + * in the order in which they are listed in the source. + * For classes, this gives the interfaces that this class implements. + * For interfaces, this gives the interfaces that this interface extends. + * An empty collection is returned if this type does not implement or + * extend any interfaces. For source types, simples name are returned, + * for binary types, qualified names are returned. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the names of interfaces that this type implements or extends, in the order in which they are listed in the source, + * an empty collection if none + */ + String[] getSuperInterfaceNames() throws JavaModelException; + + /** + * Returns the member type declared in this type with the given simple name. + * This is a handle-only method. The type may or may not exist. + * + * @param the given simple name + * @return the member type declared in this type with the given simple name + */ + IType getType(String name); + + /** + * Returns the type-qualified name of this type, + * including qualification for any enclosing types, + * but not including package qualification. + * For source types, this consists of the simple names of + * any enclosing types, separated by "$", followed by the simple name of this type. + * For binary types, this is the name of the class file without the ".class" suffix. + * This is a handle-only method. + * + * @return the type-qualified name of this type + */ + String getTypeQualifiedName(); + + /** + * Returns the type-qualified name of this type, + * including qualification for any enclosing types, + * but not including package qualification. + * This consists of the simple names of any enclosing types, + * separated by the enclosingTypeSeparator, + * followed by the simple name of this type. + * + * For example: + *
      + *
    • the type qualified name of a class B defined as a member of a class A + * using the '.' separator is "A.B"
    • + *
    • the type qualified name of a class B defined as a member of a class A + * using the '$' separator is "A$B"
    • + *
    • the type qualified name of a binary type whose class file is A$B.class + * using the '.' separator is "A.B"
    • + *
    • the type qualified name of a binary type whose class file is A$B.class + * using the '$' separator is "A$B"
    • + *
    • the type qualified name of an anonymous binary type whose class file is A$1.class + * using the '.' separator is "A$1"
    • + *
    + * + * This is a handle-only method. + * + * @param enclosingTypeSeparator the specified enclosing type separator + * @return the type-qualified name of this type + * @since 2.0 + */ + String getTypeQualifiedName(char enclosingTypeSeparator); + + /** + * Returns the immediate member types declared by this type. + * The results are listed in the order in which they appear in the source or class file. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return the immediate member types declared by this type + */ + IType[] getTypes() throws JavaModelException; + + /** + * Returns whether this type represents an anonymous type. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if this type represents an anonymous type, false otherwise + * @since 2.0 + */ + boolean isAnonymous() throws JavaModelException; + + /** + * Returns whether this type represents a class. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if this type represents a class, false otherwise + */ + boolean isClass() throws JavaModelException; + + /** + * Returns whether this type represents an interface. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if this type represents an interface, false otherwise + */ + boolean isInterface() throws JavaModelException; + + /** + * Returns whether this type represents a local type. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if this type represents a local type, false otherwise + * @since 2.0 + */ + boolean isLocal() throws JavaModelException; + + /** + * Returns whether this type represents a member type. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return true if this type represents a member type, false otherwise + * @since 2.0 + */ + boolean isMember() throws JavaModelException; + + /** + * Creates and returns a type hierarchy for this type containing + * this type and all of its supertypes. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @param monitor the given progress monitor + * @return a type hierarchy for this type containing this type and all of its supertypes + */ + //ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException; + + /** + * Creates and returns a type hierarchy for this type containing + * this type and all of its supertypes, considering types in the given + * working copies. In other words, the list of working copies will take + * precedence over their original compilation units in the workspace. + *

    + * Note that passing an empty working copy will be as if the original compilation + * unit had been deleted. + * + * @param workingCopies the working copies that take precedence over their original compilation units + * @param monitor the given progress monitor + * @return a type hierarchy for this type containing this type and all of its supertypes + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @since 2.0 + */ +// ITypeHierarchy newSupertypeHierarchy(IWorkingCopy[] workingCopies, IProgressMonitor monitor) +// throws JavaModelException; +// + /** + * Creates and returns a type hierarchy for this type containing + * this type, all of its supertypes, and all its subtypes in the workspace. + * + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @param monitor the given progress monitor + * @return a type hierarchy for this type containing + * this type, all of its supertypes, and all its subtypes in the workspace + */ +// ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException; + + /** + * Creates and returns a type hierarchy for this type containing + * this type, all of its supertypes, and all its subtypes in the workspace, + * considering types in the given working copies. In other words, the list of working + * copies that will take precedence over their original compilation units in the workspace. + *

    + * Note that passing an empty working copy will be as if the original compilation + * unit had been deleted. + * + * @param workingCopies the working copies that take precedence over their original compilation units + * @param monitor the given progress monitor + * @return a type hierarchy for this type containing + * this type, all of its supertypes, and all its subtypes in the workspace + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @since 2.0 + */ + // ITypeHierarchy newTypeHierarchy(IWorkingCopy[] workingCopies, IProgressMonitor monitor) throws JavaModelException; + + /** + * Creates and returns a type hierarchy for this type containing + * this type, all of its supertypes, and all its subtypes + * in the context of the given project. + * + * @param project the given project + * @param monitor the given progress monitor + * @exception JavaModelException if this element does not exist or if an + * exception occurs while accessing its corresponding resource. + * @return a type hierarchy for this type containing + * this type, all of its supertypes, and all its subtypes + * in the context of the given project + */ +// ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException; + + /** + * Resolves the given type name within the context of this type (depending on the type hierarchy + * and its imports). Multiple answers might be found in case there are ambiguous matches. + * + * Each matching type name is decomposed as an array of two strings, the first denoting the package + * name (dot-separated) and the second being the type name. + * Returns null if unable to find any matching type. + * + * For example, resolution of "Object" would typically return + * {{"java.lang", "Object"}}. + * + * @param typeName the given type name + * @exception JavaModelException if code resolve could not be performed. + * @return the resolved type names or null if unable to find any matching type + */ + String[][] resolveType(String typeName) throws JavaModelException; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java new file mode 100644 index 0000000..da5c9d5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java @@ -0,0 +1,349 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API + * IBM Corporation, 2002/03/01- added notion of shared working copy + * IBM Corporation, 2002/26/01- added notion of IProblemRequestor + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IProgressMonitor; + +/** + * Common protocol for Java elements that support working copies. + *

    + * A working copy of a Java element acts just like a regular element (handle), + * except it is not attached to an underlying resource. A working copy is not + * visible to the rest of the Java model. Changes in a working copy's + * buffer are not realized in a resource. To bring the Java model up-to-date with a working + * copy's contents, an explicit commit must be performed on the working copy. + * Other operations performed on a working copy update the + * contents of the working copy's buffer but do not commit the contents + * of the working copy. + *

    + *

    + * Note: The contents of a working copy is determined when a working + * copy is created, based on the current content of the element the working + * copy is created from. If a working copy is an IOpenable and is explicitly + * closed, the working copy's buffer will be thrown away. However, clients should not + * explicitly open and close working copies. + *

    + *

    + * The client that creates a working copy is responsible for + * destroying the working copy. The Java model will never automatically + * destroy or close a working copy. (Note that destroying a working copy + * does not commit it to the model, it only frees up the memory occupied by + * the element). After a working copy is destroyed, the working copy cannot + * be accessed again. Non-handle methods will throw a + * JavaModelException indicating the Java element does not exist. + *

    + *

    + * A working copy cannot be created from another working copy. + * Calling getWorkingCopy on a working copy returns the receiver. + *

    + *

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

    + */ +public interface IWorkingCopy { + + /** + * Commits the contents of this working copy to its original element + * and underlying resource, bringing the Java model up-to-date with + * the current contents of the working copy. + * + *

    It is possible that the contents of the original resource have changed + * since this working copy was created, in which case there is an update conflict. + * The value of the force parameter effects the resolution of + * such a conflict:

      + *
    • true - in this case the contents of this working copy are applied to + * the underlying resource even though this working copy was created before + * a subsequent change in the resource
    • + *
    • false - in this case a JavaModelException is thrown
    • + *
    + * + * @param force a flag to handle the cases when the contents of the original resource have changed + * since this working copy was created + * @param monitor the given progress monitor + * @exception JavaModelException if this working copy could not commit. Reasons include: + *
      + *
    • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    • A CoreException occurred while updating an underlying resource + *
    • This element is not a working copy (INVALID_ELEMENT_TYPES) + *
    • A update conflict (described above) (UPDATE_CONFLICT) + *
    + */ + void commit(boolean force, IProgressMonitor monitor) throws JavaModelException; + + /** + * Destroys this working copy, closing its buffer and discarding + * its structure. Subsequent attempts to access non-handle information + * for this working copy will result in IJavaModelExceptions. Has + * no effect if this element is not a working copy. + *

    + * If this working copy is shared, it is destroyed only when the number of calls to + * destroy() is the same as the number of calls to + * getSharedWorkingCopy(IProgressMonitor, IBufferFactory). + * A REMOVED IJavaElementDelta is then reported on this working copy. + */ + void destroy(); + + /** + * Finds the shared working copy for this element, given a IBuffer factory. + * If no working copy has been created for this element associated with this + * buffer factory, returns null. + *

    + * Users of this method must not destroy the resulting working copy. + * + * @param bufferFactory the given IBuffer factory + * @return the found shared working copy for this element, null if none + * @see IBufferFactory + * @since 2.0 + */ + IJavaElement findSharedWorkingCopy(IBufferFactory bufferFactory); + + /** + * Returns the original element the specified working copy element was created from, + * or null if this is not a working copy element. This is a handle + * only method, the returned element may or may not exist. + * + * @return the original element the specified working copy element was created from, + * or null if this is not a working copy element + */ + IJavaElement getOriginal(IJavaElement workingCopyElement); + + /** + * Returns the original element this working copy was created from, + * or null if this is not a working copy. + * + * @return the original element this working copy was created from, + * or null if this is not a working copy + */ + IJavaElement getOriginalElement(); + + /** + * Finds the elements in this compilation unit that correspond to + * the given element. + * An element A corresponds to an element B if: + *

      + *
    • A has the same element name as B. + *
    • If A is a method, A must have the same number of arguments as + * B and the simple names of the argument types must be equals. + *
    • The parent of A corresponds to the parent of B recursively up to + * their respective compilation units. + *
    • A exists. + *
    + * Returns null if no such java elements can be found + * or if the given element is not included in a compilation unit. + * + * @param element the given element + * @return the found elements in this compilation unit that correspond to the given element + * @since 2.0 + */ + IJavaElement[] findElements(IJavaElement element); + + /** + * Finds the primary type of this compilation unit (i.e. the type with the same name as the + * compilation unit), or null if no such a type exists. + * + * @return the found primary type of this compilation unit, or null if no such a type exists + * @since 2.0 + */ + IType findPrimaryType(); + + /** + * Returns a shared working copy on this element using the given factory to create + * the buffer, or this element if this element is already a working copy. + * This API can only answer an already existing working copy if it is based on the same + * original compilation unit AND was using the same buffer factory (i.e. as defined by Object#equals). + *

    + * The life time of a shared working copy is as follows: + *

      + *
    • The first call to getSharedWorkingCopy(...) creates a new working copy for this + * element
    • + *
    • Subsequent calls increment an internal counter.
    • + *
    • A call to destroy() decrements the internal counter.
    • + *
    • When this counter is 0, the working copy is destroyed. + *
    + * So users of this method must destroy exactly once the working copy. + *

    + * Note that the buffer factory will be used for the life time of this working copy, i.e. if the + * working copy is closed then reopened, this factory will be used. + * The buffer will be automatically initialized with the original's compilation unit content + * upon creation. + *

    + * When the shared working copy instance is created, an ADDED IJavaElementDelta is reported on this + * working copy. + * + * @param monitor a progress monitor used to report progress while opening this compilation unit + * or null if no progress should be reported + * @param factory the factory that creates a buffer that is used to get the content of the working copy + * or null if the internal factory should be used + * @param problemRequestor a requestor which will get notified of problems detected during + * reconciling as they are discovered. The requestor can be set to null indicating + * that the client is not interested in problems. + * @exception JavaModelException if the contents of this element can + * not be determined. Reasons include: + *

      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @return a shared working copy on this element using the given factory to create + * the buffer, or this element if this element is already a working copy + * @see IBufferFactory + * @see IProblemRequestor + * @since 2.0 + */ + IJavaElement getSharedWorkingCopy( + IProgressMonitor monitor, + IBufferFactory factory, + IProblemRequestor problemRequestor) + throws JavaModelException; + + /** + * Returns a new working copy of this element if this element is not + * a working copy, or this element if this element is already a working copy. + * + * Note: if intending to share a working copy amongst several clients, then + * #getSharedWorkingCopy should be used instead. + * + * @exception JavaModelException if the contents of this element can + * not be determined. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @return a new working copy of this element if this element is not + * a working copy, or this element if this element is already a working copy + */ + IJavaElement getWorkingCopy() throws JavaModelException; + + /** + * Returns a new working copy of this element using the given factory to create + * the buffer, or this element if this element is already a working copy. + * Note that this factory will be used for the life time of this working copy, i.e. if the + * working copy is closed then reopened, this factory will be reused. + * The buffer will be automatically initialized with the original's compilation unit content + * upon creation. + * + * Note: if intending to share a working copy amongst several clients, then + * #getSharedWorkingCopy should be used instead. + * + * @param monitor a progress monitor used to report progress while opening this compilation unit + * or null if no progress should be reported + * @param factory the factory that creates a buffer that is used to get the content of the working copy + * or null if the internal factory should be used + * @param problemRequestor a requestor which will get notified of problems detected during + * reconciling as they are discovered. The requestor can be set to null indicating + * that the client is not interested in problems. + * @exception JavaModelException if the contents of this element can + * not be determined. Reasons include: + *
      + *
    • This Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @return a new working copy of this element using the given factory to create + * the buffer, or this element if this element is already a working copy + * @since 2.0 + */ + IJavaElement getWorkingCopy( + IProgressMonitor monitor, + IBufferFactory factory, + IProblemRequestor problemRequestor) + throws JavaModelException; + + /** + * Returns whether this working copy's original element's content + * has not changed since the inception of this working copy. + * + * @return true if this working copy's original element's content + * has not changed since the inception of this working copy, false otherwise + */ + boolean isBasedOn(IResource resource); + + /** + * Returns whether this element is a working copy. + * + * @return true if this element is a working copy, false otherwise + */ + boolean isWorkingCopy(); + + /** + * Reconciles the contents of this working copy. + * It performs the reconciliation by locally caching the contents of + * the working copy, updating the contents, then creating a delta + * over the cached contents and the new contents, and finally firing + * this delta. + *

    + * If the working copy hasn't changed, then no problem will be detected, + * this is equivalent to IWorkingCopy#reconcile(false, null). + *

    + * Compilation problems found in the new contents are notified through the + * IProblemRequestor interface which was passed at + * creation, and no longer as transient markers. Therefore this API will + * return null. + *

    + * Note: It has been assumed that added inner types should + * not generate change deltas. The implementation has been + * modified to reflect this assumption. + * + * @exception JavaModelException if the contents of the original element + * cannot be accessed. Reasons include: + *

      + *
    • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @return null + */ + IMarker[] reconcile() throws JavaModelException; + + /** + * Reconciles the contents of this working copy. + * It performs the reconciliation by locally caching the contents of + * the working copy, updating the contents, then creating a delta + * over the cached contents and the new contents, and finally firing + * this delta. + *

    + * The boolean argument allows to force problem detection even if the + * working copy is already consistent. + *

    + * Compilation problems found in the new contents are notified through the + * IProblemRequestor interface which was passed at + * creation, and no longer as transient markers. Therefore this API answers + * nothing. + *

    + * Note: It has been assumed that added inner types should + * not generate change deltas. The implementation has been + * modified to reflect this assumption. + * + * @param forceProblemDetection boolean indicating whether problem should be recomputed + * even if the source hasn't changed. + * @param monitor a progress monitor + * @exception JavaModelException if the contents of the original element + * cannot be accessed. Reasons include: + *

      + *
    • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + * @since 2.0 + */ + void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException; + + /** + * Restores the contents of this working copy to the current contents of + * this working copy's original element. Has no effect if this element + * is not a working copy. + * + *

    Note: This is the inverse of committing the content of the + * working copy to the original element with commit(boolean, IProgressMonitor). + * + * @exception JavaModelException if the contents of the original element + * cannot be accessed. Reasons include: + *

      + *
    • The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)
    • + *
    + */ + void restore() throws JavaModelException; +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java new file mode 100644 index 0000000..7417c88 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; + +import net.sourceforge.phpdt.internal.core.JavaModelStatus; + +/** + * A checked exception representing a failure in the Java model. + * Java model exceptions contain a Java-specific status object describing the + * cause of the exception. + *

    + * This class is not intended to be subclassed by clients. Instances of this + * class are automatically created by the Java model when problems arise, so + * there is generally no need for clients to create instances. + *

    + * + * @see IJavaModelStatus + * @see IJavaModelStatusConstants + */ +public class JavaModelException extends CoreException { + CoreException nestedCoreException; +/** + * Creates a Java model exception that wrappers the given Throwable. + * The exception contains a Java-specific status object with severity + * IStatus.ERROR and the given status code. + * + * @param exception the Throwable + * @param code one of the Java-specific status codes declared in + * IJavaModelStatusConstants + * @see IJavaModelStatusConstants + * @see org.eclipse.core.runtime.IStatus#ERROR + */ +public JavaModelException(Throwable e, int code) { + this(new JavaModelStatus(code, e)); +} +/** + * Creates a Java model exception for the given CoreException. + * Equivalent to + * JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION. + * + * @param exception the CoreException + */ +public JavaModelException(CoreException exception) { + super(exception.getStatus()); + this.nestedCoreException = exception; +} +/** + * Creates a Java model exception for the given Java-specific status object. + * + * @param status the Java-specific status object + */ +public JavaModelException(IJavaModelStatus status) { + super(status); +} +/** + * Returns the underlying Throwable that caused the failure. + * + * @return the wrappered Throwable, or null if the + * direct case of the failure was at the Java model layer + */ +public Throwable getException() { + if (this.nestedCoreException == null) { + return getStatus().getException(); + } else { + return this.nestedCoreException; + } +} +/** + * Returns the Java model status object for this exception. + * Equivalent to (IJavaModelStatus) getStatus(). + * + * @return a status object + */ +public IJavaModelStatus getJavaModelStatus() { + IStatus status = this.getStatus(); + if (status instanceof IJavaModelStatus) { + return (IJavaModelStatus)status; + } else { + // A regular IStatus is created only in the case of a CoreException. + // See bug 13492 Should handle JavaModelExceptions that contains CoreException more gracefully + return new JavaModelStatus(this.nestedCoreException); + } +} +/** + * Returns whether this exception indicates that a Java model element does not + * exist. Such exceptions have a status with a code of + * IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST. + * This is a convenience method. + * + * @return true if this exception indicates that a Java model + * element does not exist + * @see IJavaModelStatus#isDoesNotExist + * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST + */ +public boolean isDoesNotExist() { + IJavaModelStatus javaModelStatus = getJavaModelStatus(); + return javaModelStatus != null && javaModelStatus.isDoesNotExist(); +} +/** + * Returns a printable representation of this exception suitable for debugging + * purposes only. + */ +public String toString() { + StringBuffer buffer= new StringBuffer(); + buffer.append("Java Model Exception: "); //$NON-NLS-1$ + if (getException() != null) { + if (getException() instanceof CoreException) { + CoreException c= (CoreException)getException(); + buffer.append("Core Exception [code "); //$NON-NLS-1$ + buffer.append(c.getStatus().getCode()); + buffer.append("] "); //$NON-NLS-1$ + buffer.append(c.getStatus().getMessage()); + } else { + buffer.append(getException().toString()); + } + } else { + buffer.append(getStatus().toString()); + } + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java new file mode 100644 index 0000000..18d3336 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java @@ -0,0 +1,1384 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.core; + +import net.sourceforge.phpdt.core.compiler.ITerminalSymbols; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + +/** + * Provides methods for encoding and decoding type and method signature strings. + *

    + * The syntax for a type signature is: + *

    + * typeSignature ::=
    + *     "B"  // byte
    + *   | "C"  // char
    + *   | "D"  // double
    + *   | "F"  // float
    + *   | "I"  // int
    + *   | "J"  // long
    + *   | "S"  // short
    + *   | "V"  // void
    + *   | "Z"  // boolean
    + *   | "L" + binaryTypeName + ";"  // resolved named type (i.e., in compiled code)
    + *   | "Q" + sourceTypeName + ";"  // unresolved named type (i.e., in source code)
    + *   | "[" + typeSignature  // array of type denoted by typeSignature
    + * 
    + *

    + *

    + * Examples: + *

      + *
    • "[[I" denotes int[][]
    • + *
    • "Ljava.lang.String;" denotes java.lang.String in compiled code
    • + *
    • "QString" denotes String in source code
    • + *
    • "Qjava.lang.String" denotes java.lang.String in source code
    • + *
    • "[QString" denotes String[] in source code
    • + *
    + *

    + *

    + * The syntax for a method signature is: + *

    + * methodSignature ::= "(" + paramTypeSignature* + ")" + returnTypeSignature
    + * paramTypeSignature ::= typeSignature
    + * returnTypeSignature ::= typeSignature
    + * 
    + *

    + * Examples: + *

      + *
    • "()I" denotes int foo()
    • + *
    • "([Ljava.lang.String;)V" denotes void foo(java.lang.String[]) in compiled code
    • + *
    • "(QString;)QObject;" denotes Object foo(String) in source code
    • + *
    + *

    + *

    + * This class provides static methods and constants only; it is not intended to be + * instantiated or subclassed by clients. + *

    + */ +public final class Signature { + + /** + * Character constant indicating the primitive type boolean in a signature. + * Value is 'Z'. + */ + public static final char C_BOOLEAN = 'Z'; + + /** + * Character constant indicating the primitive type byte in a signature. + * Value is 'B'. + */ + public static final char C_BYTE = 'B'; + + /** + * Character constant indicating the primitive type char in a signature. + * Value is 'C'. + */ + public static final char C_CHAR = 'C'; + + /** + * Character constant indicating the primitive type double in a signature. + * Value is 'D'. + */ + public static final char C_DOUBLE = 'D'; + + /** + * Character constant indicating the primitive type float in a signature. + * Value is 'F'. + */ + public static final char C_FLOAT = 'F'; + + /** + * Character constant indicating the primitive type int in a signature. + * Value is 'I'. + */ + public static final char C_INT = 'I'; + + /** + * Character constant indicating the semicolon in a signature. + * Value is ';'. + */ + public static final char C_SEMICOLON = ';'; + + /** + * Character constant indicating the primitive type long in a signature. + * Value is 'J'. + */ + public static final char C_LONG = 'J'; + + /** + * Character constant indicating the primitive type short in a signature. + * Value is 'S'. + */ + public static final char C_SHORT = 'S'; + + /** + * Character constant indicating result type void in a signature. + * Value is 'V'. + */ + public static final char C_VOID = 'V'; + + /** + * Character constant indicating the dot in a signature. + * Value is '.'. + */ + public static final char C_DOT = '.'; + + /** + * Character constant indicating the dollar in a signature. + * Value is '$'. + */ + public static final char C_DOLLAR = '$'; + + /** + * Character constant indicating an array type in a signature. + * Value is '['. + */ + public static final char C_ARRAY = '['; + + /** + * Character constant indicating the start of a resolved, named type in a + * signature. Value is 'L'. + */ + public static final char C_RESOLVED = 'L'; + + /** + * Character constant indicating the start of an unresolved, named type in a + * signature. Value is 'Q'. + */ + public static final char C_UNRESOLVED = 'Q'; + + /** + * Character constant indicating the end of a named type in a signature. + * Value is ';'. + */ + public static final char C_NAME_END = ';'; + + /** + * Character constant indicating the start of a parameter type list in a + * signature. Value is '('. + */ + public static final char C_PARAM_START = '('; + + /** + * Character constant indicating the end of a parameter type list in a + * signature. Value is ')'. + */ + public static final char C_PARAM_END = ')'; + + /** + * String constant for the signature of the primitive type boolean. + * Value is "Z". + */ + public static final String SIG_BOOLEAN = "Z"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type byte. + * Value is "B". + */ + public static final String SIG_BYTE = "B"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type char. + * Value is "C". + */ + public static final String SIG_CHAR = "C"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type double. + * Value is "D". + */ + public static final String SIG_DOUBLE = "D"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type float. + * Value is "F". + */ + public static final String SIG_FLOAT = "F"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type int. + * Value is "I". + */ + public static final String SIG_INT = "I"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type long. + * Value is "J". + */ + public static final String SIG_LONG = "J"; //$NON-NLS-1$ + + /** + * String constant for the signature of the primitive type short. + * Value is "S". + */ + public static final String SIG_SHORT = "S"; //$NON-NLS-1$ + + /** String constant for the signature of result type void. + * Value is "V". + */ + public static final String SIG_VOID = "V"; //$NON-NLS-1$ + + private static final char[] NO_CHAR = new char[0]; + private static final char[][] NO_CHAR_CHAR = new char[0][]; + private static final char[] BOOLEAN = {'b', 'o', 'o', 'l', 'e', 'a', 'n'}; + private static final char[] BYTE = {'b', 'y', 't', 'e'}; + private static final char[] CHAR = {'c', 'h', 'a', 'r'}; + private static final char[] DOUBLE = {'d', 'o', 'u', 'b', 'l', 'e'}; + private static final char[] FLOAT = {'f', 'l', 'o', 'a', 't'}; + private static final char[] INT = {'i', 'n', 't'}; + private static final char[] LONG = {'l', 'o', 'n', 'g'}; + private static final char[] SHORT = {'s', 'h', 'o', 'r', 't'}; + private static final char[] VOID = {'v', 'o', 'i', 'd'}; + + +/** + * Not instantiable. + */ +private Signature() {} + +private static long copyType(char[] signature, int sigPos, char[] dest, int index, boolean fullyQualifyTypeNames) { + int arrayCount = 0; + loop: while (true) { + switch (signature[sigPos++]) { + case C_ARRAY : + arrayCount++; + break; + case C_BOOLEAN : + int length = BOOLEAN.length; + System.arraycopy(BOOLEAN, 0, dest, index, length); + index += length; + break loop; + case C_BYTE : + length = BYTE.length; + System.arraycopy(BYTE, 0, dest, index, length); + index += length; + break loop; + case C_CHAR : + length = CHAR.length; + System.arraycopy(CHAR, 0, dest, index, length); + index += length; + break loop; + case C_DOUBLE : + length = DOUBLE.length; + System.arraycopy(DOUBLE, 0, dest, index, length); + index += length; + break loop; + case C_FLOAT : + length = FLOAT.length; + System.arraycopy(FLOAT, 0, dest, index, length); + index += length; + break loop; + case C_INT : + length = INT.length; + System.arraycopy(INT, 0, dest, index, length); + index += length; + break loop; + case C_LONG : + length = LONG.length; + System.arraycopy(LONG, 0, dest, index, length); + index += length; + break loop; + case C_SHORT : + length = SHORT.length; + System.arraycopy(SHORT, 0, dest, index, length); + index += length; + break loop; + case C_VOID : + length = VOID.length; + System.arraycopy(VOID, 0, dest, index, length); + index += length; + break loop; + case C_RESOLVED : + case C_UNRESOLVED : + int end = CharOperation.indexOf(C_SEMICOLON, signature, sigPos); + if (end == -1) throw new IllegalArgumentException(); + int start; + if (fullyQualifyTypeNames) { + start = sigPos; + } else { + start = CharOperation.lastIndexOf(C_DOT, signature, sigPos, end)+1; + if (start == 0) start = sigPos; + } + length = end-start; + System.arraycopy(signature, start, dest, index, length); + sigPos = end+1; + index += length; + break loop; + } + } + while (arrayCount-- > 0) { + dest[index++] = '['; + dest[index++] = ']'; + } + return (((long) index) << 32) + sigPos; +} +/** + * Creates a new type signature with the given amount of array nesting added + * to the given type signature. + * + * @param typeSignature the type signature + * @param arrayCount the desired number of levels of array nesting + * @return the encoded array type signature + * + * @since 2.0 + */ +public static char[] createArraySignature(char[] typeSignature, int arrayCount) { + if (arrayCount == 0) return typeSignature; + int sigLength = typeSignature.length; + char[] result = new char[arrayCount + sigLength]; + for (int i = 0; i < arrayCount; i++) { + result[i] = C_ARRAY; + } + System.arraycopy(typeSignature, 0, result, arrayCount, sigLength); + return result; +} +/** + * Creates a new type signature with the given amount of array nesting added + * to the given type signature. + * + * @param typeSignature the type signature + * @param arrayCount the desired number of levels of array nesting + * @return the encoded array type signature + */ +public static String createArraySignature(String typeSignature, int arrayCount) { + return new String(createArraySignature(typeSignature.toCharArray(), arrayCount)); +} +/** + * Creates a method signature from the given parameter and return type + * signatures. The encoded method signature is dot-based. + * + * @param parameterTypes the list of parameter type signatures + * @param returnType the return type signature + * @return the encoded method signature + * + * @since 2.0 + */ +public static char[] createMethodSignature(char[][] parameterTypes, char[] returnType) { + int parameterTypesLength = parameterTypes.length; + int parameterLength = 0; + for (int i = 0; i < parameterTypesLength; i++) { + parameterLength += parameterTypes[i].length; + + } + int returnTypeLength = returnType.length; + char[] result = new char[1 + parameterLength + 1 + returnTypeLength]; + result[0] = C_PARAM_START; + int index = 1; + for (int i = 0; i < parameterTypesLength; i++) { + char[] parameterType = parameterTypes[i]; + int length = parameterType.length; + System.arraycopy(parameterType, 0, result, index, length); + index += length; + } + result[index] = C_PARAM_END; + System.arraycopy(returnType, 0, result, index+1, returnTypeLength); + return result; +} +/** + * Creates a method signature from the given parameter and return type + * signatures. The encoded method signature is dot-based. + * + * @param parameterTypes the list of parameter type signatures + * @param returnType the return type signature + * @return the encoded method signature + */ +public static String createMethodSignature(String[] parameterTypes, String returnType) { + int parameterTypesLenth = parameterTypes.length; + char[][] parameters = new char[parameterTypesLenth][]; + for (int i = 0; i < parameterTypesLenth; i++) { + parameters[i] = parameterTypes[i].toCharArray(); + } + return new String(createMethodSignature(parameters, returnType.toCharArray())); +} +/** + * Creates a new type signature from the given type name encoded as a character + * array. This method is equivalent to + * createTypeSignature(new String(typeName),isResolved), although + * more efficient for callers with character arrays rather than strings. If the + * type name is qualified, then it is expected to be dot-based. + * + * @param typeName the possibly qualified type name + * @param isResolved true if the type name is to be considered + * resolved (for example, a type name from a binary class file), and + * false if the type name is to be considered unresolved + * (for example, a type name found in source code) + * @return the encoded type signature + * @see #createTypeSignature(java.lang.String,boolean) + */ +public static String createTypeSignature(char[] typeName, boolean isResolved) { + return new String(createCharArrayTypeSignature(typeName, isResolved)); +} +/** + * Creates a new type signature from the given type name encoded as a character + * array. This method is equivalent to + * createTypeSignature(new String(typeName),isResolved).toCharArray(), although + * more efficient for callers with character arrays rather than strings. If the + * type name is qualified, then it is expected to be dot-based. + * + * @param typeName the possibly qualified type name + * @param isResolved true if the type name is to be considered + * resolved (for example, a type name from a binary class file), and + * false if the type name is to be considered unresolved + * (for example, a type name found in source code) + * @return the encoded type signature + * @see #createTypeSignature(java.lang.String,boolean) + * + * @since 2.0 + */ +public static char[] createCharArrayTypeSignature(char[] typeName, boolean isResolved) { + try { + Scanner scanner = new Scanner(); + scanner.setSource(typeName); + int token = scanner.getNextToken(); + boolean primitive = true; + char primitiveSig = ' '; + StringBuffer sig = null; + int arrayCount = 0; + switch (token) { + case ITerminalSymbols.TokenNameIdentifier : + char[] idSource = scanner.getCurrentIdentifierSource(); + sig = new StringBuffer(idSource.length); + sig.append(idSource); + primitive = false; + break; +// case ITerminalSymbols.TokenNameboolean : +// primitiveSig = Signature.C_BOOLEAN; +// break; +// case ITerminalSymbols.TokenNamebyte : +// primitiveSig = Signature.C_BYTE; +// break; +// case ITerminalSymbols.TokenNamechar : +// primitiveSig = Signature.C_CHAR; +// break; +// case ITerminalSymbols.TokenNamedouble : +// primitiveSig = Signature.C_DOUBLE; +// break; +// case ITerminalSymbols.TokenNamefloat : +// primitiveSig = Signature.C_FLOAT; +// break; +// case ITerminalSymbols.TokenNameint : +// primitiveSig = Signature.C_INT; +// break; +// case ITerminalSymbols.TokenNamelong : +// primitiveSig = Signature.C_LONG; +// break; +// case ITerminalSymbols.TokenNameshort : +// primitiveSig = Signature.C_SHORT; +// break; +// case ITerminalSymbols.TokenNamevoid : +// primitiveSig = Signature.C_VOID; +// break; + default : + throw new IllegalArgumentException(); + } + token = scanner.getNextToken(); + while (!primitive && token == ITerminalSymbols.TokenNameDOT) { + sig.append(scanner.getCurrentIdentifierSource()); + token = scanner.getNextToken(); + if (token == ITerminalSymbols.TokenNameIdentifier) { + sig.append(scanner.getCurrentIdentifierSource()); + token = scanner.getNextToken(); + } else { + throw new IllegalArgumentException(); + } + } + while (token == ITerminalSymbols.TokenNameLBRACKET) { + token = scanner.getNextToken(); + if (token != ITerminalSymbols.TokenNameRBRACKET) + throw new IllegalArgumentException(); + arrayCount++; + token = scanner.getNextToken(); + } + if (token != ITerminalSymbols.TokenNameEOF) + throw new IllegalArgumentException(); + char[] result; + if (primitive) { + result = new char[arrayCount+1]; + result[arrayCount] = primitiveSig; + } else { + int sigLength = sig.length(); + int resultLength = arrayCount + 1 + sigLength + 1; // e.g. '[[[Ljava.lang.String;' + result = new char[resultLength]; + sig.getChars(0, sigLength, result, arrayCount + 1); + result[arrayCount] = isResolved ? C_RESOLVED : C_UNRESOLVED; + result[resultLength-1] = C_NAME_END; + } + for (int i = 0; i < arrayCount; i++) { + result[i] = C_ARRAY; + } + return result; + } catch (InvalidInputException e) { + throw new IllegalArgumentException(); + } +} +/** + * Creates a new type signature from the given type name. If the type name is qualified, + * then it is expected to be dot-based. + *

    + * For example: + *

    + * 
    + * createTypeSignature("int", hucairz) -> "I"
    + * createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
    + * createTypeSignature("String", false) -> "QString;"
    + * createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
    + * createTypeSignature("int []", false) -> "[I"
    + * 
    + * 
    + *

    + * + * @param typeName the possibly qualified type name + * @param isResolved true if the type name is to be considered + * resolved (for example, a type name from a binary class file), and + * false if the type name is to be considered unresolved + * (for example, a type name found in source code) + * @return the encoded type signature + */ +public static String createTypeSignature(String typeName, boolean isResolved) { + return createTypeSignature(typeName.toCharArray(), isResolved); +} +/** + * Returns the array count (array nesting depth) of the given type signature. + * + * @param typeSignature the type signature + * @return the array nesting depth, or 0 if not an array + * @exception IllegalArgumentException if the signature is not syntactically + * correct + * + * @since 2.0 + */ +public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException { + try { + int count = 0; + while (typeSignature[count] == C_ARRAY) { + ++count; + } + return count; + } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY + throw new IllegalArgumentException(); + } +} +/** + * Returns the array count (array nesting depth) of the given type signature. + * + * @param typeSignature the type signature + * @return the array nesting depth, or 0 if not an array + * @exception IllegalArgumentException if the signature is not syntactically + * correct + */ +public static int getArrayCount(String typeSignature) throws IllegalArgumentException { + return getArrayCount(typeSignature.toCharArray()); +} +/** + * Returns the type signature without any array nesting. + *

    + * For example: + *

    + * 
    + * getElementType({'[', '[', 'I'}) --> {'I'}.
    + * 
    + * 
    + *

    + * + * @param typeSignature the type signature + * @return the type signature without arrays + * @exception IllegalArgumentException if the signature is not syntactically + * correct + * + * @since 2.0 + */ +public static char[] getElementType(char[] typeSignature) throws IllegalArgumentException { + int count = getArrayCount(typeSignature); + if (count == 0) return typeSignature; + int length = typeSignature.length; + char[] result = new char[length-count]; + System.arraycopy(typeSignature, count, result, 0, length-count); + return result; +} +/** + * Returns the type signature without any array nesting. + *

    + * For example: + *

    + * 
    + * getElementType("[[I") --> "I".
    + * 
    + * 
    + *

    + * + * @param typeSignature the type signature + * @return the type signature without arrays + * @exception IllegalArgumentException if the signature is not syntactically + * correct + */ +public static String getElementType(String typeSignature) throws IllegalArgumentException { + return new String(getElementType(typeSignature.toCharArray())); +} +/** + * Returns the number of parameter types in the given method signature. + * + * @param methodSignature the method signature + * @return the number of parameters + * @exception IllegalArgumentException if the signature is not syntactically + * correct + * @since 2.0 + */ +public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException { + try { + int count = 0; + int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1; + if (i == 0) + throw new IllegalArgumentException(); + for (;;) { + char c = methodSignature[i++]; + switch (c) { + case C_ARRAY : + break; + case C_BOOLEAN : + case C_BYTE : + case C_CHAR : + case C_DOUBLE : + case C_FLOAT : + case C_INT : + case C_LONG : + case C_SHORT : + case C_VOID : + ++count; + break; + case C_RESOLVED : + case C_UNRESOLVED : + i = CharOperation.indexOf(C_SEMICOLON, methodSignature, i) + 1; + if (i == 0) + throw new IllegalArgumentException(); + ++count; + break; + case C_PARAM_END : + return count; + default : + throw new IllegalArgumentException(); + } + } + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); + } +} +/** + * Returns the number of parameter types in the given method signature. + * + * @param methodSignature the method signature + * @return the number of parameters + * @exception IllegalArgumentException if the signature is not syntactically + * correct + */ +public static int getParameterCount(String methodSignature) throws IllegalArgumentException { + return getParameterCount(methodSignature.toCharArray()); +} +/** + * Extracts the parameter type signatures from the given method signature. + * The method signature is expected to be dot-based. + * + * @param methodSignature the method signature + * @return the list of parameter type signatures + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + * + * @since 2.0 + */ +public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException { + try { + int count = getParameterCount(methodSignature); + char[][] result = new char[count][]; + if (count == 0) + return result; + int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1; + count = 0; + int start = i; + for (;;) { + char c = methodSignature[i++]; + switch (c) { + case C_ARRAY : + // array depth is i - start; + break; + case C_BOOLEAN : + case C_BYTE : + case C_CHAR : + case C_DOUBLE : + case C_FLOAT : + case C_INT : + case C_LONG : + case C_SHORT : + case C_VOID : + // common case of base types + if (i - start == 1) { + switch (c) { + case C_BOOLEAN : + result[count++] = new char[] {C_BOOLEAN}; + break; + case C_BYTE : + result[count++] = new char[] {C_BYTE}; + break; + case C_CHAR : + result[count++] = new char[] {C_CHAR}; + break; + case C_DOUBLE : + result[count++] = new char[] {C_DOUBLE}; + break; + case C_FLOAT : + result[count++] = new char[] {C_FLOAT}; + break; + case C_INT : + result[count++] = new char[] {C_INT}; + break; + case C_LONG : + result[count++] = new char[] {C_LONG}; + break; + case C_SHORT : + result[count++] = new char[] {C_SHORT}; + break; + case C_VOID : + result[count++] = new char[] {C_VOID}; + break; + } + } else { + result[count++] = CharOperation.subarray(methodSignature, start, i); + } + start = i; + break; + case C_RESOLVED : + case C_UNRESOLVED : + i = CharOperation.indexOf(C_SEMICOLON, methodSignature, i) + 1; + if (i == 0) + throw new IllegalArgumentException(); + result[count++] = CharOperation.subarray(methodSignature, start, i); + start = i; + break; + case C_PARAM_END: + return result; + default : + throw new IllegalArgumentException(); + } + } + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); + } +} +/** + * Extracts the parameter type signatures from the given method signature. + * The method signature is expected to be dot-based. + * + * @param methodSignature the method signature + * @return the list of parameter type signatures + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + */ +public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException { + char[][] parameterTypes = getParameterTypes(methodSignature.toCharArray()); + int length = parameterTypes.length; + String[] result = new String[length]; + for (int i = 0; i < length; i++) { + result[i] = new String(parameterTypes[i]); + } + return result; +} +/** + * Returns a char array containing all but the last segment of the given + * dot-separated qualified name. Returns the empty char array if it is not qualified. + *

    + * For example: + *

    + * 
    + * getQualifier({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g'}
    + * getQualifier({'O', 'u', 't', 'e', 'r', '.', 'I', 'n', 'n', 'e', 'r'}) -> {'O', 'u', 't', 'e', 'r'}
    + * 
    + * 
    + *

    + * + * @param name the name + * @return the qualifier prefix, or the empty char array if the name contains no + * dots + * + * @since 2.0 + */ +public static char[] getQualifier(char[] name) { + int lastDot = CharOperation.lastIndexOf(C_DOT, name); + if (lastDot == -1) { + return NO_CHAR; //$NON-NLS-1$ + } + return CharOperation.subarray(name, 0, lastDot); +} +/** + * Returns a string containing all but the last segment of the given + * dot-separated qualified name. Returns the empty string if it is not qualified. + *

    + * For example: + *

    + * 
    + * getQualifier("java.lang.Object") -> "java.lang"
    + * getQualifier("Outer.Inner") -> "Outer"
    + * 
    + * 
    + *

    + * + * @param name the name + * @return the qualifier prefix, or the empty string if the name contains no + * dots + */ +public static String getQualifier(String name) { + return new String(getQualifier(name.toCharArray())); +} +/** + * Extracts the return type from the given method signature. The method signature is + * expected to be dot-based. + * + * @param methodSignature the method signature + * @return the type signature of the return type + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + * + * @since 2.0 + */ +public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException { + int i = CharOperation.lastIndexOf(C_PARAM_END, methodSignature); + if (i == -1) { + throw new IllegalArgumentException(); + } + return CharOperation.subarray(methodSignature, i + 1, methodSignature.length); +} +/** + * Extracts the return type from the given method signature. The method signature is + * expected to be dot-based. + * + * @param methodSignature the method signature + * @return the type signature of the return type + * @exception IllegalArgumentException if the signature is syntactically + * incorrect + */ +public static String getReturnType(String methodSignature) throws IllegalArgumentException { + return new String(getReturnType(methodSignature.toCharArray())); +} +/** + * Returns the last segment of the given dot-separated qualified name. + * Returns the given name if it is not qualified. + *

    + * For example: + *

    + * 
    + * getSimpleName({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'O', 'b', 'j', 'e', 'c', 't'}
    + * 
    + * 
    + *

    + * + * @param name the name + * @return the last segment of the qualified name + * + * @since 2.0 + */ +public static char[] getSimpleName(char[] name) { + int lastDot = CharOperation.lastIndexOf(C_DOT, name); + if (lastDot == -1) { + return name; + } + return CharOperation.subarray(name, lastDot + 1, name.length); +} +/** + * Returns the last segment of the given dot-separated qualified name. + * Returns the given name if it is not qualified. + *

    + * For example: + *

    + * 
    + * getSimpleName("java.lang.Object") -> "Object"
    + * 
    + * 
    + *

    + * + * @param name the name + * @return the last segment of the qualified name + */ +public static String getSimpleName(String name) { + return new String(getSimpleName(name.toCharArray())); +} +/** + * Returns all segments of the given dot-separated qualified name. + * Returns an array with only the given name if it is not qualified. + * Returns an empty array if the name is empty. + *

    + * For example: + *

    + * 
    + * getSimpleNames({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}
    + * getSimpleNames({'O', 'b', 'j', 'e', 'c', 't'}) -> {{'O', 'b', 'j', 'e', 'c', 't'}}
    + * getSimpleNames("") -> {}
    + * 
    + * 
    + * + * @param name the name + * @return the list of simple names, possibly empty + * + * @since 2.0 + */ +public static char[][] getSimpleNames(char[] name) { + if (name.length == 0) { + return NO_CHAR_CHAR; + } + int dot = CharOperation.indexOf(C_DOT, name); + if (dot == -1) { + return new char[][] {name}; + } + int n = 1; + while ((dot = CharOperation.indexOf(C_DOT, name, dot + 1)) != -1) { + ++n; + } + char[][] result = new char[n + 1][]; + int segStart = 0; + for (int i = 0; i < n; ++i) { + dot = CharOperation.indexOf(C_DOT, name, segStart); + result[i] = CharOperation.subarray(name, segStart, dot); + segStart = dot + 1; + } + result[n] = CharOperation.subarray(name, segStart, name.length); + return result; +} +/** + * Returns all segments of the given dot-separated qualified name. + * Returns an array with only the given name if it is not qualified. + * Returns an empty array if the name is empty. + *

    + * For example: + *

    + * 
    + * getSimpleNames("java.lang.Object") -> {"java", "lang", "Object"}
    + * getSimpleNames("Object") -> {"Object"}
    + * getSimpleNames("") -> {}
    + * 
    + * 
    + * + * @param name the name + * @return the list of simple names, possibly empty + */ +public static String[] getSimpleNames(String name) { + char[][] simpleNames = getSimpleNames(name.toCharArray()); + int length = simpleNames.length; + String[] result = new String[length]; + for (int i = 0; i < length; i++) { + result[i] = new String(simpleNames[i]); + } + return result; +} +/** + * Converts the given method signature to a readable form. The method signature is expected to + * be dot-based. + *

    + * For example: + *

    + * 
    + * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
    + * 
    + * 
    + *

    + * + * @param methodSignature the method signature to convert + * @param methodName the name of the method to insert in the result, or + * null if no method name is to be included + * @param parameterNames the parameter names to insert in the result, or + * null if no parameter names are to be included; if supplied, + * the number of parameter names must match that of the method signature + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param includeReturnType true if the return type is to be + * included + * @return the char array representation of the method signature + * + * @since 2.0 + */ +public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) { + try { + int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature); + if (firstParen == -1) throw new IllegalArgumentException(); + + int sigLength = methodSignature.length; + + // compute result length + + // method signature + int paramCount = 0; + int lastParen = -1; + int resultLength = 0; + signature: for (int i = firstParen; i < sigLength; i++) { + switch (methodSignature[i]) { + case C_ARRAY : + resultLength += 2; // [] + continue signature; + case C_BOOLEAN : + resultLength += BOOLEAN.length; + break; + case C_BYTE : + resultLength += BYTE.length; + break; + case C_CHAR : + resultLength += CHAR.length; + break; + case C_DOUBLE : + resultLength += DOUBLE.length; + break; + case C_FLOAT : + resultLength += FLOAT.length; + break; + case C_INT : + resultLength += INT.length; + break; + case C_LONG : + resultLength += LONG.length; + break; + case C_SHORT : + resultLength += SHORT.length; + break; + case C_VOID : + resultLength += VOID.length; + break; + case C_RESOLVED : + case C_UNRESOLVED : + int end = CharOperation.indexOf(C_SEMICOLON, methodSignature, i); + if (end == -1) throw new IllegalArgumentException(); + int start; + if (fullyQualifyTypeNames) { + start = i+1; + } else { + start = CharOperation.lastIndexOf(C_DOT, methodSignature, i, end) + 1; + if (start == 0) start = i+1; + } + resultLength += end-start; + i = end; + break; + case C_PARAM_START : + // add space for "(" + resultLength++; + continue signature; + case C_PARAM_END : + lastParen = i; + if (includeReturnType) { + if (paramCount > 0) { + // remove space for ", " that was added with last parameter and remove space that is going to be added for ", " after return type + // and add space for ") " + resultLength -= 2; + } //else + // remove space that is going to be added for ", " after return type + // and add space for ") " + // -> noop + + // decrement param count because it is going to be added for return type + paramCount--; + continue signature; + } else { + if (paramCount > 0) { + // remove space for ", " that was added with last parameter and add space for ")" + resultLength--; + } else { + // add space for ")" + resultLength++; + } + break signature; + } + default : + throw new IllegalArgumentException(); + } + resultLength += 2; // add space for ", " + paramCount++; + } + + // parameter names + int parameterNamesLength = parameterNames == null ? 0 : parameterNames.length; + for (int i = 0; i >> 32); + result[index++] = ' '; + } + + // selector + if (methodName != null) { + System.arraycopy(methodName, 0, result, index, selectorLength); + index += selectorLength; + } + + // parameters + result[index++] = C_PARAM_START; + int sigPos = firstParen+1; + for (int i = 0; i < paramCount; i++) { + long pos = copyType(methodSignature, sigPos, result, index, fullyQualifyTypeNames); + index = (int) (pos >>> 32); + sigPos = (int)pos; + if (parameterNames != null) { + result[index++] = ' '; + char[] parameterName = parameterNames[i]; + int paramLength = parameterName.length; + System.arraycopy(parameterName, 0, result, index, paramLength); + index += paramLength; + } + if (i != paramCount-1) { + result[index++] = ','; + result[index++] = ' '; + } + } + if (sigPos >= sigLength) { + throw new IllegalArgumentException(); // should be on last paren + } + result[index++] = C_PARAM_END; + + return result; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); + } +} +/** + * Converts the given type signature to a readable string. The signature is expected to + * be dot-based. + * + *

    + * For example: + *

    + * 
    + * toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
    + * toString({'I'}) -> {'i', 'n', 't'}
    + * 
    + * 
    + *

    + *

    + * Note: This method assumes that a type signature containing a '$' + * is an inner type signature. While this is correct in most cases, someone could + * define a non-inner type name containing a '$'. Handling this + * correctly in all cases would have required resolving the signature, which + * generally not feasible. + *

    + * + * @param signature the type signature + * @return the string representation of the type + * @exception IllegalArgumentException if the signature is not syntactically + * correct + * + * @since 2.0 + */ +public static char[] toCharArray(char[] signature) throws IllegalArgumentException { + try { + int sigLength = signature.length; + + if (sigLength == 0 || signature[0] == C_PARAM_START) { + return toCharArray(signature, NO_CHAR, null, true, true); + } + + // compute result length + int resultLength = 0; + int index = -1; + while (signature[++index] == C_ARRAY) { + resultLength += 2; // [] + } + switch (signature[index]) { + case C_BOOLEAN : + resultLength += BOOLEAN.length; + break; + case C_BYTE : + resultLength += BYTE.length; + break; + case C_CHAR : + resultLength += CHAR.length; + break; + case C_DOUBLE : + resultLength += DOUBLE.length; + break; + case C_FLOAT : + resultLength += FLOAT.length; + break; + case C_INT : + resultLength += INT.length; + break; + case C_LONG : + resultLength += LONG.length; + break; + case C_SHORT : + resultLength += SHORT.length; + break; + case C_VOID : + resultLength += VOID.length; + break; + case C_RESOLVED : + case C_UNRESOLVED : + int end = CharOperation.indexOf(C_SEMICOLON, signature, index); + if (end == -1) throw new IllegalArgumentException(); + int start = index + 1; + resultLength += end-start; + break; + default : + throw new IllegalArgumentException(); + } + + char[] result = new char[resultLength]; + copyType(signature, 0, result, 0, true); + + /** + * Converts '$' separated type signatures into '.' separated type signature. + * NOTE: This assumes that the type signature is an inner type signature. + * This is true in most cases, but someone can define a non-inner type + * name containing a '$'. However to tell the difference, we would have + * to resolve the signature, which cannot be done at this point. + */ + CharOperation.replace(result, C_DOLLAR, C_DOT); + + return result; + } catch (ArrayIndexOutOfBoundsException e) { + throw new IllegalArgumentException(); + } +} +/** + * Converts the given array of qualified name segments to a qualified name. + *

    + * For example: + *

    + * 
    + * toQualifiedName({{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}
    + * toQualifiedName({{'O', 'b', 'j', 'e', 'c', 't'}}) -> {'O', 'b', 'j', 'e', 'c', 't'}
    + * toQualifiedName({{}}) -> {}
    + * 
    + * 
    + *

    + * + * @param segments the list of name segments, possibly empty + * @return the dot-separated qualified name, or the empty string + * + * @since 2.0 + */ +public static char[] toQualifiedName(char[][] segments) { + int length = segments.length; + if (length == 0) return NO_CHAR; + if (length == 1) return segments[0]; + + int resultLength = 0; + for (int i = 0; i < length; i++) { + resultLength += segments[i].length+1; + } + resultLength--; + char[] result = new char[resultLength]; + int index = 0; + for (int i = 0; i < length; i++) { + char[] segment = segments[i]; + int segmentLength = segment.length; + System.arraycopy(segment, 0, result, index, segmentLength); + index += segmentLength; + if (i != length-1) { + result[index++] = C_DOT; + } + } + return result; +} +/** + * Converts the given array of qualified name segments to a qualified name. + *

    + * For example: + *

    + * 
    + * toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
    + * toQualifiedName(new String[] {"Object"}) -> "Object"
    + * toQualifiedName(new String[0]) -> ""
    + * 
    + * 
    + *

    + * + * @param segments the list of name segments, possibly empty + * @return the dot-separated qualified name, or the empty string + */ +public static String toQualifiedName(String[] segments) { + int length = segments.length; + char[][] charArrays = new char[length][]; + for (int i = 0; i < length; i++) { + charArrays[i] = segments[i].toCharArray(); + } + return new String(toQualifiedName(charArrays)); +} +/** + * Converts the given type signature to a readable string. The signature is expected to + * be dot-based. + * + *

    + * For example: + *

    + * 
    + * toString("[Ljava.lang.String;") -> "java.lang.String[]"
    + * toString("I") -> "int"
    + * 
    + * 
    + *

    + *

    + * Note: This method assumes that a type signature containing a '$' + * is an inner type signature. While this is correct in most cases, someone could + * define a non-inner type name containing a '$'. Handling this + * correctly in all cases would have required resolving the signature, which + * generally not feasible. + *

    + * + * @param signature the type signature + * @return the string representation of the type + * @exception IllegalArgumentException if the signature is not syntactically + * correct + */ +public static String toString(String signature) throws IllegalArgumentException { + return new String(toCharArray(signature.toCharArray())); +} +/** + * Converts the given method signature to a readable string. The method signature is expected to + * be dot-based. + *

    + * For example: + *

    + * 
    + * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
    + * 
    + * 
    + *

    + * + * @param methodSignature the method signature to convert + * @param methodName the name of the method to insert in the result, or + * null if no method name is to be included + * @param parameterNames the parameter names to insert in the result, or + * null if no parameter names are to be included; if supplied, + * the number of parameter names must match that of the method signature + * @param fullyQualifyTypeNames true if type names should be fully + * qualified, and false to use only simple names + * @param includeReturnType true if the return type is to be + * included + * @return the string representation of the method signature + */ +public static String toString(String methodSignature, String methodName, String[] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) { + char[][] params; + if (parameterNames == null) { + params = null; + } else { + int paramLength = parameterNames.length; + params = new char[paramLength][]; + for (int i = 0; i < paramLength; i++) { + params[i] = parameterNames[i].toCharArray(); + } + } + return new String(toCharArray(methodSignature.toCharArray(), methodName == null ? null : methodName.toCharArray(), params, fullyQualifyTypeNames, includeReturnType)); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/CompletionEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/CompletionEngine.java new file mode 100644 index 0000000..8d4ed79 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/CompletionEngine.java @@ -0,0 +1,2702 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist; + +import java.util.*; + +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.*; +import net.sourceforge.phpdt.internal.compiler.env.*; + +import net.sourceforge.phpdt.internal.codeassist.impl.*; +import net.sourceforge.phpdt.core.ICompletionRequestor; +import net.sourceforge.phpdt.core.IType; +//import net.sourceforge.phpdt.core.JavaCore; +//import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.compiler.*; +import net.sourceforge.phpdt.core.compiler.IProblem; +import net.sourceforge.phpdt.internal.codeassist.complete.*; + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; +import net.sourceforge.phpdt.internal.compiler.parser.*; +import net.sourceforge.phpdt.internal.compiler.problem.*; +import net.sourceforge.phpdt.internal.compiler.util.*; +import net.sourceforge.phpdt.internal.core.BasicCompilationUnit; +import net.sourceforge.phpdt.internal.core.TypeConverter; +import net.sourceforge.phpdt.internal.compiler.impl.*; + +/** + * This class is the entry point for source completions. + * It contains two public APIs used to call CodeAssist on a given source with + * a given environment, assisting position and storage (and possibly options). + */ +public final class CompletionEngine + extends Engine + implements ISearchRequestor, TypeConstants , ITerminalSymbols , RelevanceConstants { + + public static boolean DEBUG = false; + + private final static char[] ERROR_PATTERN = "*error*".toCharArray(); //$NON-NLS-1$ + private final static char[] EXCEPTION_PATTERN = "*exception*".toCharArray(); //$NON-NLS-1$ + private final static char[] SEMICOLON = new char[] { ';' }; + TypeBinding[] expectedTypes; + + boolean assistNodeIsClass; + boolean assistNodeIsException; + boolean assistNodeIsInterface; + + CompletionParser parser; + ICompletionRequestor requestor; + ProblemReporter problemReporter; + char[] source; + char[] token; + boolean resolvingImports = false; + boolean insideQualifiedReference = false; + int startPosition, actualCompletionPosition, endPosition, offset; + HashtableOfObject knownPkgs = new HashtableOfObject(10); + HashtableOfObject knownTypes = new HashtableOfObject(10); + Scanner nameScanner; + + /* + static final char[][] mainDeclarations = + new char[][] { + "package".toCharArray(), + "import".toCharArray(), + "abstract".toCharArray(), + "final".toCharArray(), + "public".toCharArray(), + "class".toCharArray(), + "interface".toCharArray()}; + + static final char[][] modifiers = // may want field, method, type & member type modifiers + new char[][] { + "abstract".toCharArray(), + "final".toCharArray(), + "native".toCharArray(), + "public".toCharArray(), + "protected".toCharArray(), + "private".toCharArray(), + "static".toCharArray(), + "strictfp".toCharArray(), + "synchronized".toCharArray(), + "transient".toCharArray(), + "volatile".toCharArray()}; + */ + static final char[][] baseTypes = new char[][] { + "boolean".toCharArray(), //$NON-NLS-1$ + "byte".toCharArray(), //$NON-NLS-1$ + "char".toCharArray(), //$NON-NLS-1$ + "double".toCharArray(), //$NON-NLS-1$ + "float".toCharArray(), //$NON-NLS-1$ + "int".toCharArray(), //$NON-NLS-1$ + "long".toCharArray(), //$NON-NLS-1$ + "short".toCharArray(), //$NON-NLS-1$ + "void".toCharArray(), //$NON-NLS-1$ + }; + + static final char[] classField = "class".toCharArray(); //$NON-NLS-1$ + static final char[] lengthField = "length".toCharArray(); //$NON-NLS-1$ + static final char[] THIS = "this".toCharArray(); //$NON-NLS-1$ + static final char[] THROWS = "throws".toCharArray(); //$NON-NLS-1$ + + static InvocationSite FakeInvocationSite = new InvocationSite(){ + public boolean isSuperAccess(){ return false; } + public boolean isTypeAccess(){ return false; } + public void setActualReceiverType(ReferenceBinding receiverType) {} + public void setDepth(int depth){} + public void setFieldIndex(int depth){} + }; + + /** + * The CompletionEngine is responsible for computing source completions. + * + * It requires a searchable name environment, which supports some + * specific search APIs, and a requestor to feed back the results to a UI. + * + * @param nameEnvironment net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment + * used to resolve type/package references and search for types/packages + * based on partial names. + * + * @param requestor net.sourceforge.phpdt.internal.codeassist.ICompletionRequestor + * since the engine might produce answers of various forms, the engine + * is associated with a requestor able to accept all possible completions. + * + * @param settings java.util.Map + * set of options used to configure the code assist engine. + */ + public CompletionEngine( + ISearchableNameEnvironment nameEnvironment, + ICompletionRequestor requestor, + Map settings) { + + super(settings); + this.requestor = requestor; + this.nameEnvironment = nameEnvironment; + + problemReporter = new ProblemReporter( + DefaultErrorHandlingPolicies.proceedWithAllProblems(), + this.compilerOptions, + new DefaultProblemFactory(Locale.getDefault()) { + public void record(IProblem problem, CompilationResult unitResult, ReferenceContext referenceContext) { + if (problem.isError() && (problem.getID() & IProblem.Syntax) != 0) { + CompletionEngine.this.requestor.acceptError(problem); + } + } + }); + this.parser = + new CompletionParser(problemReporter, this.compilerOptions.assertMode); + this.lookupEnvironment = + new LookupEnvironment(this, this.compilerOptions, problemReporter, nameEnvironment); + this.nameScanner = + new Scanner(false, false, false, this.compilerOptions.assertMode); + } + + /** + * One result of the search consists of a new class. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + public void acceptClass(char[] packageName, char[] className, int modifiers) { + + char[] fullyQualifiedName = CharOperation.concat(packageName, className, '.'); + char[] completionName = fullyQualifiedName; + + if (this.knownTypes.containsKey(completionName)) return; + + this.knownTypes.put(completionName, this); + + int relevance = R_DEFAULT; + if (resolvingImports) { + completionName = CharOperation.concat(completionName, SEMICOLON); + relevance += computeRelevanceForCaseMatching(token, fullyQualifiedName); + } else { + if (!insideQualifiedReference) { + if (mustQualifyType(packageName, className)) { + if (packageName == null || packageName.length == 0) + if (unitScope != null && unitScope.fPackage.compoundName != NoCharChar) + return; // ignore types from the default package from outside it + } else { + completionName = className; + } + } + relevance += computeRelevanceForCaseMatching(token, className); + relevance += computeRelevanceForExpectingType(packageName, className); + relevance += computeRelevanceForClass(); + relevance += computeRelevanceForException(className); + } + + requestor.acceptClass( + packageName, + className, + completionName, + modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + + /** + * One result of the search consists of a new interface. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.I". + * The default package is represented by an empty array. + */ + public void acceptInterface( + char[] packageName, + char[] interfaceName, + int modifiers) { + + char[] fullyQualifiedName = CharOperation.concat(packageName, interfaceName, '.'); + char[] completionName = fullyQualifiedName; + + if (this.knownTypes.containsKey(completionName)) return; + + this.knownTypes.put(completionName, this); + + int relevance = R_DEFAULT; + if (resolvingImports) { + completionName = CharOperation.concat(completionName, new char[] { ';' }); + relevance += computeRelevanceForCaseMatching(token, fullyQualifiedName); + } else { + if (!insideQualifiedReference) { + if (mustQualifyType(packageName, interfaceName)) { + if (packageName == null || packageName.length == 0) + if (unitScope != null && unitScope.fPackage.compoundName != NoCharChar) + return; // ignore types from the default package from outside it + } else { + completionName = interfaceName; + } + } + relevance += computeRelevanceForCaseMatching(token, interfaceName); + relevance += computeRelevanceForExpectingType(packageName, interfaceName); + relevance += computeRelevanceForInterface(); + } + + requestor.acceptInterface( + packageName, + interfaceName, + completionName, + modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + + /** + * One result of the search consists of a new package. + * + * NOTE - All package names are presented in their readable form: + * Package names are in the form "a.b.c". + * The default package is represented by an empty array. + */ + public void acceptPackage(char[] packageName) { + + if (this.knownPkgs.containsKey(packageName)) return; + + this.knownPkgs.put(packageName, this); + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token, packageName); + + requestor.acceptPackage( + packageName, + resolvingImports + ? CharOperation.concat(packageName, new char[] { '.', '*', ';' }) + : packageName, + startPosition - offset, + endPosition - offset, + relevance); + } + + /** + * One result of the search consists of a new type. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + public void acceptType(char[] packageName, char[] typeName) { + + char[] fullyQualifiedName = CharOperation.concat(packageName, typeName, '.'); + char[] completionName = fullyQualifiedName; + + if (this.knownTypes.containsKey(completionName)) return; + + this.knownTypes.put(completionName, this); + + int relevance = R_DEFAULT; + if (resolvingImports) { + completionName = CharOperation.concat(completionName, new char[] { ';' }); + relevance += computeRelevanceForCaseMatching(token, fullyQualifiedName); + } else { + if (!insideQualifiedReference) { + if (mustQualifyType(packageName, typeName)) { + if (packageName == null || packageName.length == 0) + if (unitScope != null && unitScope.fPackage.compoundName != NoCharChar) + return; // ignore types from the default package from outside it + } else { + completionName = typeName; + } + } + relevance += computeRelevanceForCaseMatching(token, typeName); + relevance += computeRelevanceForExpectingType(packageName, typeName); + } + + requestor.acceptType( + packageName, + typeName, + completionName, + startPosition - offset, + endPosition - offset, + relevance); + } + + private void complete(AstNode astNode, Binding qualifiedBinding, Scope scope) { + + setSourceRange(astNode.sourceStart, astNode.sourceEnd); + + if(parser.assistNodeParent != null) { + computeExpectedTypes(parser.assistNodeParent, scope); + } + + // defaults... some nodes will change these + if (astNode instanceof CompletionOnFieldType) { + + CompletionOnFieldType field = (CompletionOnFieldType) astNode; + CompletionOnSingleTypeReference type = (CompletionOnSingleTypeReference) field.type; + token = type.token; + setSourceRange(type.sourceStart, type.sourceEnd); + // findKeywords(token, modifiers, scope); // could be the start of a field, method or member type + findTypesAndPackages(token, scope); + + if(!field.isLocalVariable && field.modifiers == CompilerModifiers.AccDefault) { + findMethods(token,null,scope.enclosingSourceType(),scope,new ObjectVector(),false,false,true,null,null,false); + } + } else { + if(astNode instanceof CompletionOnMethodReturnType) { + + CompletionOnMethodReturnType method = (CompletionOnMethodReturnType) astNode; + SingleTypeReference type = (CompletionOnSingleTypeReference) method.returnType; + token = type.token; + setSourceRange(type.sourceStart, type.sourceEnd); + findTypesAndPackages(token, scope); + + if(method.modifiers == CompilerModifiers.AccDefault) { + findMethods(token,null,scope.enclosingSourceType(),scope,new ObjectVector(),false,false,true,null,null,false); + } + } else { + + if (astNode instanceof CompletionOnSingleNameReference) { + + token = ((CompletionOnSingleNameReference) astNode).token; + findVariablesAndMethods( + token, + scope, + (CompletionOnSingleNameReference) astNode, + scope); + // can be the start of a qualified type name + findTypesAndPackages(token, scope); + + } else { + + if (astNode instanceof CompletionOnSingleTypeReference) { + + token = ((CompletionOnSingleTypeReference) astNode).token; + + assistNodeIsClass = astNode instanceof CompletionOnClassReference; + assistNodeIsException = astNode instanceof CompletionOnExceptionReference; + assistNodeIsInterface = astNode instanceof CompletionOnInterfaceReference; + + // can be the start of a qualified type name + if (qualifiedBinding == null) { + findTypesAndPackages(token, scope); + } else { + findMemberTypes( + token, + (ReferenceBinding) qualifiedBinding, + scope, + scope.enclosingSourceType()); + } + } else { + + if (astNode instanceof CompletionOnQualifiedNameReference) { + + insideQualifiedReference = true; + CompletionOnQualifiedNameReference ref = + (CompletionOnQualifiedNameReference) astNode; + token = ref.completionIdentifier; + long completionPosition = ref.sourcePositions[ref.sourcePositions.length - 1]; + + if (qualifiedBinding instanceof VariableBinding) { + + setSourceRange((int) (completionPosition >>> 32), (int) completionPosition); + TypeBinding receiverType = ((VariableBinding) qualifiedBinding).type; + if (receiverType != null) { + findFieldsAndMethods(token, receiverType, scope, ref, scope,false); + } + + } else { + + if (qualifiedBinding instanceof ReferenceBinding) { + + ReferenceBinding receiverType = (ReferenceBinding) qualifiedBinding; + setSourceRange((int) (completionPosition >>> 32), (int) completionPosition); + + findMemberTypes(token, receiverType, scope, scope.enclosingSourceType()); + + findClassField(token, (TypeBinding) qualifiedBinding, scope); + + findFields( + token, + receiverType, + scope, + new ObjectVector(), + new ObjectVector(), + true, + ref, + scope, + false); + + findMethods( + token, + null, + receiverType, + scope, + new ObjectVector(), + true, + false, + false, + ref, + scope, + false); + + } else { + + if (qualifiedBinding instanceof PackageBinding) { + + setSourceRange(astNode.sourceStart, (int) completionPosition); + // replace to the end of the completion identifier + findTypesAndSubpackages(token, (PackageBinding) qualifiedBinding); + } + } + } + + } else { + + if (astNode instanceof CompletionOnQualifiedTypeReference) { + + insideQualifiedReference = true; + + assistNodeIsClass = astNode instanceof CompletionOnQualifiedClassReference; + assistNodeIsException = astNode instanceof CompletionOnQualifiedExceptionReference; + assistNodeIsInterface = astNode instanceof CompletionOnQualifiedInterfaceReference; + + CompletionOnQualifiedTypeReference ref = + (CompletionOnQualifiedTypeReference) astNode; + token = ref.completionIdentifier; + long completionPosition = ref.sourcePositions[ref.tokens.length]; + + // get the source positions of the completion identifier + if (qualifiedBinding instanceof ReferenceBinding) { + + setSourceRange((int) (completionPosition >>> 32), (int) completionPosition); + findMemberTypes( + token, + (ReferenceBinding) qualifiedBinding, + scope, + scope.enclosingSourceType()); + + } else { + + if (qualifiedBinding instanceof PackageBinding) { + + setSourceRange(astNode.sourceStart, (int) completionPosition); + // replace to the end of the completion identifier + findTypesAndSubpackages(token, (PackageBinding) qualifiedBinding); + } + } + + } else { + + if (astNode instanceof CompletionOnMemberAccess) { + + CompletionOnMemberAccess access = (CompletionOnMemberAccess) astNode; + long completionPosition = access.nameSourcePosition; + setSourceRange((int) (completionPosition >>> 32), (int) completionPosition); + + token = access.token; + + findFieldsAndMethods( + token, + (TypeBinding) qualifiedBinding, + scope, + access, + scope, + false); + + } else { + + if (astNode instanceof CompletionOnMessageSend) { + + CompletionOnMessageSend messageSend = (CompletionOnMessageSend) astNode; + TypeBinding[] argTypes = + computeTypes(messageSend.arguments, (BlockScope) scope); + token = messageSend.selector; + if (qualifiedBinding == null) { + + findImplicitMessageSends(token, argTypes, scope, messageSend, scope); + } else { + + findMethods( + token, + argTypes, + (ReferenceBinding) qualifiedBinding, + scope, + new ObjectVector(), + false, + true, + false, + messageSend, + scope, + false); + } + + } else { + + if (astNode instanceof CompletionOnExplicitConstructorCall) { + + CompletionOnExplicitConstructorCall constructorCall = + (CompletionOnExplicitConstructorCall) astNode; + TypeBinding[] argTypes = + computeTypes(constructorCall.arguments, (BlockScope) scope); + findConstructors( + (ReferenceBinding) qualifiedBinding, + argTypes, + scope, + constructorCall, + false); + + } else { + + if (astNode instanceof CompletionOnQualifiedAllocationExpression) { + + CompletionOnQualifiedAllocationExpression allocExpression = + (CompletionOnQualifiedAllocationExpression) astNode; + TypeBinding[] argTypes = + computeTypes(allocExpression.arguments, (BlockScope) scope); + + ReferenceBinding ref = (ReferenceBinding) qualifiedBinding; + if(ref.isClass()) { + if(!ref.isAbstract()) { + findConstructors( + ref, + argTypes, + scope, + allocExpression, + false); + } + } + if(!ref.isFinal()){ + findAnonymousType( + ref, + argTypes, + scope, + allocExpression); + } + + } else { + + if (astNode instanceof CompletionOnClassLiteralAccess) { + CompletionOnClassLiteralAccess access = (CompletionOnClassLiteralAccess) astNode; + setSourceRange(access.classStart, access.sourceEnd); + + token = access.completionIdentifier; + + findClassField(token, (TypeBinding) qualifiedBinding, scope); + } else { + if(astNode instanceof CompletionOnMethodName) { + CompletionOnMethodName method = (CompletionOnMethodName) astNode; + + setSourceRange(method.sourceStart, method.selectorEnd); + + FieldBinding[] fields = scope.enclosingSourceType().fields(); + char[][] excludeNames = new char[fields.length][]; + for(int i = 0 ; i < fields.length ; i++){ + excludeNames[i] = fields[i].name; + } + + token = method.selector; + + findVariableNames(token, method.returnType, excludeNames); + } else { + if (astNode instanceof CompletionOnFieldName) { + CompletionOnFieldName field = (CompletionOnFieldName) astNode; + + FieldBinding[] fields = scope.enclosingSourceType().fields(); + char[][] excludeNames = new char[fields.length][]; + for(int i = 0 ; i < fields.length ; i++){ + excludeNames[i] = fields[i].name; + } + + token = field.realName; + + findVariableNames(field.realName, field.type, excludeNames); + } else { + if (astNode instanceof CompletionOnLocalName || + astNode instanceof CompletionOnArgumentName){ + LocalDeclaration variable = (LocalDeclaration) astNode; + + LocalVariableBinding[] locals = ((BlockScope)scope).locals; + char[][] excludeNames = new char[locals.length][]; + int localCount = 0; + for(int i = 0 ; i < locals.length ; i++){ + if(locals[i] != null) { + excludeNames[localCount++] = locals[i].name; + } + } + System.arraycopy(excludeNames, 0, excludeNames = new char[localCount][], 0, localCount); + + if(variable instanceof CompletionOnLocalName){ + token = ((CompletionOnLocalName) variable).realName; + } else { + token = ((CompletionOnArgumentName) variable).realName; + } + findVariableNames(token, variable.type, excludeNames); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + +// public void complete(IType type, char[] snippet, int position, char[][] localVariableTypeNames, char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic){ +// TypeConverter converter = new TypeConverter(); +// +// IType topLevelType = type; +// while(topLevelType.getDeclaringType() != null) { +// topLevelType = topLevelType.getDeclaringType(); +// } +// +// CompilationResult compilationResult = new CompilationResult((topLevelType.getElementName() + ".java").toCharArray(), 1, 1, this.compilerOptions.maxProblemsPerUnit); //$NON-NLS-1$ +// +// CompilationUnitDeclaration compilationUnit = new CompilationUnitDeclaration(problemReporter, compilationResult, 0); +// +// try { +// TypeDeclaration typeDeclaration = converter.buildTypeDeclaration(type, compilationUnit, compilationResult, problemReporter); +// +// if(typeDeclaration != null) { +// // build AST from snippet +// Initializer fakeInitializer = parseSnippeInitializer(snippet, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic); +// +// // merge AST +// FieldDeclaration[] oldFields = typeDeclaration.fields; +// FieldDeclaration[] newFields = new FieldDeclaration[oldFields.length + 1]; +// System.arraycopy(oldFields, 0, newFields, 0, oldFields.length); +// newFields[oldFields.length] = fakeInitializer; +// typeDeclaration.fields = newFields; +// +// if(DEBUG) { +// System.out.println("SNIPPET COMPLETION AST :"); //$NON-NLS-1$ +// System.out.println(compilationUnit.toString()); +// } +// +// if (compilationUnit.types != null) { +// try { +// lookupEnvironment.buildTypeBindings(compilationUnit); +// +// if ((unitScope = compilationUnit.scope) != null) { +// lookupEnvironment.completeTypeBindings(compilationUnit, true); +// compilationUnit.scope.faultInTypes(); +// compilationUnit.resolve(); +// } +// } catch (CompletionNodeFound e) { +// // completionNodeFound = true; +// if (e.astNode != null) { +// // if null then we found a problem in the completion node +// complete(e.astNode, e.qualifiedBinding, e.scope); +// } +// } +// } +// } +// } catch(JavaModelException e) { +// // Do nothing +// } +// } + +// private Initializer parseSnippeInitializer(char[] snippet, int position, char[][] localVariableTypeNames, char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic){ +// StringBuffer prefix = new StringBuffer(); +// prefix.append("public class FakeType {\n "); //$NON-NLS-1$ +// if(isStatic) { +// prefix.append("static "); //$NON-NLS-1$ +// } +// prefix.append("{\n"); //$NON-NLS-1$ +// for (int i = 0; i < localVariableTypeNames.length; i++) { +// prefix.append(AstNode.modifiersString(localVariableModifiers[i])); +// prefix.append(' '); +// prefix.append(localVariableTypeNames[i]); +// prefix.append(' '); +// prefix.append(localVariableNames[i]); +// prefix.append(';'); +// } +// +// char[] fakeSource = CharOperation.concat(prefix.toString().toCharArray(), snippet, "}}".toCharArray());//$NON-NLS-1$ +// offset = prefix.length(); +// +// String encoding = JavaCore.getOption(JavaCore.CORE_ENCODING); +// BasicCompilationUnit fakeUnit = new BasicCompilationUnit( +// fakeSource, +// null, +// "FakeType.java", //$NON-NLS-1$ +// encoding); +// +// actualCompletionPosition = prefix.length() + position - 1; +// +// CompilationResult fakeResult = new CompilationResult(fakeUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit); +// CompilationUnitDeclaration fakeAST = parser.dietParse(fakeUnit, fakeResult, actualCompletionPosition); +// +// parseMethod(fakeAST, actualCompletionPosition); +// +// return (Initializer)fakeAST.types[0].fields[0]; +// } + + /** + * Ask the engine to compute a completion at the specified position + * of the given compilation unit. + * + * @return void + * completion results are answered through a requestor. + * + * @param sourceUnit net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + * the source of the current compilation unit. + * + * @param completionPosition int + * a position in the source where the completion is taking place. + * This position is relative to the source provided. + */ + public void complete(ICompilationUnit sourceUnit, int completionPosition, int offset) { + + if(DEBUG) { + System.out.print("COMPLETION IN "); //$NON-NLS-1$ + System.out.print(sourceUnit.getFileName()); + System.out.print(" AT POSITION "); //$NON-NLS-1$ + System.out.println(completionPosition); + System.out.println("COMPLETION - Source :"); //$NON-NLS-1$ + System.out.println(sourceUnit.getContents()); + } + try { + actualCompletionPosition = completionPosition - 1; + this.offset = offset; + // for now until we can change the UI. + CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = parser.dietParse(sourceUnit, result, actualCompletionPosition); + + // boolean completionNodeFound = false; + if (parsedUnit != null) { + if(DEBUG) { + System.out.println("COMPLETION - Diet AST :"); //$NON-NLS-1$ + System.out.println(parsedUnit.toString()); + } + + // scan the package & import statements first + if (parsedUnit.currentPackage instanceof CompletionOnPackageReference) { + findPackages((CompletionOnPackageReference) parsedUnit.currentPackage); + return; + } + + ImportReference[] imports = parsedUnit.imports; + if (imports != null) { + for (int i = 0, length = imports.length; i < length; i++) { + ImportReference importReference = imports[i]; + if (importReference instanceof CompletionOnImportReference) { + findImports((CompletionOnImportReference) importReference); + return; + } + } + } + + if (parsedUnit.types != null) { + try { + lookupEnvironment.buildTypeBindings(parsedUnit); + + if ((unitScope = parsedUnit.scope) != null) { + source = sourceUnit.getContents(); + lookupEnvironment.completeTypeBindings(parsedUnit, true); + parsedUnit.scope.faultInTypes(); + parseMethod(parsedUnit, actualCompletionPosition); + if(DEBUG) { + System.out.println("COMPLETION - AST :"); //$NON-NLS-1$ + System.out.println(parsedUnit.toString()); + } + parsedUnit.resolve(); + } + } catch (CompletionNodeFound e) { + // completionNodeFound = true; + if (e.astNode != null) { + if(DEBUG) { + System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ + System.out.println(e.astNode.toString()); + } + // if null then we found a problem in the completion node + complete(e.astNode, e.qualifiedBinding, e.scope); + } + } + } + } + + /* Ignore package, import, class & interface keywords for now... + if (!completionNodeFound) { + if (parsedUnit == null || parsedUnit.types == null) { + // this is not good enough... can still be trying to define a second type + CompletionScanner scanner = (CompletionScanner) parser.scanner; + setSourceRange(scanner.completedIdentifierStart, scanner.completedIdentifierEnd); + findKeywords(scanner.completionIdentifier, mainDeclarations, null); + } + // currently have no way to know if extends/implements are possible keywords + } + */ + } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D + } catch (InvalidCursorLocation e) { // may eventually report a usefull error + } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object + } catch (CompletionNodeFound e){ // internal failure - bugs 5618 + } finally { + reset(); + } + } + + private TypeBinding[] computeTypes(Expression[] arguments, BlockScope scope) { + + if (arguments == null) + return null; + + int argsLength = arguments.length; + TypeBinding[] argTypes = new TypeBinding[argsLength]; + for (int a = argsLength; --a >= 0;) + argTypes[a] = arguments[a].resolveType(scope); + return argTypes; + } + + private void findAnonymousType( + ReferenceBinding currentType, + TypeBinding[] argTypes, + Scope scope, + InvocationSite invocationSite) { + + if (currentType.isInterface()) { + char[] completion = TypeConstants.NoChar; + // nothing to insert - do not want to replace the existing selector & arguments + if (source == null + || source.length <= endPosition + || source[endPosition] != ')') + completion = new char[] { ')' }; + + requestor.acceptAnonymousType( + currentType.qualifiedPackageName(), + currentType.qualifiedSourceName(), + TypeConstants.NoCharChar, + TypeConstants.NoCharChar, + TypeConstants.NoCharChar, + completion, + IConstants.AccPublic, + endPosition - offset, + endPosition - offset, + R_DEFAULT); + } else { + findConstructors( + currentType, + argTypes, + scope, + invocationSite, + true); + } + } + + private void findClassField(char[] token, TypeBinding receiverType, Scope scope) { + + if (token == null) + return; + + if (token.length <= classField.length + && CharOperation.prefixEquals(token, classField, false /* ignore case */ + )) { + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token, classField); + relevance += computeRelevanceForExpectingType(scope.getJavaLangClass()); + + requestor.acceptField( + NoChar, + NoChar, + classField, + NoChar, + NoChar, + classField, + CompilerModifiers.AccStatic | CompilerModifiers.AccPublic, + startPosition - offset, + endPosition - offset, + relevance); + } + } + + private void findConstructors( + ReferenceBinding currentType, + TypeBinding[] argTypes, + Scope scope, + InvocationSite invocationSite, + boolean forAnonymousType) { + + // No visibility checks can be performed without the scope & invocationSite + MethodBinding[] methods = currentType.availableMethods(); + if(methods != null) { + int minArgLength = argTypes == null ? 0 : argTypes.length; + next : for (int f = methods.length; --f >= 0;) { + MethodBinding constructor = methods[f]; + if (constructor.isConstructor()) { + + if (constructor.isSynthetic()) continue next; + + if (options.checkVisibility + && !constructor.canBeSeenBy(invocationSite, scope)) continue next; + + TypeBinding[] parameters = constructor.parameters; + int paramLength = parameters.length; + if (minArgLength > paramLength) + continue next; + for (int a = minArgLength; --a >= 0;) + if (argTypes[a] != null) // can be null if it could not be resolved properly + if (!scope.areTypesCompatible(argTypes[a], constructor.parameters[a])) + continue next; + + char[][] parameterPackageNames = new char[paramLength][]; + char[][] parameterTypeNames = new char[paramLength][]; + for (int i = 0; i < paramLength; i++) { + TypeBinding type = parameters[i]; + parameterPackageNames[i] = type.qualifiedPackageName(); + parameterTypeNames[i] = type.qualifiedSourceName(); + } + char[][] parameterNames = findMethodParameterNames(constructor,parameterTypeNames); + + char[] completion = TypeConstants.NoChar; + // nothing to insert - do not want to replace the existing selector & arguments + if (source == null + || source.length <= endPosition + || source[endPosition] != ')') + completion = new char[] { ')' }; + + if(forAnonymousType){ + requestor.acceptAnonymousType( + currentType.qualifiedPackageName(), + currentType.qualifiedSourceName(), + parameterPackageNames, + parameterTypeNames, + parameterNames, + completion, + constructor.modifiers, + endPosition - offset, + endPosition - offset, + R_DEFAULT); + } else { + requestor.acceptMethod( + currentType.qualifiedPackageName(), + currentType.qualifiedSourceName(), + currentType.sourceName(), + parameterPackageNames, + parameterTypeNames, + parameterNames, + TypeConstants.NoChar, + TypeConstants.NoChar, + completion, + constructor.modifiers, + endPosition - offset, + endPosition - offset, + R_DEFAULT); + } + } + } + } + } + + // Helper method for findFields(char[], ReferenceBinding, Scope, ObjectVector, boolean) + private void findFields( + char[] fieldName, + FieldBinding[] fields, + Scope scope, + ObjectVector fieldsFound, + ObjectVector localsFound, + boolean onlyStaticFields, + ReferenceBinding receiverType, + InvocationSite invocationSite, + Scope invocationScope, + boolean implicitCall) { + + // Inherited fields which are hidden by subclasses are filtered out + // No visibility checks can be performed without the scope & invocationSite + + int fieldLength = fieldName.length; + next : for (int f = fields.length; --f >= 0;) { + FieldBinding field = fields[f]; + + if (field.isSynthetic()) continue next; + + if (onlyStaticFields && !field.isStatic()) continue next; + + if (fieldLength > field.name.length) continue next; + + if (!CharOperation.prefixEquals(fieldName, field.name, false /* ignore case */)) continue next; + + if (options.checkVisibility + && !field.canBeSeenBy(receiverType, invocationSite, scope)) continue next; + + boolean prefixRequired = false; + + for (int i = fieldsFound.size; --i >= 0;) { + Object[] other = (Object[])fieldsFound.elementAt(i); + FieldBinding otherField = (FieldBinding) other[0]; + ReferenceBinding otherReceiverType = (ReferenceBinding) other[1]; + if (field == otherField && receiverType == otherReceiverType) + continue next; + if (CharOperation.equals(field.name, otherField.name, true)) { + if (field.declaringClass.isSuperclassOf(otherField.declaringClass)) + continue next; + if (otherField.declaringClass.isInterface()) + if (field.declaringClass.implementsInterface(otherField.declaringClass, true)) + continue next; + if (field.declaringClass.isInterface()) + if (otherField.declaringClass.implementsInterface(field.declaringClass, true)) + continue next; + prefixRequired = true; + } + } + + for (int l = localsFound.size; --l >= 0;) { + LocalVariableBinding local = (LocalVariableBinding) localsFound.elementAt(l); + + if (CharOperation.equals(field.name, local.name, true)) { + SourceTypeBinding declarationType = scope.enclosingSourceType(); + if (declarationType.isAnonymousType() && declarationType != invocationScope.enclosingSourceType()) { + continue next; + } + prefixRequired = true; + break; + } + } + + fieldsFound.add(new Object[]{field, receiverType}); + + char[] completion = field.name; + + if(prefixRequired || options.forceImplicitQualification){ + char[] prefix = computePrefix(scope.enclosingSourceType(), invocationScope.enclosingSourceType(), field.isStatic()); + completion = CharOperation.concat(prefix,completion,'.'); + } + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(fieldName, field.name); + relevance += computeRelevanceForExpectingType(field.type); + + requestor + .acceptField( + field.declaringClass.qualifiedPackageName(), + field.declaringClass.qualifiedSourceName(), + field.name, + field.type.qualifiedPackageName(), + field.type.qualifiedSourceName(), + completion, + // may include some qualification to resolve ambiguities + field.modifiers, startPosition - offset, endPosition - offset, + relevance); + } + } + + private void findFields( + char[] fieldName, + ReferenceBinding receiverType, + Scope scope, + ObjectVector fieldsFound, + ObjectVector localsFound, + boolean onlyStaticFields, + InvocationSite invocationSite, + Scope invocationScope, + boolean implicitCall) { + + if (fieldName == null) + return; + + ReferenceBinding currentType = receiverType; + ReferenceBinding[][] interfacesToVisit = null; + int lastPosition = -1; + do { + + ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + + if (interfacesToVisit == null) + interfacesToVisit = new ReferenceBinding[5][]; + + if (++lastPosition == interfacesToVisit.length) + System.arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, + lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + + FieldBinding[] fields = currentType.availableFields(); + if(fields != null) { + findFields( + fieldName, + fields, + scope, + fieldsFound, + localsFound, + onlyStaticFields, + receiverType, + invocationSite, + invocationScope, + implicitCall); + } + currentType = currentType.superclass(); + } while (currentType != null); + + if (interfacesToVisit != null) { + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + for (int j = 0, length = interfaces.length; j < length; j++) { + + ReferenceBinding anInterface = interfaces[j]; + if ((anInterface.tagBits & TagBits.InterfaceVisited) == 0) { + // if interface as not already been visited + anInterface.tagBits |= TagBits.InterfaceVisited; + + FieldBinding[] fields = anInterface.availableFields(); + if(fields != null) { + findFields( + fieldName, + fields, + scope, + fieldsFound, + localsFound, + onlyStaticFields, + receiverType, + invocationSite, + invocationScope, + implicitCall); + } + + ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + if (++lastPosition == interfacesToVisit.length) + System.arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, + lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + } + } + } + + // bit reinitialization + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + for (int j = 0, length = interfaces.length; j < length; j++) + interfaces[j].tagBits &= ~TagBits.InterfaceVisited; + } + } + } + + private void findFieldsAndMethods( + char[] token, + TypeBinding receiverType, + Scope scope, + InvocationSite invocationSite, + Scope invocationScope, + boolean implicitCall) { + + if (token == null) + return; + + if (receiverType.isBaseType()) + return; // nothing else is possible with base types + + if (receiverType.isArrayType()) { + if (token.length <= lengthField.length + && CharOperation.prefixEquals(token, lengthField, false /* ignore case */ + )) { + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token,lengthField); + relevance += computeRelevanceForExpectingType(BaseTypes.IntBinding); + + requestor.acceptField( + NoChar, + NoChar, + lengthField, + NoChar, + NoChar, + lengthField, + CompilerModifiers.AccPublic, + startPosition - offset, + endPosition - offset, + relevance); + } + receiverType = scope.getJavaLangObject(); + } + + findFields( + token, + (ReferenceBinding) receiverType, + scope, + new ObjectVector(), + new ObjectVector(), + false, + invocationSite, + invocationScope, + implicitCall); + + findMethods( + token, + null, + (ReferenceBinding) receiverType, + scope, + new ObjectVector(), + false, + false, + false, + invocationSite, + invocationScope, + implicitCall); + } + + private void findImports(CompletionOnImportReference importReference) { + char[][] tokens = importReference.tokens; + + char[] importName = CharOperation.concatWith(tokens, '.'); + + if (importName.length == 0) + return; + + char[] lastToken = tokens[tokens.length - 1]; + if(lastToken != null && lastToken.length == 0) + importName = CharOperation.concat(importName, new char[]{'.'}); + + resolvingImports = true; + setSourceRange( + importReference.sourceStart, + importReference.declarationSourceEnd); + + token = importName; + // want to replace the existing .*; + nameEnvironment.findPackages(importName, this); + nameEnvironment.findTypes(importName, this); + } + + // what about onDemand types? Ignore them since it does not happen! + // import p1.p2.A.*; + private void findKeywords(char[] keyword, char[][] choices, Scope scope) { + + int length = keyword.length; + if (length > 0) + for (int i = 0; i < choices.length; i++) + if (length <= choices[i].length + && CharOperation.prefixEquals(keyword, choices[i], false /* ignore case */ + )){ + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(keyword, choices[i]); + + requestor.acceptKeyword(choices[i], startPosition - offset, endPosition - offset,relevance); + } + } + + // Helper method for findMemberTypes(char[], ReferenceBinding, Scope) + private void findMemberTypes( + char[] typeName, + ReferenceBinding[] memberTypes, + ObjectVector typesFound, + ReferenceBinding receiverType, + SourceTypeBinding invocationType) { + + // Inherited member types which are hidden by subclasses are filtered out + // No visibility checks can be performed without the scope & invocationSite + int typeLength = typeName.length; + next : for (int m = memberTypes.length; --m >= 0;) { + ReferenceBinding memberType = memberTypes[m]; + // if (!wantClasses && memberType.isClass()) continue next; + // if (!wantInterfaces && memberType.isInterface()) continue next; + if (typeLength > memberType.sourceName.length) + continue next; + + if (!CharOperation.prefixEquals(typeName, memberType.sourceName, false + /* ignore case */ + )) + continue next; + + if (options.checkVisibility + && !memberType.canBeSeenBy(receiverType, invocationType)) + continue next; + + for (int i = typesFound.size; --i >= 0;) { + ReferenceBinding otherType = (ReferenceBinding) typesFound.elementAt(i); + + if (memberType == otherType) + continue next; + + if (CharOperation.equals(memberType.sourceName, otherType.sourceName, true)) { + + if (memberType.enclosingType().isSuperclassOf(otherType.enclosingType())) + continue next; + + if (otherType.enclosingType().isInterface()) + if (memberType.enclosingType() + .implementsInterface(otherType.enclosingType(), true)) + continue next; + + if (memberType.enclosingType().isInterface()) + if (otherType.enclosingType() + .implementsInterface(memberType.enclosingType(), true)) + continue next; + } + } + + typesFound.add(memberType); + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(typeName, memberType.sourceName); + relevance += computeRelevanceForExpectingType(memberType); + + if (memberType.isClass()) { + relevance += computeRelevanceForClass(); + requestor.acceptClass( + memberType.qualifiedPackageName(), + memberType.qualifiedSourceName(), + memberType.sourceName(), + memberType.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + + } else { + relevance += computeRelevanceForInterface(); + requestor.acceptInterface( + memberType.qualifiedPackageName(), + memberType.qualifiedSourceName(), + memberType.sourceName(), + memberType.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + } + } + + private void findMemberTypes( + char[] typeName, + ReferenceBinding receiverType, + Scope scope, + SourceTypeBinding typeInvocation) { + + ReferenceBinding currentType = receiverType; + if (typeName == null) + return; + + if (currentType.superInterfaces() == null) + return; // we're trying to find a supertype + + ObjectVector typesFound = new ObjectVector(); + if (insideQualifiedReference + || typeName.length == 0) { // do not search up the hierarchy + + findMemberTypes( + typeName, + currentType.memberTypes(), + typesFound, + receiverType, + typeInvocation); + return; + } + + ReferenceBinding[][] interfacesToVisit = null; + int lastPosition = -1; + + do { + + ReferenceBinding[] itsInterfaces = currentType.superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + + if (interfacesToVisit == null) + interfacesToVisit = new ReferenceBinding[5][]; + + if (++lastPosition == interfacesToVisit.length) + System.arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, + lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + + findMemberTypes( + typeName, + currentType.memberTypes(), + typesFound, + receiverType, + typeInvocation); + currentType = currentType.superclass(); + + } while (currentType != null); + + if (interfacesToVisit != null) { + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + for (int j = 0, length = interfaces.length; j < length; j++) { + + ReferenceBinding anInterface = interfaces[j]; + if ((anInterface.tagBits & TagBits.InterfaceVisited) == 0) { + // if interface as not already been visited + anInterface.tagBits |= TagBits.InterfaceVisited; + + findMemberTypes( + typeName, + anInterface.memberTypes(), + typesFound, + receiverType, + typeInvocation); + + ReferenceBinding[] itsInterfaces = anInterface.superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + + if (++lastPosition == interfacesToVisit.length) + System.arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, + lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + } + } + } + + // bit reinitialization + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + for (int j = 0, length = interfaces.length; j < length; j++) + interfaces[j].tagBits &= ~TagBits.InterfaceVisited; + } + } + } + + private void findIntefacesMethods( + char[] selector, + TypeBinding[] argTypes, + ReferenceBinding receiverType, + ReferenceBinding[] itsInterfaces, + Scope scope, + ObjectVector methodsFound, + boolean onlyStaticMethods, + boolean exactMatch, + boolean isCompletingDeclaration, + InvocationSite invocationSite, + Scope invocationScope, + boolean implicitCall) { + + if (selector == null) + return; + + if (itsInterfaces != NoSuperInterfaces) { + ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][]; + int lastPosition = 0; + interfacesToVisit[lastPosition] = itsInterfaces; + + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + + for (int j = 0, length = interfaces.length; j < length; j++) { + ReferenceBinding currentType = interfaces[j]; + + if ((currentType.tagBits & TagBits.InterfaceVisited) == 0) { + // if interface as not already been visited + currentType.tagBits |= TagBits.InterfaceVisited; + + MethodBinding[] methods = currentType.availableMethods(); + if(methods != null) { + if(isCompletingDeclaration){ + + findLocalMethodDeclarations( + selector, + methods, + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + receiverType); + + } else { + + findLocalMethods( + selector, + argTypes, + methods, + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + receiverType, + invocationSite, + invocationScope, + implicitCall); + } + } + + itsInterfaces = currentType.superInterfaces(); + if (itsInterfaces != NoSuperInterfaces) { + + if (++lastPosition == interfacesToVisit.length) + System.arraycopy( + interfacesToVisit, + 0, + interfacesToVisit = new ReferenceBinding[lastPosition * 2][], + 0, + lastPosition); + interfacesToVisit[lastPosition] = itsInterfaces; + } + } + } + } + + // bit reinitialization + for (int i = 0; i <= lastPosition; i++) { + ReferenceBinding[] interfaces = interfacesToVisit[i]; + + for (int j = 0, length = interfaces.length; j < length; j++){ + interfaces[j].tagBits &= ~TagBits.InterfaceVisited; + } + } + } + } + + private void findImplicitMessageSends( + char[] token, + TypeBinding[] argTypes, + Scope scope, + InvocationSite invocationSite, + Scope invocationScope) { + + if (token == null) + return; + + boolean staticsOnly = false; + // need to know if we're in a static context (or inside a constructor) + ObjectVector methodsFound = new ObjectVector(); + + done : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + + switch (scope.kind) { + + case Scope.METHOD_SCOPE : + // handle the error case inside an explicit constructor call (see MethodScope>>findField) + MethodScope methodScope = (MethodScope) scope; + staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; + break; + + case Scope.CLASS_SCOPE : + ClassScope classScope = (ClassScope) scope; + SourceTypeBinding enclosingType = classScope.referenceContext.binding; + findMethods( + token, + argTypes, + enclosingType, + classScope, + methodsFound, + staticsOnly, + true, + false, + invocationSite, + invocationScope, + true); + staticsOnly |= enclosingType.isStatic(); + break; + + case Scope.COMPILATION_UNIT_SCOPE : + break done; + } + scope = scope.parent; + } + } + + // Helper method for findMethods(char[], TypeBinding[], ReferenceBinding, Scope, ObjectVector, boolean, boolean, boolean) + private void findLocalMethods( + char[] methodName, + TypeBinding[] argTypes, + MethodBinding[] methods, + Scope scope, + ObjectVector methodsFound, + boolean onlyStaticMethods, + boolean exactMatch, + ReferenceBinding receiverType, + InvocationSite invocationSite, + Scope invocationScope, + boolean implicitCall) { + + // Inherited methods which are hidden by subclasses are filtered out + // No visibility checks can be performed without the scope & invocationSite + + int methodLength = methodName.length; + int minArgLength = argTypes == null ? 0 : argTypes.length; + + next : for (int f = methods.length; --f >= 0;) { + MethodBinding method = methods[f]; + + if (method.isSynthetic()) continue next; + + if (method.isDefaultAbstract()) continue next; + + if (method.isConstructor()) continue next; + + // if (noVoidReturnType && method.returnType == BaseTypes.VoidBinding) continue next; + if (onlyStaticMethods && !method.isStatic()) continue next; + + if (options.checkVisibility + && !method.canBeSeenBy(receiverType, invocationSite, scope)) continue next; + + if (exactMatch) { + if (!CharOperation.equals(methodName, method.selector, false /* ignore case */ + )) + continue next; + + } else { + + if (methodLength > method.selector.length) + continue next; + + if (!CharOperation.prefixEquals(methodName, method.selector, false + /* ignore case */ + )) + continue next; + } + if (minArgLength > method.parameters.length) + continue next; + + for (int a = minArgLength; --a >= 0;){ + if (argTypes[a] != null){ // can be null if it could not be resolved properly + if (!scope.areTypesCompatible(argTypes[a], method.parameters[a])) { + continue next; + } + } + } + + boolean prefixRequired = false; + + for (int i = methodsFound.size; --i >= 0;) { + Object[] other = (Object[]) methodsFound.elementAt(i); + MethodBinding otherMethod = (MethodBinding) other[0]; + ReferenceBinding otherReceiverType = (ReferenceBinding) other[1]; + if (method == otherMethod && receiverType == otherReceiverType) + continue next; + + if (CharOperation.equals(method.selector, otherMethod.selector, true) + && method.areParametersEqual(otherMethod)) { + + if (method.declaringClass.isSuperclassOf(otherMethod.declaringClass)) + continue next; + + if (otherMethod.declaringClass.isInterface()) + if (method + .declaringClass + .implementsInterface(otherMethod.declaringClass, true)) + continue next; + + if (method.declaringClass.isInterface()) + if(otherMethod + .declaringClass + .implementsInterface(method.declaringClass,true)) + continue next; + prefixRequired = true; + } + } + + methodsFound.add(new Object[]{method, receiverType}); + int length = method.parameters.length; + char[][] parameterPackageNames = new char[length][]; + char[][] parameterTypeNames = new char[length][]; + + for (int i = 0; i < length; i++) { + TypeBinding type = method.parameters[i]; + parameterPackageNames[i] = type.qualifiedPackageName(); + parameterTypeNames[i] = type.qualifiedSourceName(); + } + char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames); + + char[] completion = TypeConstants.NoChar; + + int previousStartPosition = startPosition; + + // nothing to insert - do not want to replace the existing selector & arguments + if (!exactMatch) { + if (source != null + && source.length > endPosition + && source[endPosition] == '(') + completion = method.selector; + else + completion = CharOperation.concat(method.selector, new char[] { '(', ')' }); + } else { + if(prefixRequired && (source != null)) { + completion = CharOperation.subarray(source, startPosition, endPosition); + } else { + startPosition = endPosition; + } + } + + if(prefixRequired || options.forceImplicitQualification){ + char[] prefix = computePrefix(scope.enclosingSourceType(), invocationScope.enclosingSourceType(), method.isStatic()); + completion = CharOperation.concat(prefix,completion,'.'); + } + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(methodName, method.selector); + relevance += computeRelevanceForExpectingType(method.returnType); + + requestor.acceptMethod( + method.declaringClass.qualifiedPackageName(), + method.declaringClass.qualifiedSourceName(), + method.selector, + parameterPackageNames, + parameterTypeNames, + parameterNames, + method.returnType.qualifiedPackageName(), + method.returnType.qualifiedSourceName(), + completion, + method.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + startPosition = previousStartPosition; + } + } + + private int computeRelevanceForCaseMatching(char[] token, char[] proposalName){ + if (CharOperation.prefixEquals(token, proposalName, true /* do not ignore case */)) { + return R_CASE; + } else { + return R_DEFAULT; + } + } + private int computeRelevanceForClass(){ + if(assistNodeIsClass) { + return R_CLASS; + } + return 0; + } + private int computeRelevanceForInterface(){ + if(assistNodeIsInterface) { + return R_INTERFACE; + } + return R_DEFAULT; + } + private int computeRelevanceForException(char[] proposalName){ + + if(assistNodeIsException && + (CharOperation.match(EXCEPTION_PATTERN, proposalName, false) || + CharOperation.match(ERROR_PATTERN, proposalName, false))) { + return R_EXCEPTION; + } + return R_DEFAULT; + } + private int computeRelevanceForExpectingType(TypeBinding proposalType){ + if(expectedTypes != null && proposalType != null) { + for (int i = 0; i < expectedTypes.length; i++) { + if(Scope.areTypesCompatible(proposalType, expectedTypes[i])) { + return R_EXPECTED_TYPE; + } + } + } + return R_DEFAULT; + } + private int computeRelevanceForExpectingType(char[] packageName, char[] typeName){ + if(expectedTypes != null) { + for (int i = 0; i < expectedTypes.length; i++) { + if(CharOperation.equals(expectedTypes[i].qualifiedPackageName(), packageName) && + CharOperation.equals(expectedTypes[i].qualifiedSourceName(), typeName)) { + return R_EXPECTED_TYPE; + } + } + } + return R_DEFAULT; + } + + // Helper method for findMethods(char[], MethodBinding[], Scope, ObjectVector, boolean, boolean, boolean, TypeBinding) + private void findLocalMethodDeclarations( + char[] methodName, + MethodBinding[] methods, + Scope scope, + ObjectVector methodsFound, + // boolean noVoidReturnType, how do you know? + boolean onlyStaticMethods, + boolean exactMatch, + ReferenceBinding receiverType) { + + // Inherited methods which are hidden by subclasses are filtered out + // No visibility checks can be performed without the scope & invocationSite + int methodLength = methodName.length; + next : for (int f = methods.length; --f >= 0;) { + + MethodBinding method = methods[f]; + if (method.isSynthetic()) continue next; + + if (method.isDefaultAbstract()) continue next; + + if (method.isConstructor()) continue next; + + if (method.isFinal()) continue next; + + // if (noVoidReturnType && method.returnType == BaseTypes.VoidBinding) continue next; + if (onlyStaticMethods && !method.isStatic()) continue next; + + if (options.checkVisibility + && !method.canBeSeenBy(receiverType, FakeInvocationSite , scope)) continue next; + + if (exactMatch) { + if (!CharOperation.equals(methodName, method.selector, false /* ignore case */ + )) + continue next; + + } else { + + if (methodLength > method.selector.length) + continue next; + + if (!CharOperation.prefixEquals(methodName, method.selector, false + /* ignore case */ + )) + continue next; + } + + for (int i = methodsFound.size; --i >= 0;) { + MethodBinding otherMethod = (MethodBinding) methodsFound.elementAt(i); + if (method == otherMethod) + continue next; + + if (CharOperation.equals(method.selector, otherMethod.selector, true) + && method.areParametersEqual(otherMethod)) { + continue next; + } + } + + methodsFound.add(method); + + int length = method.parameters.length; + char[][] parameterPackageNames = new char[length][]; + char[][] parameterTypeNames = new char[length][]; + + for (int i = 0; i < length; i++) { + TypeBinding type = method.parameters[i]; + parameterPackageNames[i] = type.qualifiedPackageName(); + parameterTypeNames[i] = type.qualifiedSourceName(); + } + + char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames); + + StringBuffer completion = new StringBuffer(10); + // flush uninteresting modifiers + int insertedModifiers = method.modifiers & ~(CompilerModifiers.AccNative | CompilerModifiers.AccAbstract); + + if (!exactMatch) { + if(insertedModifiers != CompilerModifiers.AccDefault){ + completion.append(AstNode.modifiersString(insertedModifiers)); + } + char[] returnPackageName = method.returnType.qualifiedPackageName(); + char[] returnTypeName = method.returnType.qualifiedSourceName(); + if(mustQualifyType(returnPackageName, returnTypeName)) { + completion.append(CharOperation.concat(returnPackageName, returnTypeName,'.')); + } else { + completion.append(method.returnType.sourceName()); + } + completion.append(' '); + completion.append(method.selector); + completion.append('('); + + for(int i = 0; i < length ; i++){ + if(mustQualifyType(parameterPackageNames[i], parameterTypeNames[i])){ + completion.append(CharOperation.concat(parameterPackageNames[i], parameterTypeNames[i], '.')); + } else { + completion.append(parameterTypeNames[i]); + } + completion.append(' '); + if(parameterNames != null){ + completion.append(parameterNames[i]); + } else { + completion.append('%'); + } + if(i != (length - 1)) + completion.append(','); + } + completion.append(')'); + + ReferenceBinding[] exceptions = method.thrownExceptions; + + if (exceptions != null && exceptions.length > 0){ + completion.append(' '); + completion.append(THROWS); + completion.append(' '); + for(int i = 0; i < exceptions.length ; i++){ + ReferenceBinding exception = exceptions[i]; + + char[] exceptionPackageName = exception.qualifiedPackageName(); + char[] exceptionTypeName = exception.qualifiedSourceName(); + + if(i != 0){ + completion.append(','); + completion.append(' '); + } + + if(mustQualifyType(exceptionPackageName, exceptionTypeName)){ + completion.append(CharOperation.concat(exceptionPackageName, exceptionTypeName, '.')); + } else { + completion.append(exception.sourceName()); + } + } + } + } + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(methodName, method.selector); + + requestor.acceptMethodDeclaration( + method.declaringClass.qualifiedPackageName(), + method.declaringClass.qualifiedSourceName(), + method.selector, + parameterPackageNames, + parameterTypeNames, + parameterNames, + method.returnType.qualifiedPackageName(), + method.returnType.qualifiedSourceName(), + completion.toString().toCharArray(), + method.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + } + private void findMethods( + char[] selector, + TypeBinding[] argTypes, + ReferenceBinding receiverType, + Scope scope, + ObjectVector methodsFound, + boolean onlyStaticMethods, + boolean exactMatch, + boolean isCompletingDeclaration, + InvocationSite invocationSite, + Scope invocationScope, + boolean implicitCall) { + if (selector == null) + return; + + if(isCompletingDeclaration) { + MethodBinding[] methods = receiverType.availableMethods(); + if (methods != null){ + for (int i = 0; i < methods.length; i++) { + if(!methods[i].isDefaultAbstract()) { + methodsFound.add(methods[i]); + } + } + } + } + + ReferenceBinding currentType = receiverType; + if (receiverType.isInterface()) { + if(isCompletingDeclaration) { + findIntefacesMethods( + selector, + argTypes, + receiverType, + currentType.superInterfaces(), + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + isCompletingDeclaration, + invocationSite, + invocationScope, + implicitCall); + } else { + findIntefacesMethods( + selector, + argTypes, + receiverType, + new ReferenceBinding[]{currentType}, + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + isCompletingDeclaration, + invocationSite, + invocationScope, + implicitCall); + } + + currentType = scope.getJavaLangObject(); + } else { + if(isCompletingDeclaration){ + findIntefacesMethods( + selector, + argTypes, + receiverType, + currentType.superInterfaces(), + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + isCompletingDeclaration, + invocationSite, + invocationScope, + implicitCall); + + currentType = receiverType.superclass(); + } + } + boolean hasPotentialDefaultAbstractMethods = true; + while (currentType != null) { + + MethodBinding[] methods = currentType.availableMethods(); + if(methods != null) { + if(isCompletingDeclaration){ + findLocalMethodDeclarations( + selector, + methods, + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + receiverType); + } else{ + findLocalMethods( + selector, + argTypes, + methods, + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + receiverType, + invocationSite, + invocationScope, + implicitCall); + } + } + + if(hasPotentialDefaultAbstractMethods && currentType.isAbstract()){ + findIntefacesMethods( + selector, + argTypes, + receiverType, + currentType.superInterfaces(), + scope, + methodsFound, + onlyStaticMethods, + exactMatch, + isCompletingDeclaration, + invocationSite, + invocationScope, + implicitCall); + } else { + hasPotentialDefaultAbstractMethods = false; + } + currentType = currentType.superclass(); + } + } + private char[][] findMethodParameterNames(MethodBinding method, char[][] parameterTypeNames){ + ReferenceBinding bindingType = method.declaringClass; + + char[][] parameterNames = null; + + int length = parameterTypeNames.length; + + if (length == 0){ + return TypeConstants.NoCharChar; + } + // look into the corresponding unit if it is available + if (bindingType instanceof SourceTypeBinding){ + SourceTypeBinding sourceType = (SourceTypeBinding) bindingType; + + if (sourceType.scope != null){ + TypeDeclaration parsedType; + + if ((parsedType = sourceType.scope.referenceContext) != null){ + AbstractMethodDeclaration methodDecl = parsedType.declarationOf(method); + + if (methodDecl != null){ + Argument[] arguments = methodDecl.arguments; + parameterNames = new char[length][]; + + for(int i = 0 ; i < length ; i++){ + parameterNames[i] = arguments[i].name; + } + } + } + } + } + // look into the model + if(parameterNames == null){ + NameEnvironmentAnswer answer = nameEnvironment.findType(bindingType.compoundName); + + if(answer != null){ + if(answer.isSourceType()) { + ISourceType sourceType = answer.getSourceTypes()[0]; + ISourceMethod[] sourceMethods = sourceType.getMethods(); + int len = sourceMethods == null ? 0 : sourceMethods.length; + for(int i = 0; i < len ; i++){ + ISourceMethod sourceMethod = sourceMethods[i]; + char[][] argTypeNames = sourceMethod.getArgumentTypeNames(); + + if(argTypeNames != null && + CharOperation.equals(method.selector,sourceMethod.getSelector()) && + CharOperation.equals(argTypeNames,parameterTypeNames)){ + parameterNames = sourceMethod.getArgumentNames(); + break; + } + } + } + } + } + return parameterNames; + } + + private void findNestedTypes( + char[] typeName, + SourceTypeBinding currentType, + Scope scope) { + if (typeName == null) + return; + + int typeLength = typeName.length; + + while (scope != null) { // done when a COMPILATION_UNIT_SCOPE is found + + switch (scope.kind) { + + case Scope.METHOD_SCOPE : + case Scope.BLOCK_SCOPE : + BlockScope blockScope = (BlockScope) scope; + + next : for (int i = 0, length = blockScope.scopeIndex; i < length; i++) { + + if (blockScope.subscopes[i] instanceof ClassScope) { + SourceTypeBinding localType = + ((ClassScope) blockScope.subscopes[i]).referenceContext.binding; + + if (!localType.isAnonymousType()) { + if (typeLength > localType.sourceName.length) + continue next; + if (!CharOperation.prefixEquals(typeName, localType.sourceName, false + /* ignore case */ + )) + continue next; + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(typeName, localType.sourceName); + relevance += computeRelevanceForExpectingType(localType); + relevance += computeRelevanceForClass(); + + requestor.acceptClass( + localType.qualifiedPackageName(), + localType.sourceName, + localType.sourceName, + localType.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + } + } + break; + + case Scope.CLASS_SCOPE : + findMemberTypes(typeName, scope.enclosingSourceType(), scope, currentType); + if (typeLength == 0) + return; // do not search outside the class scope if no prefix was provided + break; + + case Scope.COMPILATION_UNIT_SCOPE : + return; + } + scope = scope.parent; + } + } + + private void findPackages(CompletionOnPackageReference packageStatement) { + + token = CharOperation.concatWith(packageStatement.tokens, '.'); + if (token.length == 0) + return; + + setSourceRange(packageStatement.sourceStart, packageStatement.sourceEnd); + nameEnvironment.findPackages(CharOperation.toLowerCase(token), this); + } + + private void findTypesAndPackages(char[] token, Scope scope) { + + if (token == null) + return; + + if (scope.enclosingSourceType() != null) + findNestedTypes(token, scope.enclosingSourceType(), scope); + + if (unitScope != null) { + int typeLength = token.length; + SourceTypeBinding[] types = unitScope.topLevelTypes; + + for (int i = 0, length = types.length; i < length; i++) { + SourceTypeBinding sourceType = types[i]; + + if (typeLength > sourceType.sourceName.length) continue; + + if (!CharOperation.prefixEquals(token, sourceType.sourceName, false)) continue; + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token, sourceType.sourceName); + relevance += computeRelevanceForExpectingType(sourceType); + + if (sourceType.isClass()){ + relevance += computeRelevanceForClass(); + requestor.acceptClass( + sourceType.qualifiedPackageName(), + sourceType.sourceName(), + sourceType.sourceName(), + sourceType.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } else { + relevance += computeRelevanceForInterface(); + requestor.acceptInterface( + sourceType.qualifiedPackageName(), + sourceType.sourceName(), + sourceType.sourceName(), + sourceType.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + } + } + + if (token.length == 0) + return; + + findKeywords(token, baseTypes, scope); + nameEnvironment.findTypes(token, this); + nameEnvironment.findPackages(token, this); + } + + private void findTypesAndSubpackages( + char[] token, + PackageBinding packageBinding) { + + char[] qualifiedName = + CharOperation.concatWith(packageBinding.compoundName, token, '.'); + + if (token == null || token.length == 0) { + int length = qualifiedName.length; + System.arraycopy( + qualifiedName, + 0, + qualifiedName = new char[length + 1], + 0, + length); + qualifiedName[length] = '.'; + } + nameEnvironment.findTypes(qualifiedName, this); + nameEnvironment.findPackages(qualifiedName, this); + } + + private void findVariablesAndMethods( + char[] token, + Scope scope, + InvocationSite invocationSite, + Scope invocationScope) { + + if (token == null) + return; + + // Should local variables hide fields from the receiver type or any of its enclosing types? + // we know its an implicit field/method access... see BlockScope getBinding/getImplicitMethod + + boolean staticsOnly = false; + // need to know if we're in a static context (or inside a constructor) + int tokenLength = token.length; + + ObjectVector localsFound = new ObjectVector(); + ObjectVector fieldsFound = new ObjectVector(); + ObjectVector methodsFound = new ObjectVector(); + + Scope currentScope = scope; + + done1 : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + + switch (currentScope.kind) { + + case Scope.METHOD_SCOPE : + // handle the error case inside an explicit constructor call (see MethodScope>>findField) + MethodScope methodScope = (MethodScope) currentScope; + staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; + + case Scope.BLOCK_SCOPE : + BlockScope blockScope = (BlockScope) currentScope; + + next : for (int i = 0, length = blockScope.locals.length; i < length; i++) { + LocalVariableBinding local = blockScope.locals[i]; + + if (local == null) + break next; + + if (tokenLength > local.name.length) + continue next; + + if (!CharOperation.prefixEquals(token, local.name, false /* ignore case */ + )) + continue next; + + if (local.isSecret()) + continue next; + + for (int f = 0; f < localsFound.size; f++) { + LocalVariableBinding otherLocal = + (LocalVariableBinding) localsFound.elementAt(f); + if (CharOperation.equals(otherLocal.name, local.name, true)) + continue next; + } + localsFound.add(local); + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token, local.name); + relevance += computeRelevanceForExpectingType(local.type); + + requestor.acceptLocalVariable( + local.name, + local.type == null + ? NoChar + : local.type.qualifiedPackageName(), + local.type == null + ? local.declaration.type.toString().toCharArray() + : local.type.qualifiedSourceName(), + local.modifiers, + startPosition - offset, + endPosition - offset, + relevance); + } + break; + + case Scope.COMPILATION_UNIT_SCOPE : + break done1; + } + currentScope = currentScope.parent; + } + + currentScope = scope; + + done2 : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + + switch (currentScope.kind) { + + case Scope.CLASS_SCOPE : + ClassScope classScope = (ClassScope) currentScope; + SourceTypeBinding enclosingType = classScope.referenceContext.binding; + /* if (tokenLength == 0) { // only search inside the type itself if no prefix was provided + findFields(token, enclosingType.fields(), classScope, fieldsFound, staticsOnly); + findMethods(token, enclosingType.methods(), classScope, methodsFound, staticsOnly, false); + break done; + } else { */ + findFields( + token, + enclosingType, + classScope, + fieldsFound, + localsFound, + staticsOnly, + invocationSite, + invocationScope, + true); + + findMethods( + token, + null, + enclosingType, + classScope, + methodsFound, + staticsOnly, + false, + false, + invocationSite, + invocationScope, + true); + staticsOnly |= enclosingType.isStatic(); + // } + break; + + case Scope.COMPILATION_UNIT_SCOPE : + break done2; + } + currentScope = currentScope.parent; + } + } + + // Helper method for private void findVariableNames(char[] name, TypeReference type ) + private void findVariableName(char[] token, char[] qualifiedPackageName, char[] qualifiedSourceName, char[] sourceName, char[][] excludeNames, int dim){ + if(sourceName == null || sourceName.length == 0) + return; + + char[] name = null; + + // compute variable name for base type + try{ + nameScanner.setSource(sourceName); + nameScanner.getNextToken(); // switch (nameScanner.getNextToken()) { +// case TokenNameint : +// case TokenNamebyte : +// case TokenNameshort : +// case TokenNamechar : +// case TokenNamelong : +// case TokenNamefloat : +// case TokenNamedouble : +// case TokenNameboolean : +// if(token != null && token.length != 0) +// return; +// name = computeBaseNames(sourceName[0], excludeNames); +// break; +// } + if(name != null) { + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token, name); + + // accept result + requestor.acceptVariableName( + qualifiedPackageName, + qualifiedSourceName, + name, + name, + startPosition - offset, + endPosition - offset, + relevance); + return; + } + } catch(InvalidInputException e){ + } + + // compute variable name for non base type + char[][] names = computeNames(sourceName, dim > 0); + char[] displayName; + if (dim > 0){ + int l = qualifiedSourceName.length; + displayName = new char[l+(2*dim)]; + System.arraycopy(qualifiedSourceName, 0, displayName, 0, l); + for(int i = 0; i < dim; i++){ + displayName[l+(i*2)] = '['; + displayName[l+(i*2)+1] = ']'; + } + } else { + displayName = qualifiedSourceName; + } + next : for(int i = 0 ; i < names.length ; i++){ + name = names[i]; + + if (!CharOperation.prefixEquals(token, name, false)) + continue next; + + // completion must be an identifier (not a keyword, ...). + try{ + nameScanner.setSource(name); + if(nameScanner.getNextToken() != TokenNameIdentifier) + continue next; + } catch(InvalidInputException e){ + continue next; + } + + int count = 2; + char[] originalName = name; + for(int j = 0 ; j < excludeNames.length ; j++){ + if(CharOperation.equals(name, excludeNames[j], false)) { + name = CharOperation.concat(originalName, String.valueOf(count++).toCharArray()); + j = 0; + } + } + + int relevance = R_DEFAULT; + relevance += computeRelevanceForCaseMatching(token, name); + + // accept result + requestor.acceptVariableName( + qualifiedPackageName, + displayName, + name, + name, + startPosition - offset, + endPosition - offset, + relevance); + } + } + + private void findVariableNames(char[] name, TypeReference type , char[][] excludeNames){ + + if(type != null && + type.binding != null && + type.binding.problemId() == Binding.NoError){ + TypeBinding tb = type.binding; + findVariableName( + name, + tb.leafComponentType().qualifiedPackageName(), + tb.leafComponentType().qualifiedSourceName(), + tb.leafComponentType().sourceName(), + excludeNames, + type.dimensions()); + }/* else { + char[][] typeName = type.getTypeName(); + findVariableName( + name, + NoChar, + CharOperation.concatWith(typeName, '.'), + typeName[typeName.length - 1], + excludeNames, + type.dimensions()); + }*/ + } + + public AssistParser getParser() { + + return parser; + } + + protected void reset() { + + super.reset(); + this.knownPkgs = new HashtableOfObject(10); + this.knownTypes = new HashtableOfObject(10); + } + + private void setSourceRange(int start, int end) { + + this.startPosition = start; + this.endPosition = end + 1; + } + + private char[] computeBaseNames(char firstName, char[][] excludeNames){ + char[] name = new char[]{firstName}; + + for(int i = 0 ; i < excludeNames.length ; i++){ + if(CharOperation.equals(name, excludeNames[i], false)) { + name[0]++; + if(name[0] > 'z') + name[0] = 'a'; + if(name[0] == firstName) + return null; + i = 0; + } + } + + return name; + } + private void computeExpectedTypes(AstNode parent, Scope scope){ + int expectedTypeCount = 0; + expectedTypes = new TypeBinding[1]; + + if(parent instanceof AbstractVariableDeclaration) { + TypeBinding binding = ((AbstractVariableDeclaration)parent).type.binding; + if(binding != null) { + expectedTypes[expectedTypeCount++] = binding; + } + } else if(parent instanceof Assignment) { + TypeBinding binding = ((Assignment)parent).lhsType; + if(binding != null) { + expectedTypes[expectedTypeCount++] = binding; + } + } else if(parent instanceof ReturnStatement) { + MethodBinding methodBinding = ((AbstractMethodDeclaration) scope.methodScope().referenceContext).binding; + TypeBinding binding = methodBinding == null ? null : methodBinding.returnType; + if(binding != null) { + expectedTypes[expectedTypeCount++] = binding; + } + } + + System.arraycopy(expectedTypes, 0, expectedTypes = new TypeBinding[expectedTypeCount], 0, expectedTypeCount); + } + private char[][] computeNames(char[] sourceName, boolean forArray){ + char[][] names = new char[5][]; + int nameCount = 0; + boolean previousIsUpperCase = false; + for(int i = sourceName.length - 1 ; i >= 0 ; i--){ + boolean isUpperCase = Character.isUpperCase(sourceName[i]); + if(isUpperCase && !previousIsUpperCase){ + char[] name = CharOperation.subarray(sourceName,i,sourceName.length); + if(name.length > 1){ + if(nameCount == names.length) { + System.arraycopy(names, 0, names = new char[nameCount * 2][], 0, nameCount); + } + name[0] = Character.toLowerCase(name[0]); + + if(forArray) { + int length = name.length; + if (name[length-1] == 's'){ + System.arraycopy(name, 0, name = new char[length + 2], 0, length); + name[length] = 'e'; + name[length+1] = 's'; + } else { + System.arraycopy(name, 0, name = new char[length + 1], 0, length); + name[length] = 's'; + } + } + names[nameCount++] = name; + } + } + previousIsUpperCase = isUpperCase; + } + if(nameCount == 0){ + char[] name = CharOperation.toLowerCase(sourceName); + if(forArray) { + int length = name.length; + if (name[length-1] == 's'){ + System.arraycopy(name, 0, name = new char[length + 2], 0, length); + name[length] = 'e'; + name[length+1] = 's'; + } else { + System.arraycopy(name, 0, name = new char[length + 1], 0, length); + name[length] = 's'; + } + } + names[nameCount++] = name; + + } + System.arraycopy(names, 0, names = new char[nameCount][], 0, nameCount); + return names; + } + + private char[] computePrefix(SourceTypeBinding declarationType, SourceTypeBinding invocationType, boolean isStatic){ + + StringBuffer completion = new StringBuffer(10); + + if (isStatic) { + completion.append(declarationType.sourceName()); + + } else if (declarationType == invocationType) { + completion.append(THIS); + + } else { + + if (!declarationType.isNestedType()) { + + completion.append(declarationType.sourceName()); + completion.append('.'); + completion.append(THIS); + + } else if (!declarationType.isAnonymousType()) { + + completion.append(declarationType.sourceName()); + completion.append('.'); + completion.append(THIS); + + } + } + + return completion.toString().toCharArray(); + } + + private boolean isEnclosed(ReferenceBinding possibleEnclosingType, ReferenceBinding type){ + if(type.isNestedType()){ + ReferenceBinding enclosing = type.enclosingType(); + while(enclosing != null ){ + if(possibleEnclosingType == enclosing) + return true; + enclosing = enclosing.enclosingType(); + } + } + return false; + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java new file mode 100644 index 0000000..a7ddb3a --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist; + +/** + * This is the internal requestor passed to the searchable name environment + * so as to process the multiple search results as they are discovered. + * + * It is used to allow the code assist engine to add some more information + * to the raw name environment results before answering them to the UI. + */ +public interface ISearchRequestor { + + /** + * One result of the search consists of a new class. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + public void acceptClass(char[] packageName, char[] typeName, int modifiers); + + /** + * One result of the search consists of a new interface. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.I". + * The default package is represented by an empty array. + */ + public void acceptInterface(char[] packageName, char[] typeName, int modifiers); + + /** + * One result of the search consists of a new package. + * + * NOTE - All package names are presented in their readable form: + * Package names are in the form "a.b.c". + * The default package is represented by an empty array. + */ + public void acceptPackage(char[] packageName); + + /** + * One result of the search consists of a new type. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + public void acceptType(char[] packageName, char[] typeName); +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java new file mode 100644 index 0000000..3bd46bf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist; + +import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment; + +/** + * This interface defines the API that may be used to implement any + * search-based tool (such as a CodeAssist, a Finder, ...). + * It is mainly used to hide from the search tool the implementation + * of the underlying environment and its constructions. + */ +public interface ISearchableNameEnvironment extends INameEnvironment { + + /** + * Find the packages that start with the given prefix. + * A valid prefix is a qualified name separated by periods + * (ex. java.util). + * The packages found are passed to: + * ISearchRequestor.acceptPackage(char[][] packageName) + */ + void findPackages(char[] prefix, ISearchRequestor requestor); + + /** + * Find the top-level types (classes and interfaces) that are defined + * in the current environment and whose name starts with the + * given prefix. The prefix is a qualified name separated by periods + * or a simple name (ex. java.util.V or V). + * + * The types found are passed to one of the following methods (if additional + * information is known about the types): + * ISearchRequestor.acceptType(char[][] packageName, char[] typeName) + * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers) + * ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers) + * + * This method can not be used to find member types... member + * types are found relative to their enclosing type. + */ + void findTypes(char[] prefix, ISearchRequestor requestor); +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISelectionRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISelectionRequestor.java new file mode 100644 index 0000000..b8384a5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISelectionRequestor.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist; + +import net.sourceforge.phpdt.core.compiler.IProblem; + +/** + * A selection requestor accepts results from the selection engine. + */ +public interface ISelectionRequestor { + /** + * Code assist notification of a class selection. + * @param packageName char[] + * Declaring package name of the class. + * + * @param className char[] + * Name of the class. + * + * @param needQualification boolean + * Flag indicating if the type name + * must be qualified by its package name (depending on imports). + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + void acceptClass( + char[] packageName, + char[] className, + boolean needQualification); + + /** + * Code assist notification of a compilation error detected during selection. + * @param error net.sourceforge.phpdt.internal.compiler.IProblem + * Only problems which are categorized as errors are notified to the requestor, + * warnings are silently ignored. + * In case an error got signaled, no other completions might be available, + * therefore the problem message should be presented to the user. + * The source positions of the problem are related to the source where it was + * detected (might be in another compilation unit, if it was indirectly requested + * during the code assist process). + * Note: the problem knows its originating file name. + */ + void acceptError(IProblem error); + + /** + * Code assist notification of a field selection. + * @param declaringTypePackageName char[] + * Name of the package in which the type that contains this field is declared. + * + * @param declaringTypeName char[] + * Name of the type declaring this new field. + * + * @param name char[] + * Name of the field. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + void acceptField( + char[] declaringTypePackageName, + char[] declaringTypeName, + char[] name); + + /** + * Code assist notification of an interface selection. + * @param packageName char[] + * Declaring package name of the interface. + * + * @param interfaceName char[] + * Name of the interface. + * + * @param needQualification boolean + * Flag indicating if the type name + * must be qualified by its package name (depending on imports). + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.I". + * The default package is represented by an empty array. + */ + void acceptInterface( + char[] packageName, + char[] interfaceName, + boolean needQualification); + + /** + * Code assist notification of a method selection. + * @param declaringTypePackageName char[] + * Name of the package in which the type that contains this new method is declared. + * + * @param declaringTypeName char[] + * Name of the type declaring this new method. + * + * @param selector char[] + * Name of the new method. + * + * @param parameterPackageNames char[][] + * Names of the packages in which the parameter types are declared. + * Should contain as many elements as parameterTypeNames. + * + * @param parameterTypeNames char[][] + * Names of the parameters types. + * Should contain as many elements as parameterPackageNames. + * + * @param isConstructor boolean + * Answer if the method is a constructor. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Base types are in the form "int" or "boolean". + * Array types are in the qualified form "M[]" or "int[]". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + void acceptMethod( + char[] declaringTypePackageName, + char[] declaringTypeName, + char[] selector, + char[][] parameterPackageNames, + char[][] parameterTypeNames, + boolean isConstructor); + + /** + * Code assist notification of a package selection. + * @param packageName char[] + * The package name. + * + * NOTE - All package names are presented in their readable form: + * Package names are in the form "a.b.c". + * The default package is represented by an empty array. + */ + void acceptPackage(char[] packageName); +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/RelevanceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/RelevanceConstants.java new file mode 100644 index 0000000..1c00a85 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/RelevanceConstants.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist; + +public interface RelevanceConstants { + + int R_DEFAULT = 0; + int R_CASE = 10; + int R_EXPECTED_TYPE = 20; + int R_INTERFACE = 20; + int R_CLASS = 20; + int R_EXCEPTION = 20; +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/SelectionEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/SelectionEngine.java new file mode 100644 index 0000000..6f5e306 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/SelectionEngine.java @@ -0,0 +1,739 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist; + +import java.util.*; + +import net.sourceforge.phpdt.core.compiler.*; +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.core.compiler.IProblem; +import net.sourceforge.phpdt.internal.codeassist.impl.*; +import net.sourceforge.phpdt.internal.codeassist.select.*; +import net.sourceforge.phpdt.internal.compiler.*; +import net.sourceforge.phpdt.internal.compiler.env.*; +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; +import net.sourceforge.phpdt.internal.compiler.parser.*; +import net.sourceforge.phpdt.internal.compiler.problem.*; +import net.sourceforge.phpdt.internal.compiler.util.*; +import net.sourceforge.phpdt.internal.compiler.impl.*; + +/** + * The selection engine is intended to infer the nature of a selected name in some + * source code. This name can be qualified. + * + * Selection is resolving context using a name environment (no need to search), assuming + * the source where selection occurred is correct and will not perform any completion + * attempt. If this was the desired behavior, a call to the CompletionEngine should be + * performed instead. + */ +public final class SelectionEngine extends Engine implements ISearchRequestor { + + public static boolean DEBUG = false; + + SelectionParser parser; + ISelectionRequestor requestor; + + boolean acceptedAnswer; + + private int actualSelectionStart; + private int actualSelectionEnd; + private char[] qualifiedSelection; + private char[] selectedIdentifier; + + private char[][][] acceptedClasses; + private char[][][] acceptedInterfaces; + int acceptedClassesCount; + int acceptedInterfacesCount; + + /** + * The SelectionEngine is responsible for computing the selected object. + * + * It requires a searchable name environment, which supports some + * specific search APIs, and a requestor to feed back the results to a UI. + * + * @param nameEnvironment net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment + * used to resolve type/package references and search for types/packages + * based on partial names. + * + * @param requestor net.sourceforge.phpdt.internal.codeassist.ISelectionRequestor + * since the engine might produce answers of various forms, the engine + * is associated with a requestor able to accept all possible completions. + * + * @param settings java.util.Map + * set of options used to configure the code assist engine. + */ + public SelectionEngine( + ISearchableNameEnvironment nameEnvironment, + ISelectionRequestor requestor, + Map settings) { + + super(settings); + + this.requestor = requestor; + this.nameEnvironment = nameEnvironment; + + ProblemReporter problemReporter = + new ProblemReporter( + DefaultErrorHandlingPolicies.proceedWithAllProblems(), + this.compilerOptions, + new DefaultProblemFactory(Locale.getDefault())) { + public void record(IProblem problem, CompilationResult unitResult, ReferenceContext referenceContext) { + unitResult.record(problem, referenceContext); + SelectionEngine.this.requestor.acceptError(problem); + } + }; + this.parser = new SelectionParser(problemReporter, this.compilerOptions.assertMode); + this.lookupEnvironment = + new LookupEnvironment(this, this.compilerOptions, problemReporter, nameEnvironment); + } + + /** + * One result of the search consists of a new class. + * @param packageName char[] + * @param className char[] + * @param modifiers int + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + public void acceptClass(char[] packageName, char[] className, int modifiers) { + if (CharOperation.equals(className, selectedIdentifier)) { + if (qualifiedSelection != null + && !CharOperation.equals( + qualifiedSelection, + CharOperation.concat(packageName, className, '.'))) { + return; + } + + if(mustQualifyType(packageName, className)) { + char[][] acceptedClass = new char[2][]; + acceptedClass[0] = packageName; + acceptedClass[1] = className; + + if(acceptedClasses == null) { + acceptedClasses = new char[10][][]; + acceptedClassesCount = 0; + } + int length = acceptedClasses.length; + if(length == acceptedClassesCount) { + System.arraycopy(acceptedClasses, 0, acceptedClasses = new char[(length + 1)* 2][][], 0, length); + } + acceptedClasses[acceptedClassesCount++] = acceptedClass; + + } else { + requestor.acceptClass( + packageName, + className, + false); + acceptedAnswer = true; + } + } + } + + /** + * One result of the search consists of a new interface. + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.I". + * The default package is represented by an empty array. + */ + public void acceptInterface( + char[] packageName, + char[] interfaceName, + int modifiers) { + + if (CharOperation.equals(interfaceName, selectedIdentifier)) { + if (qualifiedSelection != null + && !CharOperation.equals( + qualifiedSelection, + CharOperation.concat(packageName, interfaceName, '.'))) { + return; + } + + if(mustQualifyType(packageName, interfaceName)) { + char[][] acceptedInterface= new char[2][]; + acceptedInterface[0] = packageName; + acceptedInterface[1] = interfaceName; + + if(acceptedInterfaces == null) { + acceptedInterfaces = new char[10][][]; + acceptedInterfacesCount = 0; + } + int length = acceptedInterfaces.length; + if(length == acceptedInterfacesCount) { + System.arraycopy(acceptedInterfaces, 0, acceptedInterfaces = new char[(length + 1) * 2][][], 0, length); + } + acceptedInterfaces[acceptedInterfacesCount++] = acceptedInterface; + + } else { + requestor.acceptInterface( + packageName, + interfaceName, + false); + acceptedAnswer = true; + } + } + } + + /** + * One result of the search consists of a new package. + * @param packageName char[] + * + * NOTE - All package names are presented in their readable form: + * Package names are in the form "a.b.c". + * The default package is represented by an empty array. + */ + public void acceptPackage(char[] packageName) { + } + + private void acceptQualifiedTypes() { + if(acceptedClasses != null){ + acceptedAnswer = true; + for (int i = 0; i < acceptedClassesCount; i++) { + requestor.acceptClass( + acceptedClasses[i][0], + acceptedClasses[i][1], + true); + } + acceptedClasses = null; + acceptedClassesCount = 0; + } + if(acceptedInterfaces != null){ + acceptedAnswer = true; + for (int i = 0; i < acceptedInterfacesCount; i++) { + requestor.acceptInterface( + acceptedInterfaces[i][0], + acceptedInterfaces[i][1], + true); + } + acceptedInterfaces = null; + acceptedInterfacesCount = 0; + } + } + + /** + * One result of the search consists of a new type. + * @param packageName char[] + * @param typeName char[] + * + * NOTE - All package and type names are presented in their readable form: + * Package names are in the form "a.b.c". + * Nested type names are in the qualified form "A.M". + * The default package is represented by an empty array. + */ + public void acceptType(char[] packageName, char[] typeName) { + acceptClass(packageName, typeName, 0); + } + + private boolean checkSelection( + char[] source, + int selectionStart, + int selectionEnd) { + + Scanner scanner = new Scanner(); + scanner.setSource(source); + + int lastIdentifierStart = -1; + int lastIdentifierEnd = -1; + char[] lastIdentifier = null; + int token, identCount = 0; + StringBuffer entireSelection = new StringBuffer(selectionEnd - selectionStart + 1); + + if(selectionStart > selectionEnd){ + + // compute start position of current line + int currentPosition = selectionStart - 1; + int nextCharacterPosition = selectionStart; + char currentCharacter = ' '; + try { + while(currentPosition > 0 || currentCharacter == '\r' || currentCharacter == '\n'){ + + if(source[currentPosition] == '\\' && source[currentPosition+1] == 'u') { + int pos = currentPosition + 2; + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + while (source[pos] == 'u') { + pos++; + } + if ((c1 = Character.getNumericValue(source[pos++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[pos++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[pos++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[pos++])) > 15 + || c4 < 0) { + return false; + } else { + currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + nextCharacterPosition = pos; + } + } else { + currentCharacter = source[currentPosition]; + nextCharacterPosition = currentPosition+1; + } + + if(currentCharacter == '\r' || currentCharacter == '\n') { + break; + } + currentPosition--; + } + } + catch (ArrayIndexOutOfBoundsException e) { + return false; + } + + // compute start and end of the last token + scanner.resetTo(nextCharacterPosition, selectionEnd); + do { + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return false; + } + if(( + // token == ITerminalSymbols.TokenNamethis || + // token == ITerminalSymbols.TokenNamesuper || + token == ITerminalSymbols.TokenNameIdentifier) && + scanner.startPosition <= selectionStart && + selectionStart <= scanner.currentPosition) { + lastIdentifierStart = scanner.startPosition; + lastIdentifierEnd = scanner.currentPosition - 1; + lastIdentifier = scanner.getCurrentTokenSource(); + } + } while (token != ITerminalSymbols.TokenNameEOF); + } else { + scanner.resetTo(selectionStart, selectionEnd); + + boolean expectingIdentifier = true; + + do { + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return false; + } + switch (token) { +// case ITerminalSymbols.TokenNamethis : +// case ITerminalSymbols.TokenNamesuper : + case ITerminalSymbols.TokenNameIdentifier : + if (!expectingIdentifier) + return false; + lastIdentifier = scanner.getCurrentTokenSource(); + lastIdentifierStart = scanner.startPosition; + lastIdentifierEnd = scanner.currentPosition - 1; + if(lastIdentifierEnd > selectionEnd) { + lastIdentifierEnd = selectionEnd; + lastIdentifier = CharOperation.subarray(lastIdentifier, 0,lastIdentifierEnd - lastIdentifierStart + 1); + } + entireSelection.append(lastIdentifier); + + identCount++; + expectingIdentifier = false; + break; + case ITerminalSymbols.TokenNameDOT : + if (expectingIdentifier) + return false; + entireSelection.append('.'); + expectingIdentifier = true; + break; + case ITerminalSymbols.TokenNameEOF : + if (expectingIdentifier) + return false; + break; + default : + return false; + } + } while (token != ITerminalSymbols.TokenNameEOF); + } + if (lastIdentifierStart > 0) { + actualSelectionStart = lastIdentifierStart; + actualSelectionEnd = lastIdentifierEnd; + selectedIdentifier = lastIdentifier; + if (identCount > 1) + qualifiedSelection = entireSelection.toString().toCharArray(); + return true; + } + return false; + } + + public AssistParser getParser() { + return parser; + } + + /** + * Ask the engine to compute the selection at the specified position + * of the given compilation unit. + + * @param sourceUnit net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit + * the source of the current compilation unit. + * + * @param selectionSourceStart int + * @param selectionSourceEnd int + * a range in the source where the selection is. + */ + public void select( + ICompilationUnit sourceUnit, + int selectionSourceStart, + int selectionSourceEnd) { + + char[] source = sourceUnit.getContents(); + + if(DEBUG) { + System.out.print("SELECTION IN "); //$NON-NLS-1$ + System.out.print(sourceUnit.getFileName()); + System.out.print(" FROM "); //$NON-NLS-1$ + System.out.print(selectionSourceStart); + System.out.print(" TO "); //$NON-NLS-1$ + System.out.println(selectionSourceEnd); + System.out.println("SELECTION - Source :"); //$NON-NLS-1$ + System.out.println(source); + } + if (!checkSelection(source, selectionSourceStart, selectionSourceEnd)) + return; + try { + acceptedAnswer = false; + CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = + parser.dietParse(sourceUnit, result, actualSelectionStart, actualSelectionEnd); + + if (parsedUnit != null) { + if(DEBUG) { + System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$ + System.out.println(parsedUnit.toString()); + } + + // scan the package & import statements first + if (parsedUnit.currentPackage instanceof SelectionOnPackageReference) { + char[][] tokens = + ((SelectionOnPackageReference) parsedUnit.currentPackage).tokens; + requestor.acceptPackage(CharOperation.concatWith(tokens, '.')); + return; + } + ImportReference[] imports = parsedUnit.imports; + if (imports != null) { + for (int i = 0, length = imports.length; i < length; i++) { + ImportReference importReference = imports[i]; + if (importReference instanceof SelectionOnImportReference) { + char[][] tokens = ((SelectionOnImportReference) importReference).tokens; + requestor.acceptPackage(CharOperation.concatWith(tokens, '.')); + nameEnvironment.findTypes(CharOperation.concatWith(tokens, '.'), this); + // accept qualified types only if no unqualified type was accepted + if(!acceptedAnswer) { + acceptQualifiedTypes(); + if (!acceptedAnswer) { + nameEnvironment.findTypes(selectedIdentifier, this); + // try with simple type name + if(!acceptedAnswer) { + acceptQualifiedTypes(); + } + } + } + return; + } + } + } + if (parsedUnit.types != null) { + lookupEnvironment.buildTypeBindings(parsedUnit); + if ((this.unitScope = parsedUnit.scope) != null) { + try { + lookupEnvironment.completeTypeBindings(parsedUnit, true); + parsedUnit.scope.faultInTypes(); + selectDeclaration(parsedUnit); + parseMethod(parsedUnit, selectionSourceStart); + if(DEBUG) { + System.out.println("SELECTION - AST :"); //$NON-NLS-1$ + System.out.println(parsedUnit.toString()); + } + parsedUnit.resolve(); + } catch (SelectionNodeFound e) { + if (e.binding != null) { + if(DEBUG) { + System.out.println("SELECTION - Selection binding:"); //$NON-NLS-1$ + System.out.println(e.binding.toString()); + } + // if null then we found a problem in the selection node + selectFrom(e.binding); + } + } + } + } + } + // only reaches here if no selection could be derived from the parsed tree + // thus use the selected source and perform a textual type search + if (!acceptedAnswer) { + nameEnvironment.findTypes(selectedIdentifier, this); + + // accept qualified types only if no unqualified type was accepted + if(!acceptedAnswer) { + acceptQualifiedTypes(); + } + } + } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D + } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object + } finally { + reset(); + } + } + + private void selectFrom(Binding binding) { + if (binding instanceof ReferenceBinding) { + ReferenceBinding typeBinding = (ReferenceBinding) binding; + if (qualifiedSelection != null + && !CharOperation.equals(qualifiedSelection, typeBinding.readableName())) { + return; + } + if (typeBinding.isInterface()) { + requestor.acceptInterface( + typeBinding.qualifiedPackageName(), + typeBinding.qualifiedSourceName(), + false); + } else if(typeBinding instanceof ProblemReferenceBinding){ + ProblemReferenceBinding problemBinding = (ProblemReferenceBinding)typeBinding; + if(problemBinding.original == null + || !(problemBinding.original instanceof ReferenceBinding)) { + return; + } + ReferenceBinding original = (ReferenceBinding) problemBinding.original; + + requestor.acceptClass( + original.qualifiedPackageName(), + original.qualifiedSourceName(), + false); + } else { + requestor.acceptClass( + typeBinding.qualifiedPackageName(), + typeBinding.qualifiedSourceName(), + false); + } + acceptedAnswer = true; + } else + if (binding instanceof MethodBinding) { + MethodBinding methodBinding = (MethodBinding) binding; + TypeBinding[] parameterTypes = methodBinding.parameters; + int length = parameterTypes.length; + char[][] parameterPackageNames = new char[length][]; + char[][] parameterTypeNames = new char[length][]; + for (int i = 0; i < length; i++) { + parameterPackageNames[i] = parameterTypes[i].qualifiedPackageName(); + parameterTypeNames[i] = parameterTypes[i].qualifiedSourceName(); + } + requestor.acceptMethod( + methodBinding.declaringClass.qualifiedPackageName(), + methodBinding.declaringClass.qualifiedSourceName(), + methodBinding.isConstructor() + ? methodBinding.declaringClass.sourceName() + : methodBinding.selector, + parameterPackageNames, + parameterTypeNames, + methodBinding.isConstructor()); + acceptedAnswer = true; + } else + if (binding instanceof FieldBinding) { + FieldBinding fieldBinding = (FieldBinding) binding; + if (fieldBinding.declaringClass != null) { // arraylength + requestor.acceptField( + fieldBinding.declaringClass.qualifiedPackageName(), + fieldBinding.declaringClass.qualifiedSourceName(), + fieldBinding.name); + acceptedAnswer = true; + } + } else + if (binding instanceof LocalVariableBinding) { + selectFrom(((LocalVariableBinding) binding).type); + // open on the type of the variable + } else + if (binding instanceof ArrayBinding) { + selectFrom(((ArrayBinding) binding).leafComponentType); + // open on the type of the array + } else + if (binding instanceof PackageBinding) { + PackageBinding packageBinding = (PackageBinding) binding; + requestor.acceptPackage(packageBinding.readableName()); + acceptedAnswer = true; + } else + if(binding instanceof BaseTypeBinding) { + acceptedAnswer = true; + } + } + + /** + * Asks the engine to compute the selection of the given type + * from the source type. + * + * @param sourceType net.sourceforge.phpdt.internal.compiler.env.ISourceType + * a source form of the current type in which code assist is invoked. + * + * @param typeName char[] + * a type name which is to be resolved in the context of a compilation unit. + * NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left) + * + * @param searchInEnvironment + * if true and no selection could be found in context then search type in environment. + */ + public void selectType(ISourceType sourceType, char[] typeName, boolean searchInEnvironment) { + try { + acceptedAnswer = false; + + // find the outer most type + ISourceType outerType = sourceType; + ISourceType parent = sourceType.getEnclosingType(); + while (parent != null) { + outerType = parent; + parent = parent.getEnclosingType(); + } + // compute parse tree for this most outer type + CompilationResult result = new CompilationResult(outerType.getFileName(), 1, 1, this.compilerOptions.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = + SourceTypeConverter + .buildCompilationUnit( + new ISourceType[] { outerType }, + false, + // don't need field and methods + true, // by default get member types + this.parser.problemReporter(), result); + + if (parsedUnit != null && parsedUnit.types != null) { + if(DEBUG) { + System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$ + System.out.println(parsedUnit.toString()); + } + // find the type declaration that corresponds to the original source type + char[] packageName = sourceType.getPackageName(); + char[] sourceTypeName = sourceType.getQualifiedName(); + // the fully qualified name without the package name + if (packageName != null) { + // remove the package name if necessary + sourceTypeName = + CharOperation.subarray( + sourceType.getQualifiedName(), + packageName.length + 1, + sourceTypeName.length); + }; + TypeDeclaration typeDecl = + parsedUnit.declarationOfType(CharOperation.splitOn('.', sourceTypeName)); + if (typeDecl != null) { + + // add fake field with the type we're looking for + // note: since we didn't ask for fields above, there is no field defined yet + FieldDeclaration field = new FieldDeclaration(); + int dot; + if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) { + this.selectedIdentifier = typeName; + field.type = new SelectionOnSingleTypeReference(typeName, -1); + // position not used + } else { + qualifiedSelection = typeName; + char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot - 1); + char[] selectionIdentifier = + CharOperation.subarray(typeName, dot + 1, typeName.length); + this.selectedIdentifier = selectionIdentifier; + field.type = + new SelectionOnQualifiedTypeReference( + previousIdentifiers, + selectionIdentifier, + new long[previousIdentifiers.length + 1]); + } + field.name = "".toCharArray(); //$NON-NLS-1$ + typeDecl.fields = new FieldDeclaration[] { field }; + + // build bindings + lookupEnvironment.buildTypeBindings(parsedUnit); + if ((this.unitScope = parsedUnit.scope) != null) { + try { + // build fields + // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along) + this.lookupEnvironment.completeTypeBindings(parsedUnit, true); + + // resolve + parsedUnit.scope.faultInTypes(); + parsedUnit.resolve(); + } catch (SelectionNodeFound e) { + if (e.binding != null) { + if(DEBUG) { + System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$ + System.out.println(e.binding.toString()); + } + // if null then we found a problem in the selection node + selectFrom(e.binding); + } + } + } + } + } + // only reaches here if no selection could be derived from the parsed tree + // thus use the selected source and perform a textual type search + if (!acceptedAnswer && searchInEnvironment) { + if (this.selectedIdentifier != null) { + nameEnvironment.findTypes(typeName, this); + + // accept qualified types only if no unqualified type was accepted + if(!acceptedAnswer) { + acceptQualifiedTypes(); + } + } + } + } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object + } finally { + qualifiedSelection = null; + reset(); + } + } + + // Check if a declaration got selected in this unit + private void selectDeclaration(CompilationUnitDeclaration compilationUnit){ + + // the selected identifier is not identical to the parser one (equals but not identical), + // for traversing the parse tree, the parser assist identifier is necessary for identitiy checks + char[] assistIdentifier = this.getParser().assistIdentifier(); + if (assistIdentifier == null) return; + + // iterate over the types + TypeDeclaration[] types = compilationUnit.types; + for (int i = 0, length = types == null ? 0 : types.length; i < length; i++){ + selectDeclaration(types[i], assistIdentifier); + } + } + + // Check if a declaration got selected in this type + private void selectDeclaration(TypeDeclaration typeDeclaration, char[] assistIdentifier){ + + if (typeDeclaration.name == assistIdentifier){ + throw new SelectionNodeFound(typeDeclaration.binding); + } + TypeDeclaration[] memberTypes = typeDeclaration.memberTypes; + for (int i = 0, length = memberTypes == null ? 0 : memberTypes.length; i < length; i++){ + selectDeclaration(memberTypes[i], assistIdentifier); + } + FieldDeclaration[] fields = typeDeclaration.fields; + for (int i = 0, length = fields == null ? 0 : fields.length; i < length; i++){ + if (fields[i].name == assistIdentifier){ + throw new SelectionNodeFound(fields[i].binding); + } + } + AbstractMethodDeclaration[] methods = typeDeclaration.methods; + for (int i = 0, length = methods == null ? 0 : methods.length; i < length; i++){ + AbstractMethodDeclaration method = methods[i]; + if (method.selector == assistIdentifier){ + if(method.binding != null) { + throw new SelectionNodeFound(method.binding); + } else { + if(method.scope != null) { + throw new SelectionNodeFound(new MethodBinding(method.modifiers, method.selector, null, null, null, method.scope.referenceType().binding)); + } + } + } + } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionNodeFound.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionNodeFound.java new file mode 100644 index 0000000..41e45e5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionNodeFound.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +import net.sourceforge.phpdt.internal.compiler.ast.AstNode; +import net.sourceforge.phpdt.internal.compiler.lookup.Binding; +import net.sourceforge.phpdt.internal.compiler.lookup.Scope; + +public class CompletionNodeFound extends RuntimeException { + public AstNode astNode; + public Binding qualifiedBinding; + public Scope scope; +public CompletionNodeFound() { + this(null, null, null); // we found a problem in the completion node +} +public CompletionNodeFound(AstNode astNode, Binding qualifiedBinding, Scope scope) { + this.astNode = astNode; + this.qualifiedBinding = qualifiedBinding; + this.scope = scope; +} +public CompletionNodeFound(AstNode astNode, Scope scope) { + this(astNode, null, scope); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnArgumentName.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnArgumentName.java new file mode 100644 index 0000000..50bb859 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnArgumentName.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +import net.sourceforge.phpdt.internal.compiler.ast.Argument; +import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + + +public class CompletionOnArgumentName extends Argument { + private static final char[] FAKENAMESUFFIX = " ".toCharArray(); //$NON-NLS-1$ + public char[] realName; + public CompletionOnArgumentName(char[] name , long posNom , TypeReference tr , int modifiers){ + super(CharOperation.concat(name, FAKENAMESUFFIX), posNom, tr, modifiers); + this.realName = name; + } + + public void resolve(BlockScope scope) { + super.resolve(scope); + throw new CompletionNodeFound(this, scope); + } + + public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { + super.bind(scope, typeBinding, used); + + throw new CompletionNodeFound(this, scope); + } + + public String toString(int tab) { + String s = tabString(tab); + s += " class X { + * void foo() { + * + * } + * } + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnClassLiteralAccess extends ClassLiteralAccess { + public char[] completionIdentifier; + public int classStart; + +public CompletionOnClassLiteralAccess(long pos, TypeReference t) { + super((int)pos, t); + this.classStart = (int) (pos >>> 32); +} +public TypeBinding resolveType(BlockScope scope) { + if (super.resolveType(scope) == null) + throw new CompletionNodeFound(); + else + throw new CompletionNodeFound(this, targetType, scope); +} +public String toStringExpression() { + StringBuffer result = new StringBuffer(""); //$NON-NLS-1$ + return result.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnClassReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnClassReference.java new file mode 100644 index 0000000..f22f53c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnClassReference.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +public class CompletionOnClassReference extends CompletionOnSingleTypeReference { + public CompletionOnClassReference(char[] source, long pos) { + super(source, pos); + } + public String toStringExpression(int tab) { + return ""; //$NON-NLS-2$ //$NON-NLS-1$ + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExceptionReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExceptionReference.java new file mode 100644 index 0000000..f3f723e --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExceptionReference.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce an exception type reference containing the completion identifier. + * e.g. + * + * class X { + * void foo() { + * try { + * bar(); + * } catch (IOExc[cursor] e) { + * } + * } + * } + * + * ---> class X { + * void foo() { + * try { + * bar(); + * } catch ( e) { + * } + * } + * } + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ +public class CompletionOnExceptionReference extends CompletionOnSingleTypeReference { +public CompletionOnExceptionReference(char[] source, long pos) { + super(source, pos); +} +public String toStringExpression(int tab) { + return ""; //$NON-NLS-2$ //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java new file mode 100644 index 0000000..50d998e --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce a explicit constructor call containing the cursor. + * e.g. + * + * class X { + * X() { + * this(1, 2, [cursor] + * } + * } + * + * ---> class X { + * X() { + * + * } + * } + * + * The source range is always of length 0. + * The arguments of the constructor call are all the arguments defined + * before the cursor. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnExplicitConstructorCall extends ExplicitConstructorCall { +public CompletionOnExplicitConstructorCall(int accessMode) { + super(accessMode); +} +public void resolve(BlockScope scope) { + ReferenceBinding receiverType = scope.enclosingSourceType(); + + if (accessMode != This && receiverType != null) { + if (receiverType.isHierarchyInconsistent()) + throw new CompletionNodeFound(); + receiverType = receiverType.superclass(); + } + if (receiverType == null) + throw new CompletionNodeFound(); + else + throw new CompletionNodeFound(this, receiverType, scope); +} +public String toString(int tab) { + String s = tabString(tab); + s += " class X { + * ; + * } + * + * The source range is always of length 0. + * The arguments of the allocation expression are all the arguments defined + * before the cursor. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnFieldType extends FieldDeclaration { + public boolean isLocalVariable; + +public CompletionOnFieldType(TypeReference type, boolean isLocalVariable){ + super(); + this.sourceStart = type.sourceStart; + this.sourceEnd = type.sourceEnd; + this.type = type; + this.name = NoChar; + this.isLocalVariable = isLocalVariable; +} +public TypeBinding getTypeBinding(Scope scope) { + if(type instanceof CompletionOnSingleTypeReference) + throw new CompletionNodeFound(this, scope); + else // handle the qualified type ref directly + return type.getTypeBinding(scope); +} +public String toString(int tab) { + + return type.toString(tab); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnImportReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnImportReference.java new file mode 100644 index 0000000..8aff63e --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnImportReference.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce an import reference containing the cursor location. + * e.g. + * + * import java.io[cursor]; + * class X { + * void foo() { + * } + * } + * + * ---> + * class X { + * void foo() { + * } + * } + * + * The source range is always of length 0. + * The arguments of the allocation expression are all the arguments defined + * before the cursor. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; + +public class CompletionOnImportReference extends ImportReference { + +public CompletionOnImportReference(char[][] tokens , long[] positions) { + super(tokens, positions, false); +} +public String toString(int tab, boolean withOnDemand) { + + StringBuffer buffer = new StringBuffer(tabString(tab)); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnInterfaceReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnInterfaceReference.java new file mode 100644 index 0000000..a52fdf7 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnInterfaceReference.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +public class CompletionOnInterfaceReference extends CompletionOnSingleTypeReference { + public CompletionOnInterfaceReference(char[] source, long pos) { + super(source, pos); + } + public String toStringExpression(int tab) { + return ""; //$NON-NLS-2$ //$NON-NLS-1$ + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnLocalName.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnLocalName.java new file mode 100644 index 0000000..8d4feb5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnLocalName.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +import net.sourceforge.phpdt.internal.compiler.ast.Expression; +import net.sourceforge.phpdt.internal.compiler.ast.LocalDeclaration; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + + +public class CompletionOnLocalName extends LocalDeclaration { + private static final char[] FAKENAMESUFFIX = " ".toCharArray(); //$NON-NLS-1$ + public char[] realName; + public CompletionOnLocalName(Expression expr,char[] name, int sourceStart, int sourceEnd){ + super(expr, CharOperation.concat(name, FAKENAMESUFFIX), sourceStart, sourceEnd); + this.realName = name; + } + + public void resolve(BlockScope scope) { + super.resolve(scope); + + throw new CompletionNodeFound(this, scope); + } + public String toString(int tab) { + String s = tabString(tab); + s += " class X { + * void foo() { + * + * } + * } + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnMemberAccess extends FieldReference { + + public CompletionOnMemberAccess(char[] source, long pos) { + super(source, pos); + } + + public TypeBinding resolveType(BlockScope scope) { + TypeBinding receiverType = receiver.resolveType(scope); + if (receiverType == null || receiverType.isBaseType()) + throw new CompletionNodeFound(); + else + throw new CompletionNodeFound(this, receiverType, scope); + // array types are passed along to find the length field + } + + public String toStringExpression() { + + return ""; //$NON-NLS-1$ + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMessageSend.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMessageSend.java new file mode 100644 index 0000000..0882c74 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMessageSend.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce a message send containing the cursor. + * e.g. + * + * class X { + * void foo() { + * this.bar(1, 2, [cursor] + * } + * } + * + * ---> class X { + * void foo() { + * + * } + * } + * + * The source range is always of length 0. + * The arguments of the message send are all the arguments defined + * before the cursor. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnMessageSend extends MessageSend { + + public TypeBinding resolveType(BlockScope scope) { + if (receiver == ThisReference.ThisImplicit) + throw new CompletionNodeFound(this, null, scope); + + TypeBinding receiverType = receiver.resolveType(scope); + if (receiverType == null || receiverType.isBaseType()) + throw new CompletionNodeFound(); + + if (receiverType.isArrayType()) + receiverType = scope.getJavaLangObject(); + throw new CompletionNodeFound(this, receiverType, scope); + } + + public String toStringExpression() { + + String s = ""; //$NON-NLS-1$ + return s; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMethodName.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMethodName.java new file mode 100644 index 0000000..9679be1 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnMethodName.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +import net.sourceforge.phpdt.internal.compiler.CompilationResult; +import net.sourceforge.phpdt.internal.compiler.ast.MethodDeclaration; +import net.sourceforge.phpdt.internal.compiler.lookup.ClassScope; + +public class CompletionOnMethodName extends MethodDeclaration { + public int selectorEnd; + + public CompletionOnMethodName(CompilationResult compilationResult){ + super(compilationResult); + } + + public void resolve(ClassScope upperScope) { + + super.resolve(upperScope); + throw new CompletionNodeFound(this, upperScope); + } + + public String toString(int tab) { + + String s = tabString(tab); + s += " + * class X { + * void foo() { + * } + * } + * + * The source range is always of length 0. + * The arguments of the allocation expression are all the arguments defined + * before the cursor. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; + +public class CompletionOnPackageReference extends ImportReference { +public CompletionOnPackageReference(char[][] tokens , long[] positions) { + super(tokens, positions, true); +} +public String toString(int tab, boolean withOnDemand) { + StringBuffer buffer = new StringBuffer(tabString(tab)); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java new file mode 100644 index 0000000..6aec572 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedAllocationExpression.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce an allocation expression containing the cursor. + * If the allocation expression is not qualified, the enclosingInstance field + * is null. + * e.g. + * + * class X { + * void foo() { + * new Bar(1, 2, [cursor] + * } + * } + * + * ---> class X { + * void foo() { + * + * } + * } + * + * The source range is always of length 0. + * The arguments of the allocation expression are all the arguments defined + * before the cursor. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnQualifiedAllocationExpression extends QualifiedAllocationExpression { +public TypeBinding resolveType(BlockScope scope) { + TypeBinding typeBinding = null; + if (enclosingInstance != null) { + TypeBinding enclosingType = enclosingInstance.resolveType(scope); + if (!(enclosingType instanceof ReferenceBinding)) { + scope.problemReporter().illegalPrimitiveOrArrayTypeForEnclosingInstance(enclosingType, enclosingInstance); + throw new CompletionNodeFound(); + } + typeBinding = ((SingleTypeReference) type).resolveTypeEnclosing(scope, (ReferenceBinding) enclosingType); + if (!(typeBinding instanceof ReferenceBinding)) + throw new CompletionNodeFound(); // no need to continue if its an array or base type + if (typeBinding.isInterface()) // handle the anonymous class definition case + typeBinding = scope.getJavaLangObject(); + } else { + typeBinding = type.resolveType(scope); + if (!(typeBinding instanceof ReferenceBinding)) + throw new CompletionNodeFound(); // no need to continue if its an array or base type + } + + throw new CompletionNodeFound(this, typeBinding, scope); +} +public String toStringExpression(int tab) { + return + ((this.enclosingInstance == null) ? + ""; //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedClassReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedClassReference.java new file mode 100644 index 0000000..7d28391 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedClassReference.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +public class CompletionOnQualifiedClassReference extends CompletionOnQualifiedTypeReference { +public CompletionOnQualifiedClassReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) { + super(previousIdentifiers, completionIdentifier, positions); +} +public String toStringExpression(int tab) { + + StringBuffer buffer = new StringBuffer(); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedExceptionReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedExceptionReference.java new file mode 100644 index 0000000..f788b6e --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedExceptionReference.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce an exception type reference containing the completion identifier + * as part of a qualified name. + * e.g. + * + * class X { + * void foo() { + * try { + * bar(); + * } catch (java.io.IOExc[cursor] e) { + * } + * } + * } + * + * ---> class X { + * void foo() { + * try { + * bar(); + * } catch ( e) { + * } + * } + * } + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ +public class CompletionOnQualifiedExceptionReference extends CompletionOnQualifiedTypeReference { +public CompletionOnQualifiedExceptionReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) { + super(previousIdentifiers, completionIdentifier, positions); +} +public String toStringExpression(int tab) { + + StringBuffer buffer = new StringBuffer(); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedInterfaceReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedInterfaceReference.java new file mode 100644 index 0000000..aca5446 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedInterfaceReference.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +public class CompletionOnQualifiedInterfaceReference extends CompletionOnQualifiedTypeReference { +public CompletionOnQualifiedInterfaceReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) { + super(previousIdentifiers, completionIdentifier, positions); +} +public String toStringExpression(int tab) { + + StringBuffer buffer = new StringBuffer(); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java new file mode 100644 index 0000000..ad0cda8 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedNameReference.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce a qualified name reference containing the completion identifier. + * e.g. + * + * class X { + * Y y; + * void foo() { + * y.fred.ba[cursor] + * } + * } + * + * ---> class X { + * Y y; + * void foo() { + * + * } + * } + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnQualifiedNameReference extends QualifiedNameReference { + public char[] completionIdentifier; + public long[] sourcePositions; // positions of each token, the last one being the positions of the completion identifier +public CompletionOnQualifiedNameReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) { + super(previousIdentifiers, (int) (positions[0] >>> 32), (int) positions[positions.length - 1]); + this.completionIdentifier = completionIdentifier; + this.sourcePositions = positions; +} +public CompletionOnQualifiedNameReference(char[][] previousIdentifiers, char[] completionIdentifier, int sourceStart, int sourceEnd) { + super(previousIdentifiers, sourceStart, sourceEnd); + this.completionIdentifier = completionIdentifier; + this.sourcePositions = new long[] {((long)sourceStart << 32) + sourceEnd}; +} +public TypeBinding resolveType(BlockScope scope) { + // it can be a package, type, member type, local variable or field + binding = scope.getBinding(tokens, this); + if (!binding.isValidBinding()) { + if (binding instanceof ProblemFieldBinding) { + scope.problemReporter().invalidField(this, (FieldBinding) binding); + } else if (binding instanceof ProblemReferenceBinding) { + scope.problemReporter().invalidType(this, (TypeBinding) binding); + } else { + scope.problemReporter().unresolvableReference(this, binding); + } + throw new CompletionNodeFound(); + } + + throw new CompletionNodeFound(this, binding, scope); +} +public String toStringExpression() { + + StringBuffer buffer = new StringBuffer(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java new file mode 100644 index 0000000..a62d389 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnQualifiedTypeReference.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce a type reference containing the completion identifier as part + * of a qualified name. + * e.g. + * + * class X extends java.lang.Obj[cursor] + * + * ---> class X extends + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnQualifiedTypeReference extends QualifiedTypeReference { + public char[] completionIdentifier; +public CompletionOnQualifiedTypeReference(char[][] previousIdentifiers, char[] completionIdentifier, long[] positions) { + super(previousIdentifiers, positions); + this.completionIdentifier = completionIdentifier; +} +public void aboutToResolve(Scope scope) { + getTypeBinding(scope); +} +/* + * No expansion of the completion reference into an array one + */ +public TypeReference copyDims(int dim){ + return this; +} +public TypeBinding getTypeBinding(Scope scope) { + // it can be a package, type or member type + Binding binding = scope.parent.getTypeOrPackage(tokens); // step up from the ClassScope + if (!binding.isValidBinding()) { + scope.problemReporter().invalidType(this, (TypeBinding) binding); + throw new CompletionNodeFound(); + } + + throw new CompletionNodeFound(this, binding, scope); +} +public String toStringExpression(int tab) { + + StringBuffer buffer = new StringBuffer(); + buffer.append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleNameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleNameReference.java new file mode 100644 index 0000000..ed517e9 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleNameReference.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce a single name reference containing the completion identifier. + * e.g. + * + * class X { + * void foo() { + * ba[cursor] + * } + * } + * + * ---> class X { + * void foo() { + * + * } + * } + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnSingleNameReference extends SingleNameReference { +public CompletionOnSingleNameReference(char[] source, long pos) { + super(source, pos); +} +public TypeBinding resolveType(BlockScope scope) { + throw new CompletionNodeFound(this, scope); +} +public String toStringExpression() { + return ""; //$NON-NLS-2$ //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java new file mode 100644 index 0000000..a72d1f5 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionOnSingleTypeReference.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Completion node build by the parser in any case it was intending to + * reduce a type reference containing the completion identifier as a single + * name reference. + * e.g. + * + * class X extends Obj[cursor] + * + * ---> class X extends + * + * The source range of the completion node denotes the source range + * which should be replaced by the completion. + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class CompletionOnSingleTypeReference extends SingleTypeReference { +public boolean isCompletionNode; +public CompletionOnSingleTypeReference(char[] source, long pos) { + super(source, pos); + isCompletionNode = true; +} +public void aboutToResolve(Scope scope) { + getTypeBinding(scope); +} +/* + * No expansion of the completion reference into an array one + */ +public TypeReference copyDims(int dim){ + return this; +} +public TypeBinding getTypeBinding(Scope scope) { + if(isCompletionNode) { + throw new CompletionNodeFound(this, scope); + } else { + return super.getTypeBinding(scope); + } +} +public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { + if(isCompletionNode) { + throw new CompletionNodeFound(this, enclosingType, scope); + } else { + return super.resolveTypeEnclosing(scope, enclosingType); + } +} +public String toStringExpression(int tab){ + + return "" ; //$NON-NLS-2$ //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionParser.java new file mode 100644 index 0000000..228c98c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionParser.java @@ -0,0 +1,1386 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Parser able to build specific completion parse nodes, given a cursorLocation. + * + * Cursor location denotes the position of the last character behind which completion + * got requested: + * -1 means completion at the very beginning of the source + * 0 means completion behind the first character + * n means completion behind the n-th character + */ +import net.sourceforge.phpdt.internal.compiler.*; +import net.sourceforge.phpdt.internal.compiler.env.*; + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.parser.*; +import net.sourceforge.phpdt.internal.compiler.problem.*; +import net.sourceforge.phpdt.internal.codeassist.impl.*; + +public class CompletionParser extends AssistParser { + + /* public fields */ + + public int cursorLocation; + public char[][] labels; // the visible labels up to the cursor location + public AstNode assistNodeParent; // the parent node of assist node + /* the following fields are internal flags */ + + boolean betweenNewAndLeftBraket; // whether we are between the keyword 'new' and the following left braket, ie. '[', '(' or '{' + boolean betweenCatchAndRightParen; // whether we are between the keyword 'catch' and the following ')' + boolean completionBehindDot; // true when completion identifier immediately follows a dot + + boolean nextTypeReferenceIsClass; + boolean nextTypeReferenceIsException; + boolean nextTypeReferenceIsInterface; + + int bracketDepth; + int throwBracketDepth; + + // the stacks of types and qualifiers for invocations (ie. method invocations, allocation expressions and + // explicit constructor invocations). They use the same stack pointer as the selector stack (ie. invocationPtr) + // the invocation type stack contains one of the invocation type constants below + // the qualifier stack contains pointers to the expression stack or -1 if there is no qualifier + // (a qualifier is the expression that qualifies a 'new', a 'super' constructor or a 'this' constructor + // or it is the receiver of a message send) + int[] invocationTypeStack = new int[StackIncrement]; + int[] qualifierStack = new int[StackIncrement]; + + // invocation type constants + static final int EXPLICIT_RECEIVER = 0; + static final int NO_RECEIVER = -1; + static final int SUPER_RECEIVER = -2; + static final int NAME_RECEIVER = -3; + static final int ALLOCATION = -4; + static final int QUALIFIED_ALLOCATION = -5; + + // the type of the current invocation (one of the invocation type constants) + int invocationType; + + // a pointer in the expression stack to the qualifier of a invocation + int qualifier; + + // a stack of label counters + // a new counter is pushed on the stack each time when a method (or a constructor) is entered, + // it is poped when the method (or constructor) is exited, + // it is incremented when a new label is defined + int labelCounterPtr; + int[] labelCounterStack = new int[StackIncrement]; + + // a stack of invocationPtr: contains the first invocationPtr of a block + // the current invocationPtr+1 is pushed when a block is entered + // it is poped when a block is exited + int blockInvocationPtr; + int[] blockInvocationStack = new int[StackIncrement]; + + // last modifiers info + int lastModifiers = AccDefault; + int lastModifiersStart = -1; + +public CompletionParser(ProblemReporter problemReporter, boolean assertMode) { + super(problemReporter, assertMode); +} +public char[] assistIdentifier(){ + return ((CompletionScanner)scanner).completionIdentifier; +} +protected void attachOrphanCompletionNode(){ + if (this.isOrphanCompletionNode) { + AstNode orphan = this.assistNode; + this.isOrphanCompletionNode = false; + + /* if in context of a type, then persists the identifier into a fake field return type */ + if (currentElement instanceof RecoveredType){ + RecoveredType recoveredType = (RecoveredType)currentElement; + /* filter out cases where scanner is still inside type header */ + if (recoveredType.foundOpeningBrace) { + /* generate a pseudo field with a completion on type reference */ + if (orphan instanceof TypeReference){ + CompletionOnFieldType fieldDeclaration = new CompletionOnFieldType((TypeReference)orphan, false); + + // retrieve available modifiers if any + if (intPtr >= 2 && intStack[intPtr-1] == this.lastModifiersStart && intStack[intPtr-2] == this.lastModifiers){ + fieldDeclaration.modifiersSourceStart = intStack[intPtr-1]; + fieldDeclaration.modifiers = intStack[intPtr-2]; + } + + currentElement = currentElement.add(fieldDeclaration, 0); + return; + } + } + } + /* if in context of a method, persists if inside arguments as a type */ + if (currentElement instanceof RecoveredMethod){ + RecoveredMethod recoveredMethod = (RecoveredMethod)currentElement; + /* only consider if inside method header */ + if (!recoveredMethod.foundOpeningBrace) { + //if (rParenPos < lParenPos){ // inside arguments + if (orphan instanceof TypeReference){ + currentElement = currentElement.parent.add( + new CompletionOnFieldType((TypeReference)orphan, true), 0); + return; + } + } + } + + // add the completion node to the method declaration or constructor declaration + if (orphan instanceof Statement) { + /* check for completion at the beginning of method body + behind an invalid signature + */ + RecoveredMethod method = currentElement.enclosingMethod(); + if (method != null){ + AbstractMethodDeclaration methodDecl = method.methodDeclaration; + if ((methodDecl.bodyStart == methodDecl.sourceEnd+1) // was missing opening brace + && (scanner.getLineNumber(orphan.sourceStart) == scanner.getLineNumber(methodDecl.sourceEnd))){ + return; + } + } + // add the completion node as a statement to the list of block statements + currentElement = currentElement.add((Statement)orphan, 0); + return; + } + } + + // the following code applies only in methods, constructors or initializers + if ((!this.inMethodStack[this.inMethodPtr] && !this.inFieldInitializationStack[this.inFieldInitializationPtr])) { + return; + } + + // push top expression on ast stack if it contains the completion node + Expression expression; + if (this.expressionPtr > -1 && containsCompletionNode(expression = this.expressionStack[this.expressionPtr])) { + /* check for completion at the beginning of method body + behind an invalid signature + */ + RecoveredMethod method = currentElement.enclosingMethod(); + if (method != null){ + AbstractMethodDeclaration methodDecl = method.methodDeclaration; + if ((methodDecl.bodyStart == methodDecl.sourceEnd+1) // was missing opening brace + && (scanner.getLineNumber(expression.sourceStart) == scanner.getLineNumber(methodDecl.sourceEnd))){ + return; + } + } + if (expression instanceof AllocationExpression) { + // keep the context if it is an allocation expression + Statement statement = (Statement)wrapWithExplicitConstructorCallIfNeeded(expression); + currentElement = currentElement.add(statement, 0); + } else { + Statement statement = (Statement)wrapWithExplicitConstructorCallIfNeeded(this.assistNode); + currentElement = currentElement.add(statement, 0); + } + } +} +public int bodyEnd(AbstractMethodDeclaration method){ + return cursorLocation; +} +public int bodyEnd(Initializer initializer){ + return cursorLocation; +} +/** + * Checks if the completion is on the exception type of a catch clause. + * Returns whether we found a completion node. + */ +private boolean checkCatchClause() { + if (this.betweenCatchAndRightParen && this.identifierPtr > -1) { + // NB: if the cursor is on the variable, then it has been reduced (so identifierPtr is -1), + // thus this can only be a completion on the type of the catch clause + this.assistNode = getTypeReference(0); + this.lastCheckPoint = this.assistNode.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } + return false; +} +/** + * Checks if the completion is on the type following a 'new'. + * Returns whether we found a completion node. + */ +private boolean checkClassInstanceCreation() { + if (this.betweenNewAndLeftBraket) { + // completion on type inside an allocation expression + + if(this.throwBracketDepth != -1 && this.throwBracketDepth == this.bracketDepth) { + this.nextTypeReferenceIsException = true; + } + TypeReference type = getTypeReference(0); + this.nextTypeReferenceIsException = false; + this.assistNode = type; + this.lastCheckPoint = type.sourceEnd + 1; + if (this.invocationType == ALLOCATION) { + // non qualified allocation expression + AllocationExpression allocExpr = new AllocationExpression(); + allocExpr.type = type; + allocExpr.sourceStart = type.sourceStart; + allocExpr.sourceEnd = type.sourceEnd; + pushOnExpressionStack(allocExpr); + this.isOrphanCompletionNode = false; + } else { + // qualified allocation expression + QualifiedAllocationExpression allocExpr = new QualifiedAllocationExpression(); + allocExpr.type = type; + allocExpr.enclosingInstance = this.expressionStack[this.qualifier]; + allocExpr.sourceStart = this.intStack[this.intPtr--]; + allocExpr.sourceEnd = type.sourceEnd; + this.expressionStack[this.qualifier] = allocExpr; // attach it now (it replaces the qualifier expression) + this.isOrphanCompletionNode = false; + } + return true; + } + return false; +} +/** + * Checks if the completion is on the dot following an array type, + * a primitive type or an primitive array type. + * Returns whether we found a completion node. + */ +private boolean checkClassLiteralAccess() { + if (this.identifierLengthPtr >= 1 && this.previousToken == TokenNameDOT) { // (NB: the top id length is 1 and it is for the completion identifier) + int length; + // if the penultimate id length is negative, + // the completion is after a primitive type or a primitive array type + if ((length = this.identifierLengthStack[this.identifierLengthPtr-1]) < 0) { + // build the primitive type node + int dim = this.isAfterArrayType() ? this.intStack[this.intPtr--] : 0; + SingleTypeReference typeRef = (SingleTypeReference)TypeReference.baseTypeReference(-length, dim); + typeRef.sourceStart = this.intStack[this.intPtr--]; + if (dim == 0) { + typeRef.sourceEnd = this.intStack[this.intPtr--]; + } else { + this.intPtr--; + typeRef.sourceEnd = this.endPosition; + } + //typeRef.sourceEnd = typeRef.sourceStart + typeRef.token.length; // NB: It's ok to use the length of the token since it doesn't contain any unicode + + // find the completion identifier and its source positions + char[] source = identifierStack[identifierPtr]; + long pos = this.identifierPositionStack[this.identifierPtr--]; + this.identifierLengthPtr--; // it can only be a simple identifier (so its length is one) + + // build the completion on class literal access node + CompletionOnClassLiteralAccess access = new CompletionOnClassLiteralAccess(pos, typeRef); + access.completionIdentifier = source; + this.identifierLengthPtr--; // pop the length that was used to say it is a primitive type + this.assistNode = access; + this.isOrphanCompletionNode = true; + return true; + } + + // if the completion is after a regular array type + if (isAfterArrayType()) { + // find the completion identifier and its source positions + char[] source = identifierStack[identifierPtr]; + long pos = this.identifierPositionStack[this.identifierPtr--]; + this.identifierLengthPtr--; // it can only be a simple identifier (so its length is one) + + // get the type reference + TypeReference typeRef = getTypeReference(this.intPtr--); + + // build the completion on class literal access node + CompletionOnClassLiteralAccess access = new CompletionOnClassLiteralAccess(pos, typeRef); + access.completionIdentifier = source; + this.assistNode = access; + this.isOrphanCompletionNode = true; + return true; + } + + } + return false; +} +/** + * Checks if the completion is inside a method invocation or a constructor invocation. + * Returns whether we found a completion node. + */ +private boolean checkInvocation() { + Expression topExpression = this.expressionPtr >= 0 ? + this.expressionStack[this.expressionPtr] : + null; + boolean isEmptyNameCompletion = false; + boolean isEmptyAssistIdentifier = false; + int startInvocationPtr = this.blockInvocationPtr >= 0 ? this.blockInvocationStack[this.blockInvocationPtr] : 0; + if (this.invocationPtr >= startInvocationPtr + && ((isEmptyNameCompletion = topExpression == this.assistNode && this.isEmptyNameCompletion()) // eg. it is something like "this.fred([cursor]" but it is not something like "this.fred(1 + [cursor]" + || (isEmptyAssistIdentifier = this.indexOfAssistIdentifier() >= 0 && this.identifierStack[this.identifierPtr].length == 0))) { // eg. it is something like "this.fred(1 [cursor]" + + // pop empty name completion + if (isEmptyNameCompletion) { + this.expressionPtr--; + this.expressionLengthStack[this.expressionLengthPtr]--; + } else if (isEmptyAssistIdentifier) { + this.identifierPtr--; + this.identifierLengthPtr--; + } + + // find receiver and qualifier + int invocationType = this.invocationTypeStack[this.invocationPtr]; + int qualifierExprPtr = this.qualifierStack[this.invocationPtr]; + + // find arguments + int numArgs = this.expressionPtr - qualifierExprPtr; + int argStart = qualifierExprPtr + 1; + Expression[] arguments = null; + if (numArgs > 0) { + // remember the arguments + arguments = new Expression[numArgs]; + System.arraycopy(this.expressionStack, argStart, arguments, 0, numArgs); + + // consume the expression arguments + this.expressionPtr -= numArgs; + int count = numArgs; + while (count > 0) { + count -= this.expressionLengthStack[this.expressionLengthPtr--]; + } + } + + // build ast node + if (invocationType != ALLOCATION && invocationType != QUALIFIED_ALLOCATION) { + // creates completion on message send + CompletionOnMessageSend messageSend = new CompletionOnMessageSend(); + messageSend.arguments = arguments; + switch (invocationType) { + case NO_RECEIVER: + // implicit this + messageSend.receiver = ThisReference.ThisImplicit; + break; + case NAME_RECEIVER: + // remove special flags for primitive types + while (this.identifierLengthPtr >= 0 && this.identifierLengthStack[this.identifierLengthPtr] < 0) { + this.identifierLengthPtr--; + } + + // remove selector + this.identifierPtr--; + this.identifierLengthStack[this.identifierLengthPtr]--; + // consume the receiver + messageSend.receiver = this.getUnspecifiedReference(); + break; + case SUPER_RECEIVER: + messageSend.receiver = SuperReference.Super; + break; + case EXPLICIT_RECEIVER: + messageSend.receiver = this.expressionStack[qualifierExprPtr]; + } + + // set selector + int selectorPtr = this.selectorStack[this.invocationPtr]; + messageSend.selector = this.identifierStack[selectorPtr]; + // remove selector + if (this.identifierLengthPtr >=0 && this.identifierLengthStack[this.identifierLengthPtr] == 1) { + this.identifierPtr--; + this.identifierLengthPtr--; + } + + // the entire message may be replaced in case qualification is needed + messageSend.sourceStart = (int)(this.identifierPositionStack[selectorPtr] >> 32); //this.cursorLocation + 1; + messageSend.sourceEnd = this.cursorLocation; + + // remember the message send as an orphan completion node + this.assistNode = messageSend; + this.lastCheckPoint = messageSend.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } else { + int selectorPtr = this.selectorStack[this.invocationPtr]; + if (selectorPtr == THIS_CONSTRUCTOR || selectorPtr == SUPER_CONSTRUCTOR) { + // creates an explicit constructor call + CompletionOnExplicitConstructorCall call = new CompletionOnExplicitConstructorCall( + (selectorPtr == THIS_CONSTRUCTOR) ? ExplicitConstructorCall.This : ExplicitConstructorCall.Super); + call.arguments = arguments; + if (invocationType == QUALIFIED_ALLOCATION) { + call.qualification = this.expressionStack[qualifierExprPtr]; + } + + // no source is going to be replaced + call.sourceStart = this.cursorLocation + 1; + call.sourceEnd = this.cursorLocation; + + // remember the explicit constructor call as an orphan completion node + this.assistNode = call; + this.lastCheckPoint = call.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } else { + // creates an allocation expression + CompletionOnQualifiedAllocationExpression allocExpr = new CompletionOnQualifiedAllocationExpression(); + allocExpr.arguments = arguments; + allocExpr.type = super.getTypeReference(0); // we don't want a completion node here, so call super + if (invocationType == QUALIFIED_ALLOCATION) { + allocExpr.enclosingInstance = this.expressionStack[qualifierExprPtr]; + } + // no source is going to be replaced + allocExpr.sourceStart = this.cursorLocation + 1; + allocExpr.sourceEnd = this.cursorLocation; + + // remember the allocation expression as an orphan completion node + this.assistNode = allocExpr; + this.lastCheckPoint = allocExpr.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } + } + } + return false; +} +/** + * Checks if the completion is on a member access (ie. in an identifier following a dot). + * Returns whether we found a completion node. + */ +private boolean checkMemberAccess() { + if (this.previousToken == TokenNameDOT && this.qualifier > -1 && this.expressionPtr == this.qualifier) { + // the receiver is an expression + pushCompletionOnMemberAccessOnExpressionStack(false); + return true; + } + return false; +} +/** + * Checks if the completion is on a name reference. + * Returns whether we found a completion node. + */ +private boolean checkNameCompletion() { + /* + We didn't find any other completion, but the completion identifier is on the identifier stack, + so it can only be a completion on name. + Note that we allow the completion on a name even if nothing is expected (eg. foo() b[cursor] would + be a completion on 'b'). This policy gives more to the user than he/she would expect, but this + simplifies the problem. To fix this, the recovery must be changed to work at a 'statement' granularity + instead of at the 'expression' granularity as it does right now. + */ + + // NB: at this point the completion identifier is on the identifier stack + this.assistNode = getUnspecifiedReferenceOptimized(); + this.lastCheckPoint = this.assistNode.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; +} +/** + * Checks if the completion is in the context of a method and on the type of one of its arguments + * Returns whether we found a completion node. + */ +private boolean checkRecoveredMethod() { + if (currentElement instanceof RecoveredMethod){ + /* check if current awaiting identifier is the completion identifier */ + if (this.indexOfAssistIdentifier() < 0) return false; + + /* check if on line with an error already - to avoid completing inside + illegal type names e.g. int[ */ + if (lastErrorEndPosition <= cursorLocation+1 + && scanner.getLineNumber(lastErrorEndPosition) + == scanner.getLineNumber(((CompletionScanner)scanner).completedIdentifierStart)){ + return false; + } + RecoveredMethod recoveredMethod = (RecoveredMethod)currentElement; + /* only consider if inside method header */ + if (!recoveredMethod.foundOpeningBrace + && lastIgnoredToken == -1) { + //if (rParenPos < lParenPos){ // inside arguments + this.assistNode = this.getTypeReference(0); + this.lastCheckPoint = this.assistNode.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } + } + return false; +} +/** + * Checks if the completion is in the context of a type and on a type reference in this type. + * Persists the identifier into a fake field return type + * Returns whether we found a completion node. + */ +private boolean checkRecoveredType() { + if (currentElement instanceof RecoveredType){ + /* check if current awaiting identifier is the completion identifier */ + if (this.indexOfAssistIdentifier() < 0) return false; + + /* check if on line with an error already - to avoid completing inside + illegal type names e.g. int[ */ + if ((lastErrorEndPosition <= cursorLocation+1) + && scanner.getLineNumber(lastErrorEndPosition) + == scanner.getLineNumber(((CompletionScanner)scanner).completedIdentifierStart)){ + return false; + } + RecoveredType recoveredType = (RecoveredType)currentElement; + /* filter out cases where scanner is still inside type header */ + if (recoveredType.foundOpeningBrace) { + this.assistNode = this.getTypeReference(0); + this.lastCheckPoint = this.assistNode.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } + } + return false; +} +/* + * Check whether about to shift beyond the completion token. + * If so, depending on the context, a special node might need to be created + * and attached to the existing recovered structure so as to be remember in the + * resulting parsed structure. + */ +public void completionIdentifierCheck(){ + + if (checkRecoveredType()) return; + if (checkRecoveredMethod()) return; + + // if not in a method in non diet mode and if not inside a field initializer, only record references attached to types + if (!(this.inMethodStack[this.inMethodPtr] && !this.diet) + && !insideFieldInitialization()) return; + + /* + In some cases, the completion identifier may not have yet been consumed, + e.g. int.[cursor] + This is because the grammar does not allow any (empty) identifier to follow + a base type. We thus have to manually force the identifier to be consumed + (i.e. pushed). + */ + if (assistIdentifier() == null && this.currentToken == TokenNameIdentifier) { // Test below copied from CompletionScanner.getCurrentIdentifierSource() + if (cursorLocation < this.scanner.startPosition && this.scanner.currentPosition == this.scanner.startPosition){ // fake empty identifier got issued + this.pushIdentifier(); + } else if (cursorLocation+1 >= this.scanner.startPosition && cursorLocation < this.scanner.currentPosition){ + this.pushIdentifier(); + } + } + + // check for different scenarii + try { + // no need to go further if we found a non empty completion node + // (we still need to store labels though) + if (this.assistNode != null) { + // however inside an invocation, the completion identifier may already have been consumed into an empty name + // completion, so this check should be before we check that we are at the cursor location + if (!isEmptyNameCompletion() || checkInvocation()) return; + } + + // no need to check further if we are not at the cursor location + if (this.indexOfAssistIdentifier() < 0) return; + + if (checkClassInstanceCreation()) return; + if (checkCatchClause()) return; + if (checkMemberAccess()) return; + if (checkClassLiteralAccess()) return; + + // if the completion was not on an empty name, it can still be inside an invocation (eg. this.fred("abc"[cursor]) + // (NB: Put this check before checkNameCompletion() because the selector of the invocation can be on the identifier stack) + if (checkInvocation()) return; + + if (checkNameCompletion()) return; + } finally { + storeLabelsIfNeeded(); + } +} +protected void consumeCaseLabel() { + Expression caseExpression = this.expressionStack[this.expressionPtr]; + if (caseExpression instanceof SingleNameReference || caseExpression instanceof QualifiedNameReference) { + // label counter was wrongly incremented in consumeToken + if (this.labelCounterPtr >= 0) this.labelCounterStack[this.labelCounterPtr]--; + } + super.consumeCaseLabel(); +} +protected void consumeClassHeaderExtends() { + this.nextTypeReferenceIsClass = true; + super.consumeClassHeaderExtends(); + this.nextTypeReferenceIsClass = false; +} +protected void consumeClassTypeElt() { + this.nextTypeReferenceIsException = true; + super.consumeClassTypeElt(); + this.nextTypeReferenceIsException = false; +} +protected void consumeConditionalExpression(int op) { + Expression valueIfTrue = this.expressionStack[this.expressionPtr - 1]; + if (valueIfTrue instanceof SingleNameReference || valueIfTrue instanceof QualifiedNameReference) { + // label counter was wrongly incremented in consumeToken + if (this.labelCounterPtr >= 0) this.labelCounterStack[this.labelCounterPtr]--; + } + super.consumeConditionalExpression(op); +} +protected void consumeConstructorBody() { + super.consumeConstructorBody(); + this.labelCounterPtr--; + if (this.blockInvocationPtr >= 0) this.blockInvocationPtr--; +} +protected void consumeConstructorHeader() { + super.consumeConstructorHeader(); + pushBlockInvocationPtr(); +} +protected void consumeConstructorHeaderName() { + + /* no need to take action if not inside assist identifiers */ + if (indexOfAssistIdentifier() < 0) { + super.consumeConstructorHeaderName(); + return; + } + + /* force to start recovering in order to get fake field behavior */ + if (currentElement == null){ + this.hasReportedError = true; // do not report any error + } + this.restartRecovery = true; +} +protected void consumeEnterVariable() { + identifierPtr--; + identifierLengthPtr--; + + boolean isLocalDeclaration = nestedMethod[nestedType] != 0; + int variableIndex = variablesCounter[nestedType]; + int extendedDimension = intStack[intPtr + 1]; + + if(isLocalDeclaration || indexOfAssistIdentifier() < 0 || variableIndex != 0 || extendedDimension != 0) { + identifierPtr++; + identifierLengthPtr++; + super.consumeEnterVariable(); + } else { + restartRecovery = true; + + // recovery + if (currentElement != null) { + int nameSourceStart = (int)(identifierPositionStack[identifierPtr] >>> 32); + intPtr--; + + TypeReference type = getTypeReference(intStack[intPtr--]); + intPtr--; + + if (!(currentElement instanceof RecoveredType) + && (currentToken == TokenNameDOT + || (scanner.getLineNumber(type.sourceStart) + != scanner.getLineNumber(nameSourceStart)))){ + lastCheckPoint = nameSourceStart; + restartRecovery = true; + return; + } + + FieldDeclaration completionFieldDecl = new CompletionOnFieldType(type, false); + completionFieldDecl.modifiers = intStack[intPtr--]; + assistNode = completionFieldDecl; + lastCheckPoint = type.sourceEnd + 1; + currentElement = currentElement.add(completionFieldDecl, 0); + lastIgnoredToken = -1; + } + } +} +protected void consumeExitVariableWithInitialization() { + super.consumeExitVariableWithInitialization(); + + // does not keep the initialization if completion is not inside + AbstractVariableDeclaration variable = (AbstractVariableDeclaration) astStack[astPtr]; + if (cursorLocation + 1 < variable.initialization.sourceStart || + cursorLocation > variable.initialization.sourceEnd) { + variable.initialization = null; + } +} + +/* + * Copy of code from superclass with the following change: + * If the cursor location is on the field access, then create a + * CompletionOnMemberAccess instead. + */ +protected void consumeFieldAccess(boolean isSuperAccess) { + // FieldAccess ::= Primary '.' 'Identifier' + // FieldAccess ::= 'super' '.' 'Identifier' + + // potential receiver is being poped, so reset potential receiver + this.invocationType = NO_RECEIVER; + + if (this.indexOfAssistIdentifier() < 0) { + super.consumeFieldAccess(isSuperAccess); + } else { + this.pushCompletionOnMemberAccessOnExpressionStack(isSuperAccess); + } +} + +protected void consumeFormalParameter() { + if (this.indexOfAssistIdentifier() < 0) { + super.consumeFormalParameter(); + } else { + + identifierLengthPtr--; + char[] name = identifierStack[identifierPtr]; + long namePositions = identifierPositionStack[identifierPtr--]; + TypeReference type = getTypeReference(intStack[intPtr--] + intStack[intPtr--]); + intPtr -= 2; + Argument arg = + new CompletionOnArgumentName( + name, + namePositions, + type, + intStack[intPtr + 1] & ~AccDeprecated); // modifiers + pushOnAstStack(arg); + + assistNode = arg; + this.lastCheckPoint = (int) namePositions; + isOrphanCompletionNode = true; + + /* if incomplete method header, listLength counter will not have been reset, + indicating that some arguments are available on the stack */ + listLength++; + } +} +protected void consumeInterfaceType() { + this.nextTypeReferenceIsInterface = true; + super.consumeInterfaceType(); + this.nextTypeReferenceIsInterface = false; +} +protected void consumeMethodHeaderName() { + if(this.indexOfAssistIdentifier() < 0) { + identifierPtr--; + identifierLengthPtr--; + if(this.indexOfAssistIdentifier() != 0) { + identifierPtr++; + identifierLengthPtr++; + super.consumeMethodHeaderName(); + } else { + restartRecovery = true; + + // recovery + if (currentElement != null) { + //name + char[] selector = identifierStack[identifierPtr + 1]; + long selectorSource = identifierPositionStack[identifierPtr + 1]; + + //type + TypeReference type = getTypeReference(intStack[intPtr--]); + ((CompletionOnSingleTypeReference)type).isCompletionNode = false; + //modifiers + int declarationSourceStart = intStack[intPtr--]; + int modifiers = intStack[intPtr--]; + + if(scanner.getLineNumber(type.sourceStart) != scanner.getLineNumber((int) (selectorSource >>> 32))) { + FieldDeclaration completionFieldDecl = new CompletionOnFieldType(type, false); + completionFieldDecl.modifiers = modifiers; + assistNode = completionFieldDecl; + lastCheckPoint = type.sourceEnd + 1; + currentElement = currentElement.add(completionFieldDecl, 0); + lastIgnoredToken = -1; + } else { + CompletionOnMethodReturnType md = new CompletionOnMethodReturnType(type, this.compilationUnit.compilationResult); + md.selector = selector; + md.declarationSourceStart = declarationSourceStart; + md.modifiers = modifiers; + md.bodyStart = lParenPos+1; + listLength = 0; // initialize listLength before reading parameters/throws + assistNode = md; + this.lastCheckPoint = md.bodyStart; + currentElement = currentElement.add(md, 0); + lastIgnoredToken = -1; + } + } + } + } else { + // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + CompletionOnMethodName md = new CompletionOnMethodName(this.compilationUnit.compilationResult); + + //name + md.selector = identifierStack[identifierPtr]; + long selectorSource = identifierPositionStack[identifierPtr--]; + //type + md.returnType = getTypeReference(intStack[intPtr--]); + //modifiers + md.declarationSourceStart = intStack[intPtr--]; + md.modifiers = intStack[intPtr--]; + + //highlight starts at selector start + md.sourceStart = (int) (selectorSource >>> 32); + md.selectorEnd = (int) selectorSource; + pushOnAstStack(md); + md.sourceEnd = lParenPos; + md.bodyStart = lParenPos+1; + listLength = 0; // initialize listLength before reading parameters/throws + + this.assistNode = md; + this.lastCheckPoint = md.sourceEnd; + // recovery + if (currentElement != null){ + if (currentElement instanceof RecoveredType + //|| md.modifiers != 0 + || (scanner.getLineNumber(md.returnType.sourceStart) + == scanner.getLineNumber(md.sourceStart))){ + lastCheckPoint = md.bodyStart; + currentElement = currentElement.add(md, 0); + lastIgnoredToken = -1; + } else { + lastCheckPoint = md.sourceStart; + restartRecovery = true; + } + } + } +} + + +protected void consumeMethodBody() { + super.consumeMethodBody(); + this.labelCounterPtr--; + if (this.blockInvocationPtr >= 0) this.blockInvocationPtr--; +} + +protected void consumeMethodHeader() { + super.consumeMethodHeader(); + pushBlockInvocationPtr(); +} +protected void consumeModifiers() { + super.consumeModifiers(); + // save from stack values + this.lastModifiersStart = intStack[intPtr]; + this.lastModifiers = intStack[intPtr-1]; +} +protected void consumeNestedMethod() { + super.consumeNestedMethod(); + this.pushNewLabelCounter(); +} +protected void consumeStatementLabel() { + super.consumeStatementLabel(); + if (this.labelCounterPtr >= 0) this.labelCounterStack[this.labelCounterPtr]--; +} +protected void consumeToken(int token) { + int previous = this.previousToken; + int previousIdentifierPtr = this.previousIdentifierPtr; + super.consumeToken(token); + + // if in field initializer (directly or not), on the completion identifier and not in recovery mode yet + // then position end of file at cursor location (so that we have the same behavior as + // in method bodies) + if (token == TokenNameIdentifier + && this.identifierStack[this.identifierPtr] == assistIdentifier() + && this.currentElement == null + && this.insideFieldInitialization()) { + this.scanner.eofPosition = cursorLocation < Integer.MAX_VALUE ? cursorLocation+1 : cursorLocation; + } + + // if in a method or if in a field initializer + if (this.inMethodStack[this.inMethodPtr] || this.inFieldInitializationStack[this.inFieldInitializationPtr]) { + switch (token) { + case TokenNameDOT: + switch (previous) { +// case TokenNamethis: // eg. this[.]fred() +// this.invocationType = EXPLICIT_RECEIVER; +// break; +// case TokenNamesuper: // eg. super[.]fred() +// this.invocationType = SUPER_RECEIVER; +// break; + case TokenNameIdentifier: // eg. bar[.]fred() + if (!this.betweenNewAndLeftBraket) { // eg. not new z.y[.]X() + if (this.identifierPtr != previousIdentifierPtr) { // if identifier has been consumed, eg. this.x[.]fred() + this.invocationType = EXPLICIT_RECEIVER; + } else { + this.invocationType = NAME_RECEIVER; + } + } + break; + } + break; + case TokenNameIdentifier: + if (previous == TokenNameDOT) { // eg. foo().[fred]() + // if current identifier is the empty completion one + if (identifierStack[identifierPtr] == CompletionScanner.EmptyCompletionIdentifier){ + this.completionBehindDot = true; + } + if (this.invocationType != SUPER_RECEIVER // eg. not super.[fred]() + && this.invocationType != NAME_RECEIVER // eg. not bar.[fred]() + && this.invocationType != ALLOCATION // eg. not new foo.[Bar]() + && this.invocationType != QUALIFIED_ALLOCATION) { // eg. not fred().new foo.[Bar]() + + this.invocationType = EXPLICIT_RECEIVER; + this.qualifier = this.expressionPtr; + } + } + break; + case TokenNamenew: + this.betweenNewAndLeftBraket = true; + this.qualifier = this.expressionPtr; // NB: even if there is no qualification, set it to the expression ptr so that the number of arguments are correctly computed + if (previous == TokenNameDOT) { // eg. fred().[new] X() + this.invocationType = QUALIFIED_ALLOCATION; + } else { // eg. [new] X() + this.invocationType = ALLOCATION; + } + break; +// case TokenNamethis: +// if (previous == TokenNameDOT) { // eg. fred().[this]() +// this.invocationType = QUALIFIED_ALLOCATION; +// this.qualifier = this.expressionPtr; +// } +// break; +// case TokenNamesuper: +// if (previous == TokenNameDOT) { // eg. fred().[super]() +// this.invocationType = QUALIFIED_ALLOCATION; +// this.qualifier = this.expressionPtr; +// } +// break; +// case TokenNamecatch: +// this.betweenCatchAndRightParen = true; +// break; + case TokenNameLPAREN: + this.betweenNewAndLeftBraket = false; + this.bracketDepth++; + if (this.invocationType == NO_RECEIVER || this.invocationType == NAME_RECEIVER) { + this.qualifier = this.expressionPtr; // remenber the last expression so that arguments are correctly computed + } + switch (previous) { + case TokenNameIdentifier: // eg. fred[(]) or foo.fred[(]) + this.pushOnInvocationStacks(this.invocationType, this.qualifier); + this.invocationType = NO_RECEIVER; + break; +// case TokenNamethis: // explicit constructor invocation, eg. this[(]1, 2) +// this.pushOnInvocationStacks( +// (this.invocationType == QUALIFIED_ALLOCATION) ? QUALIFIED_ALLOCATION : ALLOCATION, +// this.qualifier); +// this.invocationType = NO_RECEIVER; +// break; +// case TokenNamesuper: // explicit constructor invocation, eg. super[(]1, 2) +// this.pushOnInvocationStacks( +// (this.invocationType == QUALIFIED_ALLOCATION) ? QUALIFIED_ALLOCATION : ALLOCATION, +// this.qualifier); +// this.invocationType = NO_RECEIVER; +// break; + } + break; + case TokenNameLBRACE: + this.betweenNewAndLeftBraket = false; + this.bracketDepth++; + this.pushBlockInvocationPtr(); + break; + case TokenNameLBRACKET: + this.betweenNewAndLeftBraket = false; + this.bracketDepth++; + break; + case TokenNameRBRACE: + this.bracketDepth--; + if (this.blockInvocationPtr >= 0) this.blockInvocationPtr--; + break; + case TokenNameRBRACKET: + this.bracketDepth--; + break; + case TokenNameRPAREN: + this.betweenCatchAndRightParen = false; + this.bracketDepth--; + break; + case TokenNameCOLON: + if (previous == TokenNameIdentifier) { + if (this.labelCounterPtr >= 0) this.labelCounterStack[this.labelCounterPtr]++; + } + break; +// case TokenNamethrow: +// this.throwBracketDepth= bracketDepth; +// break; + } + } +} +/** + * Return whether the given ast node contains the completion node. + */ +private boolean containsCompletionNode(AstNode ast) { + if (this.assistNode == null || ast instanceof Literal) { + return false; + } + if (this.assistNode == ast) { + return true; + } + if (ast instanceof Reference || ast instanceof TypeReference) { + return ast == this.assistNode; + } + if (ast instanceof Assignment) { + Assignment assign = (Assignment)ast; + return containsCompletionNode(assign.lhs) || containsCompletionNode(assign.expression); + } + if (ast instanceof UnaryExpression) { + UnaryExpression unary = (UnaryExpression)ast; + return containsCompletionNode(unary.expression); + } + if (ast instanceof BinaryExpression) { + BinaryExpression binary = (BinaryExpression)ast; + return containsCompletionNode(binary.left) || containsCompletionNode(binary.right); + } + if (ast instanceof InstanceOfExpression) { + InstanceOfExpression instanceOfExpr = (InstanceOfExpression)ast; + return containsCompletionNode(instanceOfExpr.expression) || containsCompletionNode(instanceOfExpr.type); + } + if (ast instanceof ConditionalExpression) { + ConditionalExpression conditional = (ConditionalExpression)ast; + return containsCompletionNode(conditional.condition) || containsCompletionNode(conditional.valueIfTrue) || containsCompletionNode(conditional.valueIfFalse); + } + if (ast instanceof AllocationExpression) { + AllocationExpression alloc = (AllocationExpression)ast; + return containsCompletionNode(alloc.type); + } + if (ast instanceof CastExpression) { + CastExpression cast = (CastExpression)ast; + return containsCompletionNode(cast.expression) || containsCompletionNode(cast.type); + } + if (ast instanceof ExplicitConstructorCall) { + ExplicitConstructorCall call = (ExplicitConstructorCall)ast; + Expression[] arguments = call.arguments; + if (arguments != null) { + for (int i = 0; i < arguments.length; i++) { + if (containsCompletionNode(arguments[i])) { + return true; + } + } + return false; + } + } + return false; +} +public ImportReference createAssistImportReference(char[][] tokens, long[] positions){ + return new CompletionOnImportReference(tokens, positions); +} +public ImportReference createAssistPackageReference(char[][] tokens, long[] positions){ + return new CompletionOnPackageReference(tokens, positions); +} +public NameReference createQualifiedAssistNameReference(char[][] previousIdentifiers, char[] name, long[] positions){ + return new CompletionOnQualifiedNameReference( + previousIdentifiers, + name, + positions); +} +public TypeReference createQualifiedAssistTypeReference(char[][] previousIdentifiers, char[] name, long[] positions){ + return this.betweenCatchAndRightParen || this.nextTypeReferenceIsException // check for exception scenario + ? new CompletionOnQualifiedExceptionReference( + previousIdentifiers, + name, + positions) + : this.nextTypeReferenceIsInterface + ? new CompletionOnQualifiedInterfaceReference( + previousIdentifiers, + name, + positions) + : this.nextTypeReferenceIsClass + ? new CompletionOnQualifiedClassReference( + previousIdentifiers, + name, + positions) + : new CompletionOnQualifiedTypeReference( + previousIdentifiers, + name, + positions); +} +public NameReference createSingleAssistNameReference(char[] name, long position) { + return new CompletionOnSingleNameReference(name, position); +} +public TypeReference createSingleAssistTypeReference(char[] name, long position) { + return this.betweenCatchAndRightParen || this.nextTypeReferenceIsException // check for exception scenario + ? new CompletionOnExceptionReference(name, position) + : this.nextTypeReferenceIsInterface + ? new CompletionOnInterfaceReference(name, position) + : this.nextTypeReferenceIsClass + ? new CompletionOnClassReference(name, position) + : new CompletionOnSingleTypeReference(name, position); +} +public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int cursorLocation) { + + this.cursorLocation = cursorLocation; + CompletionScanner completionScanner = (CompletionScanner)this.scanner; + completionScanner.completionIdentifier = null; + completionScanner.cursorLocation = cursorLocation; + return this.dietParse(sourceUnit, compilationResult); +} +/* + * Flush parser/scanner state regarding to code assist + */ +public void flushAssistState() { + + super.flushAssistState(); + this.isOrphanCompletionNode = false; + CompletionScanner completionScanner = (CompletionScanner)this.scanner; + completionScanner.completedIdentifierStart = 0; + completionScanner.completedIdentifierEnd = -1; +} +protected NameReference getUnspecifiedReferenceOptimized() { + if (this.identifierLengthStack[this.identifierLengthPtr] > 1) { // reducing a qualified name + // potential receiver is being poped, so reset potential receiver + this.invocationType = NO_RECEIVER; + } + return super.getUnspecifiedReferenceOptimized(); +} +/** + * Return whether the given ast node has information interresting for code completion. + */ +private boolean hasCompletionInformation(AstNode ast) { + return ( + ast instanceof AbstractMethodDeclaration || + ast instanceof AbstractVariableDeclaration || + ast instanceof LabeledStatement || + ast instanceof TypeDeclaration); +} +public void initialize() { + super.initialize(); + this.initializeForBlockStatements(); + this.labelCounterPtr = -1; +} +/* + * Initializes the state of the parser that is about to go for BlockStatements. + */ +private void initializeForBlockStatements() { + this.previousToken = -1; + this.previousIdentifierPtr = -1; + this.completionBehindDot = false; + this.betweenNewAndLeftBraket = false; + this.betweenCatchAndRightParen = false; + this.bracketDepth = 0; + this.throwBracketDepth = -1; + this.invocationType = NO_RECEIVER; + this.qualifier = -1; + this.blockInvocationPtr = -1; +} +public void initializeScanner(){ + this.scanner = new CompletionScanner(this.assertMode); +} +/** + * Returns whether the completion is just after an array type + * eg. String[].[cursor] + */ +private boolean isAfterArrayType() { + // TBD: The following relies on the fact that array dimensions are small: it says that if the + // top of the intStack is less than 11, then it must be a dimension + // (smallest position of array type in a compilation unit is 11 as in "class X{Y[]") + if ((this.intPtr > -1) && (this.intStack[this.intPtr] < 11)) { + return true; + } + return false; +} +private boolean isEmptyNameCompletion() { + return + this.assistNode != null && + this.assistNode instanceof CompletionOnSingleNameReference && + (((CompletionOnSingleNameReference)this.assistNode).token.length == 0); +} +public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int cursorLocation) { + + this.cursorLocation = cursorLocation; + CompletionScanner completionScanner = (CompletionScanner)this.scanner; + completionScanner.completionIdentifier = null; + completionScanner.cursorLocation = cursorLocation; + return this.parse(sourceUnit, compilationResult); +} +/* + * Prepares the state of the parser to go for BlockStatements. + */ +protected void prepareForBlockStatements() { + super.prepareForBlockStatements(); + this.initializeForBlockStatements(); +} +protected void pushBlockInvocationPtr() { + try { + this.blockInvocationStack[++this.blockInvocationPtr] = this.invocationPtr+1; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = this.blockInvocationStack.length; + int[] oldStack = this.blockInvocationStack; + this.blockInvocationStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, this.blockInvocationStack, 0, oldStackLength); + this.blockInvocationStack[this.blockInvocationPtr] = this.invocationPtr+1; + } +} +/** + * Creates a completion on member access node and push it + * on the expression stack. + */ +private void pushCompletionOnMemberAccessOnExpressionStack(boolean isSuperAccess) { + char[] source = identifierStack[identifierPtr]; + long pos = identifierPositionStack[identifierPtr--]; + CompletionOnMemberAccess fr = new CompletionOnMemberAccess(source, pos); + this.assistNode = fr; + this.lastCheckPoint = fr.sourceEnd + 1; + identifierLengthPtr--; + if (isSuperAccess) { //considerates the fieldReference beginning at the 'super' .... + fr.sourceStart = intStack[intPtr--]; + fr.receiver = new SuperReference(fr.sourceStart, endPosition); + pushOnExpressionStack(fr); + } else { //optimize push/pop + if ((fr.receiver = expressionStack[expressionPtr]).isThis()) { //fieldreference begins at the this + fr.sourceStart = fr.receiver.sourceStart; + } + expressionStack[expressionPtr] = fr; + } +} +protected void pushNewLabelCounter() { + try { + this.labelCounterStack[++this.labelCounterPtr] = 0; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = this.labelCounterStack.length; + int[] oldStack = this.labelCounterStack; + this.labelCounterStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, this.labelCounterStack, 0, oldStackLength); + this.labelCounterStack[this.labelCounterPtr] = 0; + } +} +/** + * Pushes the given invocation type (one of the invocation type constants) on the invocation type stack, + * and the given qualifier (an expression pointer to the expression stack) on the qualifier stack. + */ +protected void pushOnInvocationStacks(int invocationType, int qualifierExprPtr) { + // NB: invocationPtr has already been incremented by a call to pushOnSelectorStack() + try { + this.invocationTypeStack[this.invocationPtr] = invocationType; + this.qualifierStack[this.invocationPtr] = qualifierExprPtr; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = this.invocationTypeStack.length; + int oldInvocationTypeStack[] = this.invocationTypeStack; + int oldQualifierStack[] = this.qualifierStack; + this.invocationTypeStack = new int[oldStackLength + StackIncrement]; + this.qualifierStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldInvocationTypeStack, 0, this.invocationTypeStack, 0, oldStackLength); + System.arraycopy(oldQualifierStack, 0, this.qualifierStack, 0, oldStackLength); + this.invocationTypeStack[this.invocationPtr] = invocationType; + this.qualifierStack[this.invocationPtr] = qualifierExprPtr; + } +} +public void recordCompletionOnReference(){ + + if (currentElement instanceof RecoveredType){ + RecoveredType recoveredType = (RecoveredType)currentElement; + + /* filter out cases where scanner is still inside type header */ + if (!recoveredType.foundOpeningBrace) return; + + /* generate a pseudo field with a completion on type reference */ + currentElement.add( + new CompletionOnFieldType(this.getTypeReference(0), false), 0); + return; + } + if (!diet) return; // only record references attached to types + +} +protected void reportSyntaxError(int act, int currentKind, int stateStackTop) { + + /* Intercept error state on EOF inside method bodies, due to + cursor location being used as an EOF position. + */ + if (!diet && currentToken == TokenNameEOF) return; + super.reportSyntaxError(act, currentKind, stateStackTop); +} +/* + * Reset internal state after completion is over + */ + +public void reset() { + super.reset(); + this.cursorLocation = 0; +} +/* + * Reset internal state after completion is over + */ + +public void resetAfterCompletion() { + this.cursorLocation = 0; + this.flushAssistState(); +} +/* + * Reset context so as to resume to regular parse loop + * If unable to reset for resuming, answers false. + * + * Move checkpoint location, reset internal stacks and + * decide which grammar goal is activated. + */ +protected boolean resumeAfterRecovery() { + if (this.assistNode != null) { + /* if reached [eof] inside method body, but still inside nested type, + or inside a field initializer, should continue in diet mode until + the end of the method body or compilation unit */ + if ((scanner.eofPosition == cursorLocation+1) + && (!(referenceContext instanceof CompilationUnitDeclaration) + || insideFieldInitialization())) { + + /* disabled since does not handle possible field/message refs, i.e. Obj[ASSIST HERE]ect.registerNatives() + // consume extra tokens which were part of the qualified reference + // so that the replaced source comprises them as well + if (this.assistNode instanceof NameReference){ + int oldEof = scanner.eofPosition; + scanner.eofPosition = currentElement.topElement().sourceEnd()+1; + scanner.currentPosition = this.cursorLocation+1; + int token = -1; + try { + do { + // first token might not have to be a dot + if (token >= 0 || !this.completionBehindDot){ + if ((token = scanner.getNextToken()) != TokenNameDOT) break; + } + if ((token = scanner.getNextToken()) != TokenNameIdentifier) break; + this.assistNode.sourceEnd = scanner.currentPosition - 1; + } while (token != TokenNameEOF); + } catch (InvalidInputException e){ + } finally { + scanner.eofPosition = oldEof; + } + } + */ + /* restart in diet mode for finding sibling constructs */ + if (currentElement.enclosingType() != null){ + lastCheckPoint = this.assistNode.sourceEnd+1; + int end = currentElement.topElement().sourceEnd(); + scanner.eofPosition = end < Integer.MAX_VALUE ? end + 1 : end; + } else { + this.resetStacks(); + return false; + } + } + } + return super.resumeAfterRecovery(); +} +public void setAssistIdentifier(char[] assistIdent){ + ((CompletionScanner)scanner).completionIdentifier = assistIdent; +} +/** + * Stores the labels left on the identifier stack if they have not been stored yet. + */ +private void storeLabelsIfNeeded() { +// int counter = this.labelCounterPtr >= 0 ? this.labelCounterStack[this.labelCounterPtr] : 0; +// if (this.labels == null && this.identifierPtr >= 0) { +// this.labels = new char[counter][]; +// System.arraycopy(this.identifierStack, this.identifierPtr - counter + 1, this.labels, 0, counter); +// } +// this.identifierPtr -= counter; +// this.identifierLengthPtr -= counter; // labels have not been concatenated yet +} +/* + * Update recovery state based on current parser/scanner state + */ +protected void updateRecoveryState() { + + /* expose parser state to recovery state */ + currentElement.updateFromParserState(); + + /* may be able to retrieve completionNode as an orphan, and then attach it */ + this.completionIdentifierCheck(); + this.attachOrphanCompletionNode(); + + // if an assist node has been found and a recovered element exists, + // mark enclosing blocks as to be preserved + if (this.assistNode != null && this.currentElement != null) { + currentElement.preserveEnclosingBlocks(); + } + + /* check and update recovered state based on current token, + this action is also performed when shifting token after recovery + got activated once. + */ + this.recoveryTokenCheck(); +} + +protected LocalDeclaration createLocalDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { + if (this.indexOfAssistIdentifier() < 0) { + return super.createLocalDeclaration(initialization, name, sourceStart, sourceEnd); + } else { + CompletionOnLocalName local = new CompletionOnLocalName(initialization, name, sourceStart, sourceEnd); + this.assistNode = local; + this.lastCheckPoint = sourceEnd + 1; + return local; + } +} + +protected FieldDeclaration createFieldDeclaration(Expression initialization, char[] name, int sourceStart, int sourceEnd) { + if (this.indexOfAssistIdentifier() < 0) { + return super.createFieldDeclaration(initialization, name, sourceStart, sourceEnd); + } else { + CompletionOnFieldName field = new CompletionOnFieldName(initialization, name, sourceStart, sourceEnd); + this.assistNode = field; + this.lastCheckPoint = sourceEnd + 1; + return field; + } +} + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionScanner.java new file mode 100644 index 0000000..d3b2156 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/CompletionScanner.java @@ -0,0 +1,707 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/* + * Scanner aware of a cursor location so as to discard trailing portions of identifiers + * containing the cursor location. + * + * Cursor location denotes the position of the last character behind which completion + * got requested: + * -1 means completion at the very beginning of the source + * 0 means completion behind the first character + * n means completion behind the n-th character + */ +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; + +public class CompletionScanner extends Scanner { + + public char[] completionIdentifier; + public int cursorLocation; + + /* Source positions of the completedIdentifier + * if inside actual identifier, end goes to the actual identifier + * end, i.e. beyond cursor location + */ + public int completedIdentifierStart = 0; + public int completedIdentifierEnd = -1; + + public static final char[] EmptyCompletionIdentifier = {}; +public CompletionScanner(boolean assertMode) { + super(false, false, false, assertMode); +} +/* + * Truncate the current identifier if it is containing the cursor location. Since completion is performed + * on an identifier prefix. + * + */ +public char[] getCurrentIdentifierSource() { + + if (completionIdentifier == null){ + if (cursorLocation < startPosition && currentPosition == startPosition){ // fake empty identifier got issued + // remember actual identifier positions + completedIdentifierStart = startPosition; + completedIdentifierEnd = completedIdentifierStart - 1; + return completionIdentifier = EmptyCompletionIdentifier; + } + if (cursorLocation+1 >= startPosition && cursorLocation < currentPosition){ + // remember actual identifier positions + completedIdentifierStart = startPosition; + completedIdentifierEnd = currentPosition - 1; + if (withoutUnicodePtr != 0){ // check unicode scenario + System.arraycopy(withoutUnicodeBuffer, 1, completionIdentifier = new char[withoutUnicodePtr], 0, withoutUnicodePtr); + } else { + int length = cursorLocation + 1 - startPosition; + // no char[] sharing around completionIdentifier, we want it to be unique so as to use identity checks + System.arraycopy(source, startPosition, (completionIdentifier = new char[length]), 0, length); + } + return completionIdentifier; + } + } + return super.getCurrentIdentifierSource(); +} +/* + * Identifier splitting for unicodes. + * Only store the current unicode if we did not pass the cursorLocation. + * Note: this does not handle cases where the cursor is in the middle of a unicode + */ +public boolean getNextCharAsJavaIdentifierPart() { + + int temp = currentPosition; + try { + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1, c2, c3, c4; + int unicodeSize = 6; + currentPosition++; + while (source[currentPosition] == 'u') { + currentPosition++; + unicodeSize++; + } + + if (((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + || c1 < 0) + || ((c2 = Character.getNumericValue(source[currentPosition++])) > 15 || c2 < 0) + || ((c3 = Character.getNumericValue(source[currentPosition++])) > 15 || c3 < 0) + || ((c4 = Character.getNumericValue(source[currentPosition++])) > 15 || c4 < 0)) { + currentPosition = temp; + return false; + } + + currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + if (!Character.isJavaIdentifierPart(currentCharacter)) { + currentPosition = temp; + return false; + } + + //need the unicode buffer + if (withoutUnicodePtr == 0) { + //buffer all the entries that have been left aside.... + withoutUnicodePtr = currentPosition - unicodeSize - startPosition; + System.arraycopy( + source, + startPosition, + withoutUnicodeBuffer, + 1, + withoutUnicodePtr); + } + if (temp < cursorLocation && cursorLocation < currentPosition-1){ + throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_UNICODE); + } + // store the current unicode, only if we did not pass the cursorLocation + // Note: this does not handle cases where the cursor is in the middle of a unicode + if ((completionIdentifier != null) + || (startPosition <= cursorLocation+1 && cursorLocation >= currentPosition-1)){ + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } + return true; + } //-------------end unicode traitement-------------- + else { + if (!Character.isJavaIdentifierPart(currentCharacter)) { + currentPosition = temp; + return false; + } + + if (withoutUnicodePtr != 0){ + // store the current unicode, only if we did not pass the cursorLocation + // Note: this does not handle cases where the cursor is in the middle of a unicode + if ((completionIdentifier != null) + || (startPosition <= cursorLocation+1 && cursorLocation >= currentPosition-1)){ + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } + } + return true; + } + } catch (IndexOutOfBoundsException e) { + currentPosition = temp; + return false; + } +} +public int getNextToken() throws InvalidInputException { + + this.wasAcr = false; + if (diet) { + jumpOverMethodBody(); + diet = false; + return currentPosition > source.length ? TokenNameEOF : TokenNameRBRACE; + } + try { + while (true) { //loop for jumping over comments + withoutUnicodePtr = 0; + //start with a new token (even comment written with unicode ) + + // ---------Consume white space and handles startPosition--------- + int whiteStart = currentPosition; + boolean isWhiteSpace; + do { + startPosition = currentPosition; + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + isWhiteSpace = jumpOverUnicodeWhiteSpace(); + } else { + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + pushLineSeparator(); + isWhiteSpace = + (currentCharacter == ' ') || Character.isWhitespace(currentCharacter); + } + /* completion requesting strictly inside blanks */ + if ((whiteStart != currentPosition) + //&& (previousToken == TokenNameDOT) + && (completionIdentifier == null) + && (whiteStart <= cursorLocation+1) + && (cursorLocation < startPosition) + && !Character.isJavaIdentifierStart(currentCharacter)){ + currentPosition = startPosition; // for next token read + return TokenNameIdentifier; + } + } while (isWhiteSpace); + if (tokenizeWhiteSpace && (whiteStart != currentPosition - 1)) { + // reposition scanner in case we are interested by spaces as tokens + currentPosition--; + startPosition = whiteStart; + return TokenNameWHITESPACE; + } + //little trick to get out in the middle of a source computation + if (currentPosition > eofPosition){ + /* might be completing at eof (e.g. behind a dot) */ + if (completionIdentifier == null && + startPosition == cursorLocation + 1){ + currentPosition = startPosition; // for being detected as empty free identifier + return TokenNameIdentifier; + } + return TokenNameEOF; + } + + // ---------Identify the next token------------- + + switch (currentCharacter) { + case '(' : + return TokenNameLPAREN; + case ')' : + return TokenNameRPAREN; + case '{' : + return TokenNameLBRACE; + case '}' : + return TokenNameRBRACE; + case '[' : + return TokenNameLBRACKET; + case ']' : + return TokenNameRBRACKET; + case ';' : + return TokenNameSEMICOLON; + case ',' : + return TokenNameCOMMA; + case '.' : + if (startPosition <= cursorLocation + && cursorLocation < currentPosition){ + return TokenNameDOT; // completion inside .<|>12 + } + if (getNextCharAsDigit()) + return scanNumber(true); + return TokenNameDOT; + case '+' : + { + int test; + if ((test = getNextChar('+', '=')) == 0) + return TokenNamePLUS_PLUS; + if (test > 0) + return TokenNamePLUS_EQUAL; + return TokenNamePLUS; + } + case '-' : + { + int test; + if ((test = getNextChar('-', '=')) == 0) + return TokenNameMINUS_MINUS; + if (test > 0) + return TokenNameMINUS_EQUAL; + return TokenNameMINUS; + } + case '~' : + return TokenNameTWIDDLE; + case '!' : + if (getNextChar('=')) + return TokenNameNOT_EQUAL; + return TokenNameNOT; + case '*' : + if (getNextChar('=')) + return TokenNameMULTIPLY_EQUAL; + return TokenNameMULTIPLY; + case '%' : + if (getNextChar('=')) + return TokenNameREMAINDER_EQUAL; + return TokenNameREMAINDER; + case '<' : + { + int test; + if ((test = getNextChar('=', '<')) == 0) + return TokenNameLESS_EQUAL; + if (test > 0) { + if (getNextChar('=')) + return TokenNameLEFT_SHIFT_EQUAL; + return TokenNameLEFT_SHIFT; + } + return TokenNameLESS; + } + case '>' : + { + int test; + if ((test = getNextChar('=', '>')) == 0) + return TokenNameGREATER_EQUAL; + if (test > 0) { + if ((test = getNextChar('=', '>')) == 0) + return TokenNameRIGHT_SHIFT_EQUAL; + if (test > 0) { + if (getNextChar('=')) + return TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL; + return TokenNameUNSIGNED_RIGHT_SHIFT; + } + return TokenNameRIGHT_SHIFT; + } + return TokenNameGREATER; + } + case '=' : + if (getNextChar('=')) + return TokenNameEQUAL_EQUAL; + return TokenNameEQUAL; + case '&' : + { + int test; + if ((test = getNextChar('&', '=')) == 0) + return TokenNameAND_AND; + if (test > 0) + return TokenNameAND_EQUAL; + return TokenNameAND; + } + case '|' : + { + int test; + if ((test = getNextChar('|', '=')) == 0) + return TokenNameOR_OR; + if (test > 0) + return TokenNameOR_EQUAL; + return TokenNameOR; + } + case '^' : + if (getNextChar('=')) + return TokenNameXOR_EQUAL; + return TokenNameXOR; + case '?' : + return TokenNameQUESTION; + case ':' : + return TokenNameCOLON; + case '\'' : + { + int test; + if ((test = getNextChar('\n', '\r')) == 0) { + throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); + } + if (test > 0) { + // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed + for (int lookAhead = 0; lookAhead < 3; lookAhead++) { + if (currentPosition + lookAhead == source.length) + break; + if (source[currentPosition + lookAhead] == '\n') + break; + if (source[currentPosition + lookAhead] == '\'') { + 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 (currentPosition + lookAhead == source.length) + break; + if (source[currentPosition + lookAhead] == '\n') + break; + if (source[currentPosition + lookAhead] == '\'') { + currentPosition += lookAhead + 1; + break; + } + } + throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); + } + if (getNextChar('\\')) + scanEscapeCharacter(); + else { // consume next character + unicodeAsBackSlash = false; + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + getNextUnicodeChar(); + } else { + if (withoutUnicodePtr != 0) { + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } + } + } + if (getNextChar('\'')) + return TokenNameCharacterLiteral; + // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed + for (int lookAhead = 0; lookAhead < 20; lookAhead++) { + if (currentPosition + lookAhead == source.length) + break; + if (source[currentPosition + lookAhead] == '\n') + break; + if (source[currentPosition + lookAhead] == '\'') { + currentPosition += lookAhead + 1; + break; + } + } + throw new InvalidInputException(INVALID_CHARACTER_CONSTANT); + case '"' : + try { + // consume next character + unicodeAsBackSlash = false; + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + getNextUnicodeChar(); + } else { + if (withoutUnicodePtr != 0) { + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } + } + + while (currentCharacter != '"') { + /**** \r and \n are not valid in string literals ****/ + if ((currentCharacter == '\n') || (currentCharacter == '\r')) { + // relocate if finding another quote fairly close: thus unicode '/u000D' will be fully consumed + for (int lookAhead = 0; lookAhead < 50; lookAhead++) { + if (currentPosition + lookAhead == source.length) + break; + if (source[currentPosition + lookAhead] == '\n') + break; + if (source[currentPosition + lookAhead] == '\"') { + currentPosition += lookAhead + 1; + break; + } + } + throw new InvalidInputException(INVALID_CHAR_IN_STRING); + } + if (currentCharacter == '\\') { + int escapeSize = currentPosition; + boolean backSlashAsUnicodeInString = unicodeAsBackSlash; + //scanEscapeCharacter make a side effect on this value and we need the previous value few lines down this one + scanEscapeCharacter(); + escapeSize = currentPosition - escapeSize; + if (withoutUnicodePtr == 0) { + //buffer all the entries that have been left aside.... + withoutUnicodePtr = currentPosition - escapeSize - 1 - startPosition; + System.arraycopy( + source, + startPosition, + withoutUnicodeBuffer, + 1, + withoutUnicodePtr); + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } else { //overwrite the / in the buffer + withoutUnicodeBuffer[withoutUnicodePtr] = currentCharacter; + if (backSlashAsUnicodeInString) { //there are TWO \ in the stream where only one is correct + withoutUnicodePtr--; + } + } + } + // consume next character + unicodeAsBackSlash = false; + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + getNextUnicodeChar(); + } else { + if (withoutUnicodePtr != 0) { + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } + } + + } + } catch (IndexOutOfBoundsException e) { + 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 (currentPosition + lookAhead == source.length) + break; + if (source[currentPosition + lookAhead] == '\n') + break; + if (source[currentPosition + lookAhead] == '\"') { + currentPosition += lookAhead + 1; + break; + } + } + + } + throw e; // rethrow + } + if (startPosition <= cursorLocation && cursorLocation <= currentPosition-1){ + throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_STRING); + } + return TokenNameStringLiteral; + case '/' : + { + int test; + if ((test = getNextChar('/', '*')) == 0) { //line comment + try { //get the next char + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + currentPosition++; + while (source[currentPosition] == 'u') { + currentPosition++; + } + if ((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[currentPosition++])) > 15 + || c4 < 0) { + throw new InvalidInputException(INVALID_UNICODE_ESCAPE); + } else { + currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + + //handle the \\u case manually into comment + if (currentCharacter == '\\') { + if (source[currentPosition] == '\\') + currentPosition++; + } //jump over the \\ + while (currentCharacter != '\r' && currentCharacter != '\n') { + //get the next char + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + currentPosition++; + while (source[currentPosition] == 'u') { + currentPosition++; + } + if ((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[currentPosition++])) > 15 + || c4 < 0) { + throw new InvalidInputException(INVALID_UNICODE_ESCAPE); + } else { + currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + //handle the \\u case manually into comment + if (currentCharacter == '\\') { + if (source[currentPosition] == '\\') + currentPosition++; + } //jump over the \\ + } + recordComment(false); + if (startPosition <= cursorLocation && cursorLocation < currentPosition-1){ + throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); + } + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + pushLineSeparator(); + if (tokenizeComments) { + currentPosition--; // reset one character behind + return TokenNameCOMMENT_LINE; + } + } catch (IndexOutOfBoundsException e) { //an eof will them be generated + if (tokenizeComments) { + currentPosition--; // reset one character behind + return TokenNameCOMMENT_LINE; + } + } + break; + } + if (test > 0) { //traditional and annotation comment + boolean isJavadoc = false, star = false; + // consume next character + unicodeAsBackSlash = false; + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + getNextUnicodeChar(); + } else { + if (withoutUnicodePtr != 0) { + withoutUnicodeBuffer[++withoutUnicodePtr] = currentCharacter; + } + } + + if (currentCharacter == '*') { + isJavadoc = true; + star = true; + } + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + pushLineSeparator(); + try { //get the next char + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + currentPosition++; + while (source[currentPosition] == 'u') { + currentPosition++; + } + if ((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[currentPosition++])) > 15 + || c4 < 0) { + throw new InvalidInputException(INVALID_UNICODE_ESCAPE); + } else { + currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + //handle the \\u case manually into comment + if (currentCharacter == '\\') { + if (source[currentPosition] == '\\') + currentPosition++; + } //jump over the \\ + // empty comment is not a javadoc /**/ + if (currentCharacter == '/') { + isJavadoc = false; + } + //loop until end of comment */ + while ((currentCharacter != '/') || (!star)) { + if (recordLineSeparator + && ((currentCharacter == '\r') || (currentCharacter == '\n'))) + pushLineSeparator(); + star = currentCharacter == '*'; + //get next char + if (((currentCharacter = source[currentPosition++]) == '\\') + && (source[currentPosition] == 'u')) { + //-------------unicode traitement ------------ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + currentPosition++; + while (source[currentPosition] == 'u') { + currentPosition++; + } + if ((c1 = Character.getNumericValue(source[currentPosition++])) > 15 + || c1 < 0 + || (c2 = Character.getNumericValue(source[currentPosition++])) > 15 + || c2 < 0 + || (c3 = Character.getNumericValue(source[currentPosition++])) > 15 + || c3 < 0 + || (c4 = Character.getNumericValue(source[currentPosition++])) > 15 + || c4 < 0) { + throw new InvalidInputException(INVALID_UNICODE_ESCAPE); + } else { + currentCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + } + //handle the \\u case manually into comment + if (currentCharacter == '\\') { + if (source[currentPosition] == '\\') + currentPosition++; + } //jump over the \\ + } + recordComment(isJavadoc); + if (startPosition <= cursorLocation && cursorLocation < currentPosition-1){ + throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_COMMENT); + } + if (tokenizeComments) { + if (isJavadoc) + return TokenNameCOMMENT_JAVADOC; + return TokenNameCOMMENT_BLOCK; + } + } catch (IndexOutOfBoundsException e) { + throw new InvalidInputException(UNTERMINATED_COMMENT); + } + break; + } + if (getNextChar('=')) + return TokenNameDIVIDE_EQUAL; + return TokenNameDIVIDE; + } + case '\u001a' : + if (atEnd()) + return TokenNameEOF; + //the atEnd may not be if source is only some part of a real (external) stream + throw new InvalidInputException("Ctrl-Z"); //$NON-NLS-1$ + + default : + if (Character.isJavaIdentifierStart(currentCharacter)) + return scanIdentifierOrKeyword(); + if (Character.isDigit(currentCharacter)) + return scanNumber(false); + return TokenNameERROR; + } + } + } //-----------------end switch while try-------------------- + catch (IndexOutOfBoundsException e) { + } + /* might be completing at very end of file (e.g. behind a dot) */ + if (completionIdentifier == null && + startPosition == cursorLocation + 1){ + currentPosition = startPosition; // for being detected as empty free identifier + return TokenNameIdentifier; + } + return TokenNameEOF; +} +/* + * In case we actually read a keyword, but the cursor is located inside, + * we pretend we read an identifier. + */ +public int scanIdentifierOrKeyword() throws InvalidInputException { + + int id = super.scanIdentifierOrKeyword(); + + // convert completed keyword into an identifier + if (id != TokenNameIdentifier + && startPosition <= cursorLocation+1 + && cursorLocation < currentPosition){ + return TokenNameIdentifier; + } + return id; +} +public int scanNumber(boolean dotPrefix) throws InvalidInputException { + + int token = super.scanNumber(dotPrefix); + + // consider completion just before a number to be ok, will insert before it + if (startPosition <= cursorLocation && cursorLocation < currentPosition){ + throw new InvalidCursorLocation(InvalidCursorLocation.NO_COMPLETION_INSIDE_NUMBER); + } + return token; +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/InvalidCursorLocation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/InvalidCursorLocation.java new file mode 100644 index 0000000..295dd81 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/complete/InvalidCursorLocation.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.complete; + +/** + * Thrown whenever cursor location is not inside a consistent token + * i.e. inside a string, number, unicode, comments etc... + */ +public class InvalidCursorLocation extends RuntimeException { + + public String irritant; + + /* Possible irritants */ + public static final String NO_COMPLETION_INSIDE_UNICODE = "No Completion Inside Unicode"; //$NON-NLS-1$ + public static final String NO_COMPLETION_INSIDE_COMMENT = "No Completion Inside Comment"; //$NON-NLS-1$ + public static final String NO_COMPLETION_INSIDE_STRING = "No Completion Inside String"; //$NON-NLS-1$ + public static final String NO_COMPLETION_INSIDE_NUMBER = "No Completion Inside Number"; //$NON-NLS-1$ + +public InvalidCursorLocation(String irritant){ + this.irritant = irritant; +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java new file mode 100644 index 0000000..76fbddd --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistOptions.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.impl; + +import java.util.Map; + +public class AssistOptions { + /** + * Option IDs + */ + public static final String OPTION_PerformVisibilityCheck = + "org.eclipse.jdt.core.codeComplete.visibilityCheck"; //$NON-NLS-1$ + public static final String OPTION_ForceImplicitQualification = + "org.eclipse.jdt.core.codeComplete.forceImplicitQualification"; //$NON-NLS-1$ + public static final String ENABLED = "enabled"; //$NON-NLS-1$ + public static final String DISABLED = "disabled"; //$NON-NLS-1$ + + public boolean checkVisibility = false; + public boolean forceImplicitQualification = false; + + /** + * Initializing the assist options with default settings + */ + public AssistOptions() { + } + + /** + * Initializing the assist options with external settings + */ + public AssistOptions(Map settings) { + if (settings == null) + return; + + // filter options which are related to the assist component + Object[] entries = settings.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; + String optionID = (String) entry.getKey(); + String optionValue = (String) entry.getValue(); + + if (optionID.equals(OPTION_PerformVisibilityCheck)) { + if (optionValue.equals(ENABLED)) { + this.checkVisibility = true; + } else + if (optionValue.equals(DISABLED)) { + this.checkVisibility = false; + } + continue; + } else if (optionID.equals(OPTION_ForceImplicitQualification)) { + if (optionValue.equals(ENABLED)) { + this.forceImplicitQualification = true; + } else + if (optionValue.equals(DISABLED)) { + this.forceImplicitQualification = false; + } + continue; + } + } + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistParser.java new file mode 100644 index 0000000..b97679f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/AssistParser.java @@ -0,0 +1,1009 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.impl; + +/* + * Parser extension for code assist task + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.AbstractMethodDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.AstNode; +import net.sourceforge.phpdt.internal.compiler.ast.Block; +import net.sourceforge.phpdt.internal.compiler.ast.CompilationUnitDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.ConstructorDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.ExplicitConstructorCall; +import net.sourceforge.phpdt.internal.compiler.ast.Expression; +import net.sourceforge.phpdt.internal.compiler.ast.FieldDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.ImportReference; +import net.sourceforge.phpdt.internal.compiler.ast.Initializer; +import net.sourceforge.phpdt.internal.compiler.ast.LocalDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.MessageSend; +import net.sourceforge.phpdt.internal.compiler.ast.MethodDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.NameReference; +import net.sourceforge.phpdt.internal.compiler.ast.TypeDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; +import net.sourceforge.phpdt.internal.compiler.parser.Parser; +import net.sourceforge.phpdt.internal.compiler.parser.RecoveredElement; +import net.sourceforge.phpdt.internal.compiler.parser.RecoveredField; +import net.sourceforge.phpdt.internal.compiler.parser.RecoveredInitializer; +import net.sourceforge.phpdt.internal.compiler.parser.RecoveredMethod; +import net.sourceforge.phpdt.internal.compiler.parser.RecoveredType; +import net.sourceforge.phpdt.internal.compiler.parser.RecoveredUnit; +import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation; +import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; + +public abstract class AssistParser extends Parser { + + public AstNode assistNode; + public boolean isOrphanCompletionNode; + + /* recovery */ + int[] blockStarts = new int[30]; + + // the previous token read by the scanner + protected int previousToken; + + // the index in the identifier stack of the previous identifier + protected int previousIdentifierPtr; + + // the stacks of selectors for invocations (ie. method invocations, allocation expressions and + // explicit constructor invocations) + // the selector stack contains pointers to the identifier stack or one of the selector constants below + protected int invocationPtr; + protected int[] selectorStack = new int[StackIncrement]; + + // selector constants + protected static final int THIS_CONSTRUCTOR = -1; + protected static final int SUPER_CONSTRUCTOR = -2; + + // whether the parser is in a field initializer + // (false is pushed each time a new type is entered, + // it is changed to true when the initializer is entered, + // it is changed back to false when the initializer is exited, + // and it is poped when the type is exited) + protected int inFieldInitializationPtr; + protected boolean[] inFieldInitializationStack = new boolean[StackIncrement]; + + // whether the parser is in a method, constructor or initializer + // (false is pushed each time a new type is entered, + // it is changed to true when the method is entered, + // it is changed back to false when the method is exited, + // and it is poped when the type is exited) + protected int inMethodPtr; + protected boolean[] inMethodStack = new boolean[StackIncrement]; +public AssistParser(ProblemReporter problemReporter, boolean assertMode) { + super(problemReporter, true, assertMode); +} +public abstract char[] assistIdentifier(); +public int bodyEnd(AbstractMethodDeclaration method){ + return method.declarationSourceEnd; +} +public int bodyEnd(Initializer initializer){ + return initializer.declarationSourceEnd; +} +/* + * Build initial recovery state. + * Recovery state is inferred from the current state of the parser (reduced node stack). + */ +public RecoveredElement buildInitialRecoveryState(){ + + /* recovery in unit structure */ + if (referenceContext instanceof CompilationUnitDeclaration){ + RecoveredElement element = super.buildInitialRecoveryState(); + flushAssistState(); + initInMethodAndInFieldInitializationStack(element); + return element; + } + + /* recovery in method body */ + lastCheckPoint = 0; + + RecoveredElement element = null; + if (referenceContext instanceof AbstractMethodDeclaration){ + element = new RecoveredMethod((AbstractMethodDeclaration) referenceContext, null, 0, this); + lastCheckPoint = ((AbstractMethodDeclaration) referenceContext).bodyStart; + } else { + /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */ + if (referenceContext instanceof TypeDeclaration){ + TypeDeclaration type = (TypeDeclaration) referenceContext; + for (int i = 0; i < type.fields.length; i++){ + FieldDeclaration field = type.fields[i]; + if (!field.isField() + && field.declarationSourceStart <= scanner.initialPosition + && scanner.initialPosition <= field.declarationSourceEnd + && scanner.eofPosition <= field.declarationSourceEnd+1){ + element = new RecoveredInitializer((Initializer) field, null, 1, this); + lastCheckPoint = field.declarationSourceStart; + break; + } + } + } + } + + if (element == null) return element; + + /* add initial block */ + Block block = new Block(0); + int lastStart = blockStarts[0]; + block.sourceStart = lastStart; + element = element.add(block, 1); + int blockIndex = 1; // ignore first block start, since manually rebuilt here + + for(int i = 0; i <= astPtr; i++){ + AstNode node = astStack[i]; + + /* check for intermediate block creation, so recovery can properly close them afterwards */ + int nodeStart = node.sourceStart; + for (int j = blockIndex; j <= realBlockPtr; j++){ + if (blockStarts[j] > nodeStart){ + blockIndex = j; // shift the index to the new block + break; + } + if (blockStarts[j] != lastStart){ // avoid multiple block if at same position + block = new Block(0); + block.sourceStart = lastStart = blockStarts[j]; + element = element.add(block, 1); + } + blockIndex = j+1; // shift the index to the new block + } + if (node instanceof LocalDeclaration){ + LocalDeclaration local = (LocalDeclaration) node; + if (local.declarationSourceEnd == 0){ + element = element.add(local, 0); + if (local.initialization == null){ + lastCheckPoint = local.sourceEnd + 1; + } else { + lastCheckPoint = local.initialization.sourceEnd + 1; + } + } else { + element = element.add(local, 0); + lastCheckPoint = local.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof AbstractMethodDeclaration){ + AbstractMethodDeclaration method = (AbstractMethodDeclaration) node; + if (method.declarationSourceEnd == 0){ + element = element.add(method, 0); + lastCheckPoint = method.bodyStart; + } else { + element = element.add(method, 0); + lastCheckPoint = method.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof Initializer){ + Initializer initializer = (Initializer) node; + if (initializer.declarationSourceEnd == 0){ + element = element.add(initializer, 1); + lastCheckPoint = initializer.bodyStart; + } else { + element = element.add(initializer, 0); + lastCheckPoint = initializer.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof FieldDeclaration){ + FieldDeclaration field = (FieldDeclaration) node; + if (field.declarationSourceEnd == 0){ + element = element.add(field, 0); + if (field.initialization == null){ + lastCheckPoint = field.sourceEnd + 1; + } else { + lastCheckPoint = field.initialization.sourceEnd + 1; + } + } else { + element = element.add(field, 0); + lastCheckPoint = field.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof TypeDeclaration){ + TypeDeclaration type = (TypeDeclaration) node; + if (type.declarationSourceEnd == 0){ + element = element.add(type, 0); + lastCheckPoint = type.bodyStart; + } else { + element = element.add(type, 0); + lastCheckPoint = type.declarationSourceEnd + 1; + } + continue; + } + if (node instanceof ImportReference){ + ImportReference importRef = (ImportReference) node; + element = element.add(importRef, 0); + lastCheckPoint = importRef.declarationSourceEnd + 1; + } + } + if (this.currentToken == TokenNameRBRACE) { + this.currentToken = 0; // closing brace has already been taken care of + } + + /* might need some extra block (after the last reduced node) */ + int pos = this.assistNode == null ? lastCheckPoint : this.assistNode.sourceStart; + for (int j = blockIndex; j <= realBlockPtr; j++){ + if ((blockStarts[j] < pos) && (blockStarts[j] != lastStart)){ // avoid multiple block if at same position + block = new Block(0); + block.sourceStart = lastStart = blockStarts[j]; + element = element.add(block, 1); + } + } + + initInMethodAndInFieldInitializationStack(element); + return element; +} +protected void consumeClassBodyDeclarationsopt() { + super.consumeClassBodyDeclarationsopt(); + this.inFieldInitializationPtr--; + this.inMethodPtr--; +} +protected void consumeClassBodyopt() { + super.consumeClassBodyopt(); + this.invocationPtr--; // NB: This can be decremented below -1 only if in diet mode and not in field initializer +} +protected void consumeClassHeader() { + super.consumeClassHeader(); + this.pushNotInInitializer(); + this.pushNotInMethod(); +} +protected void consumeConstructorBody() { + super.consumeConstructorBody(); + this.inMethodStack[this.inMethodPtr] = false; +} +protected void consumeConstructorHeader() { + super.consumeConstructorHeader(); + this.inMethodStack[this.inMethodPtr] = true; +} +protected void consumeEmptyClassBodyDeclarationsopt() { + super.consumeEmptyClassBodyDeclarationsopt(); + this.inFieldInitializationPtr--; + this.inMethodPtr--; +} +protected void consumeEnterAnonymousClassBody() { + super.consumeEnterAnonymousClassBody(); + this.invocationPtr--; // NB: This can be decremented below -1 only if in diet mode and not in field initializer + this.pushNotInInitializer(); + this.pushNotInMethod(); +} +protected void consumeExplicitConstructorInvocation(int flag, int recFlag) { + super.consumeExplicitConstructorInvocation(flag, recFlag); + this.invocationPtr--; // NB: This can be decremented below -1 only if in diet mode and not in field initializer +} +protected void consumeForceNoDiet() { + super.consumeForceNoDiet(); + // if we are not in a method (ie. we are not in a local variable initializer) + // then we are entering a field initializer + if (!this.inMethodStack[this.inMethodPtr]) { + this.inFieldInitializationStack[this.inFieldInitializationPtr] = true; + } +} +protected void consumeInterfaceHeader() { + super.consumeInterfaceHeader(); + this.pushNotInInitializer(); + this.pushNotInMethod(); +} +protected void consumeInterfaceMemberDeclarationsopt() { + super.consumeInterfaceMemberDeclarationsopt(); + this.inFieldInitializationPtr--; + this.inMethodPtr--; +} +protected void consumeMethodBody() { + super.consumeMethodBody(); + this.inMethodStack[this.inMethodPtr] = false; +} +protected void consumeMethodHeader() { + super.consumeMethodHeader(); + this.inMethodStack[this.inMethodPtr] = true; +} +protected void consumeMethodInvocationName() { + super.consumeMethodInvocationName(); + this.invocationPtr--; // NB: This can be decremented below -1 only if in diet mode and not in field initializer + MessageSend messageSend = (MessageSend)expressionStack[expressionPtr]; + if (messageSend == assistNode){ + this.lastCheckPoint = messageSend.sourceEnd + 1; + } +} +protected void consumeMethodInvocationPrimary() { + super.consumeMethodInvocationPrimary(); + this.invocationPtr--; // NB: This can be decremented below -1 only if in diet mode and not in field initializer + MessageSend messageSend = (MessageSend)expressionStack[expressionPtr]; + if (messageSend == assistNode){ + this.lastCheckPoint = messageSend.sourceEnd + 1; + } +} +protected void consumeMethodInvocationSuper() { + super.consumeMethodInvocationSuper(); + this.invocationPtr--; // NB: This can be decremented below -1 only if in diet mode and not in field initializer + MessageSend messageSend = (MessageSend)expressionStack[expressionPtr]; + if (messageSend == assistNode){ + this.lastCheckPoint = messageSend.sourceEnd + 1; + } +} +protected void consumeNestedMethod() { + super.consumeNestedMethod(); + this.inMethodStack[this.inMethodPtr] = true; +} +protected void consumeOpenBlock() { + // OpenBlock ::= $empty + + super.consumeOpenBlock(); + try { + blockStarts[realBlockPtr] = scanner.startPosition; + } catch (IndexOutOfBoundsException e) { + //realBlockPtr is correct + int oldStackLength = blockStarts.length; + int oldStack[] = blockStarts; + blockStarts = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldStack, 0, blockStarts, 0, oldStackLength); + blockStarts[realBlockPtr] = scanner.startPosition; + } +} +protected void consumePackageDeclarationName() { + // PackageDeclarationName ::= 'package' Name + /* build an ImportRef build from the last name + stored in the identifier stack. */ + + int index; + + /* no need to take action if not inside assist identifiers */ + if ((index = indexOfAssistIdentifier()) < 0) { + super.consumePackageDeclarationName(); + return; + } + /* retrieve identifiers subset and whole positions, the assist node positions + should include the entire replaced source. */ + int length = identifierLengthStack[identifierLengthPtr]; + char[][] subset = identifierSubSet(index+1); // include the assistIdentifier + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + + /* build specific assist node on package statement */ + ImportReference reference = this.createAssistPackageReference(subset, positions); + assistNode = reference; + this.lastCheckPoint = reference.sourceEnd + 1; + compilationUnit.currentPackage = reference; + + if (currentToken == TokenNameSEMICOLON){ + reference.declarationSourceEnd = scanner.currentPosition - 1; + } else { + reference.declarationSourceEnd = (int) positions[length-1]; + } + //endPosition is just before the ; + reference.declarationSourceStart = intStack[intPtr--]; + // flush annotations defined prior to import statements + reference.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(reference.declarationSourceEnd); + + // recovery + if (currentElement != null){ + lastCheckPoint = reference.declarationSourceEnd+1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } +} +protected void consumeRestoreDiet() { + super.consumeRestoreDiet(); + // if we are not in a method (ie. we were not in a local variable initializer) + // then we are exiting a field initializer + if (!this.inMethodStack[this.inMethodPtr]) { + this.inFieldInitializationStack[this.inFieldInitializationPtr] = false; + } +} +protected void consumeSingleTypeImportDeclarationName() { + // SingleTypeImportDeclarationName ::= 'import' Name + /* push an ImportRef build from the last name + stored in the identifier stack. */ + + int index; + + /* no need to take action if not inside assist identifiers */ + if ((index = indexOfAssistIdentifier()) < 0) { + super.consumeSingleTypeImportDeclarationName(); + return; + } + /* retrieve identifiers subset and whole positions, the assist node positions + should include the entire replaced source. */ + int length = identifierLengthStack[identifierLengthPtr]; + char[][] subset = identifierSubSet(index+1); // include the assistIdentifier + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + + /* build specific assist node on import statement */ + ImportReference reference = this.createAssistImportReference(subset, positions); + assistNode = reference; + this.lastCheckPoint = reference.sourceEnd + 1; + + pushOnAstStack(reference); + + if (currentToken == TokenNameSEMICOLON){ + reference.declarationSourceEnd = scanner.currentPosition - 1; + } else { + reference.declarationSourceEnd = (int) positions[length-1]; + } + //endPosition is just before the ; + reference.declarationSourceStart = intStack[intPtr--]; + // flush annotations defined prior to import statements + reference.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(reference.declarationSourceEnd); + + // recovery + if (currentElement != null){ + lastCheckPoint = reference.declarationSourceEnd+1; + currentElement = currentElement.add(reference, 0); + lastIgnoredToken = -1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } +} +protected void consumeStaticInitializer() { + super.consumeStaticInitializer(); + this.inMethodStack[this.inMethodPtr] = false; +} +protected void consumeStaticOnly() { + super.consumeStaticOnly(); + this.inMethodStack[this.inMethodPtr] = true; +} +protected void consumeToken(int token) { + super.consumeToken(token); + // register message send selector only if inside a method or if looking at a field initializer + // and if the current token is an open parenthesis + if ((this.inMethodStack[this.inMethodPtr] || this.inFieldInitializationStack[this.inFieldInitializationPtr]) && token == TokenNameLPAREN) { + switch (this.previousToken) { + case TokenNameIdentifier: + this.pushOnSelectorStack(this.identifierPtr); + break; +// case TokenNamethis: // explicit constructor invocation, eg. this(1, 2) +// this.pushOnSelectorStack(THIS_CONSTRUCTOR); +// break; +// case TokenNamesuper: // explicit constructor invocation, eg. super(1, 2) +// this.pushOnSelectorStack(SUPER_CONSTRUCTOR); +// break; + } + } + this.previousToken = token; + if (token == TokenNameIdentifier) { + this.previousIdentifierPtr = this.identifierPtr; + } +} +protected void consumeTypeImportOnDemandDeclarationName() { + // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' + /* push an ImportRef build from the last name + stored in the identifier stack. */ + + int index; + + /* no need to take action if not inside assist identifiers */ + if ((index = indexOfAssistIdentifier()) < 0) { + super.consumeTypeImportOnDemandDeclarationName(); + return; + } + /* retrieve identifiers subset and whole positions, the assist node positions + should include the entire replaced source. */ + int length = identifierLengthStack[identifierLengthPtr]; + char[][] subset = identifierSubSet(index+1); // include the assistIdentifier + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + + /* build specific assist node on import statement */ + ImportReference reference = this.createAssistImportReference(subset, positions); + reference.onDemand = true; + assistNode = reference; + this.lastCheckPoint = reference.sourceEnd + 1; + + pushOnAstStack(reference); + + if (currentToken == TokenNameSEMICOLON){ + reference.declarationSourceEnd = scanner.currentPosition - 1; + } else { + reference.declarationSourceEnd = (int) positions[length-1]; + } + //endPosition is just before the ; + reference.declarationSourceStart = intStack[intPtr--]; + // flush annotations defined prior to import statements + reference.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(reference.declarationSourceEnd); + + // recovery + if (currentElement != null){ + lastCheckPoint = reference.declarationSourceEnd+1; + currentElement = currentElement.add(reference, 0); + lastIgnoredToken = -1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } +} +public abstract ImportReference createAssistImportReference(char[][] tokens, long[] positions); +public abstract ImportReference createAssistPackageReference(char[][] tokens, long[] positions); +public abstract NameReference createQualifiedAssistNameReference(char[][] previousIdentifiers, char[] name, long[] positions); +public abstract TypeReference createQualifiedAssistTypeReference(char[][] previousIdentifiers, char[] name, long[] positions); +public abstract NameReference createSingleAssistNameReference(char[] name, long position); +public abstract TypeReference createSingleAssistTypeReference(char[] name, long position); +/* + * Flush parser/scanner state regarding to code assist + */ +public void flushAssistState(){ + this.assistNode = null; + this.isOrphanCompletionNode = false; + this.setAssistIdentifier(null); +} +/* + * Build specific type reference nodes in case the cursor is located inside the type reference + */ +protected TypeReference getTypeReference(int dim) { + + int index; + + /* no need to take action if not inside completed identifiers */ + if ((index = indexOfAssistIdentifier()) < 0) { + return super.getTypeReference(dim); + } + + /* retrieve identifiers subset and whole positions, the assist node positions + should include the entire replaced source. */ + int length = identifierLengthStack[identifierLengthPtr]; + char[][] subset = identifierSubSet(index); + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + + /* build specific assist on type reference */ + TypeReference reference; + if (index == 0) { + /* assist inside first identifier */ + reference = this.createSingleAssistTypeReference( + assistIdentifier(), + positions[0]); + } else { + /* assist inside subsequent identifier */ + reference = this.createQualifiedAssistTypeReference( + subset, + assistIdentifier(), + positions); + } + assistNode = reference; + this.lastCheckPoint = reference.sourceEnd + 1; + return reference; +} +/* + * Copy of code from superclass with the following change: + * In the case of qualified name reference if the cursor location is on the + * qualified name reference, then create a CompletionOnQualifiedNameReference + * instead. + */ +protected NameReference getUnspecifiedReferenceOptimized() { + + int completionIndex; + + /* no need to take action if not inside completed identifiers */ + if ((completionIndex = indexOfAssistIdentifier()) < 0) { + return super.getUnspecifiedReferenceOptimized(); + } + + /* retrieve identifiers subset and whole positions, the completion node positions + should include the entire replaced source. */ + int length = identifierLengthStack[identifierLengthPtr]; + char[][] subset = identifierSubSet(completionIndex); + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + + /* build specific completion on name reference */ + NameReference reference; + if (completionIndex == 0) { + /* completion inside first identifier */ + reference = this.createSingleAssistNameReference(assistIdentifier(), positions[0]); + } else { + /* completion inside subsequent identifier */ + reference = this.createQualifiedAssistNameReference(subset, assistIdentifier(), positions); + }; + reference.bits &= ~AstNode.RestrictiveFlagMASK; + reference.bits |= LOCAL | FIELD; + + assistNode = reference; + lastCheckPoint = reference.sourceEnd + 1; + return reference; +} +public void goForBlockStatementsopt() { + //tells the scanner to go for block statements opt parsing + + firstToken = TokenNameTWIDDLE; + scanner.recordLineSeparator = false; +} +public void goForConstructorBlockStatementsopt() { + //tells the scanner to go for constructor block statements opt parsing + + firstToken = TokenNameNOT; + scanner.recordLineSeparator = false; +} +/* + * Retrieve a partial subset of a qualified name reference up to the completion point. + * It does not pop the actual awaiting identifiers, so as to be able to retrieve position + * information afterwards. + */ +protected char[][] identifierSubSet(int subsetLength){ + + if (subsetLength == 0) return null; + + char[][] subset; + System.arraycopy( + identifierStack, + identifierPtr - identifierLengthStack[identifierLengthPtr] + 1, + (subset = new char[subsetLength][]), + 0, + subsetLength); + return subset; +} +/* + * Iterate the most recent group of awaiting identifiers (grouped for qualified name reference (eg. aa.bb.cc) + * so as to check whether one of them is the assist identifier. + * If so, then answer the index of the assist identifier (0 being the first identifier of the set). + * eg. aa(0).bb(1).cc(2) + * If no assist identifier was found, answers -1. + */ +protected int indexOfAssistIdentifier(){ + + if (identifierLengthPtr < 0){ + return -1; // no awaiting identifier + } + + char[] assistIdentifier ; + if ((assistIdentifier = this.assistIdentifier()) == null){ + return -1; // no assist identifier found yet + } + + // iterate awaiting identifiers backwards + int length = identifierLengthStack[identifierLengthPtr]; + for (int i = 0; i < length; i++){ + if (identifierStack[identifierPtr - i] == assistIdentifier){ + return length - i - 1; + } + } + // none of the awaiting identifiers is the completion one + return -1; +} +public void initialize() { + super.initialize(); + this.flushAssistState(); + this.invocationPtr = -1; + this.inMethodStack[this.inMethodPtr = 0] = false; + this.inFieldInitializationStack[this.inFieldInitializationPtr = 0] = false; + this.previousIdentifierPtr = -1; +} +public abstract void initializeScanner(); + +protected void initInMethodAndInFieldInitializationStack(RecoveredElement currentElement) { + + int length = currentElement.depth() + 1; + int ptr = length; + boolean[] methodStack = new boolean[length]; + boolean[] fieldInitializationStack = new boolean[length]; + boolean inMethod = false; + boolean inFieldInitializer = false; + + RecoveredElement element = currentElement; + while(element != null){ + if(element instanceof RecoveredMethod || + element instanceof RecoveredInitializer) { + if(element.parent == null) { + methodStack[--ptr] = true; + fieldInitializationStack[ptr] = false; + } + inMethod = true; + } else if(element instanceof RecoveredField){ + inFieldInitializer = element.sourceEnd() == 0; + } else if(element instanceof RecoveredType){ + methodStack[--ptr] = inMethod; + fieldInitializationStack[ptr] = inFieldInitializer; + + inMethod = false; + inFieldInitializer = false; + } else if(element instanceof RecoveredUnit) { + methodStack[--ptr] = false; + fieldInitializationStack[ptr] = false; + } + element = element.parent; + } + + inMethodPtr = length - ptr - 1; + inFieldInitializationPtr = inMethodPtr; + System.arraycopy(methodStack, ptr, inMethodStack, 0, inMethodPtr + 1); + System.arraycopy(fieldInitializationStack, ptr, inFieldInitializationStack, 0, inFieldInitializationPtr + 1); + +} + +/** + * Returns whether we are directly or indirectly inside a field initializer. + */ +protected boolean insideFieldInitialization() { + for (int i = this.inFieldInitializationPtr; i >= 0; i--) { + if (this.inFieldInitializationStack[i]) { + return true; + } + } + return false; +} +/** + * Parse the block statements inside the given method declaration and try to complete at the + * cursor location. + */ +public void parseBlockStatements(AbstractMethodDeclaration md, CompilationUnitDeclaration unit) { + if (md instanceof MethodDeclaration) { + parseBlockStatements((MethodDeclaration) md, unit); + } else if (md instanceof ConstructorDeclaration) { + parseBlockStatements((ConstructorDeclaration) md, unit); + } +} +/** + * Parse the block statements inside the given constructor declaration and try to complete at the + * cursor location. + */ +public void parseBlockStatements(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { + //only parse the method body of cd + //fill out its statements + + //convert bugs into parse error + + initialize(); + + // simulate goForConstructorBody except that we don't want to balance brackets because they are not going to be balanced + goForConstructorBlockStatementsopt(); + + referenceContext = cd; + compilationUnit = unit; + + scanner.resetTo(cd.bodyStart, bodyEnd(cd)); + consumeNestedMethod(); + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } +} +/** + * Parse the block statements inside the given initializer and try to complete at the + * cursor location. + */ +public void parseBlockStatements( + Initializer ini, + TypeDeclaration type, + CompilationUnitDeclaration unit) { + + initialize(); + + // simulate goForInitializer except that we don't want to balance brackets because they are not going to be balanced + goForBlockStatementsopt(); + + referenceContext = type; + compilationUnit = unit; + + scanner.resetTo(ini.sourceStart, bodyEnd(ini)); // just after the beginning { + consumeNestedMethod(); + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } +} +/** + * Parse the block statements inside the given method declaration and try to complete at the + * cursor location. + */ +public void parseBlockStatements(MethodDeclaration md, CompilationUnitDeclaration unit) { + //only parse the method body of md + //fill out method statements + + //convert bugs into parse error + + if (md.isAbstract()) + return; + if (md.isNative()) + return; + if ((md.modifiers & AccSemicolonBody) != 0) + return; + + initialize(); + + // simulate goForMethodBody except that we don't want to balance brackets because they are not going to be balanced + goForBlockStatementsopt(); + + referenceContext = md; + compilationUnit = unit; + + scanner.resetTo(md.bodyStart, bodyEnd(md)); // reset the scanner to parser from { down to the cursor location + consumeNestedMethod(); + try { + parse(); + } catch (AbortCompilation ex) { + lastAct = ERROR_ACTION; + } finally { + nestedMethod[nestedType]--; + } +} +/* + * Prepares the state of the parser to go for BlockStatements. + */ +protected void prepareForBlockStatements() { + this.nestedMethod[this.nestedType = 0] = 1; + this.variablesCounter[this.nestedType] = 0; + this.realBlockStack[this.realBlockPtr = 1] = 0; + this.invocationPtr = -1; +} +/* + * Pushes 'false' on the inInitializerStack. + */ +protected void pushNotInInitializer() { + try { + this.inFieldInitializationStack[++this.inFieldInitializationPtr] = false; + } catch (IndexOutOfBoundsException e) { + //except in test's cases, it should never raise + int oldStackLength = this.inFieldInitializationStack.length; + System.arraycopy(this.inFieldInitializationStack , 0, (this.inFieldInitializationStack = new boolean[oldStackLength + StackIncrement]), 0, oldStackLength); + this.inFieldInitializationStack[this.inFieldInitializationPtr] = false; + } +} +/* + * Pushes 'false' on the inMethodStack. + */ +protected void pushNotInMethod() { + try { + this.inMethodStack[++this.inMethodPtr] = false; + } catch (IndexOutOfBoundsException e) { + //except in test's cases, it should never raise + int oldStackLength = this.inMethodStack.length; + System.arraycopy(this.inMethodStack , 0, (this.inMethodStack = new boolean[oldStackLength + StackIncrement]), 0, oldStackLength); + this.inMethodStack[this.inMethodPtr] = false; + } +} +/** + * Pushes the given the given selector (an identifier pointer to the identifier stack) on the selector stack. + */ +protected void pushOnSelectorStack(int selectorIdPtr) { + if (this.invocationPtr < -1) return; + try { + this.selectorStack[++this.invocationPtr] = selectorIdPtr; + } catch (IndexOutOfBoundsException e) { + int oldStackLength = this.selectorStack.length; + int oldSelectorStack[] = this.selectorStack; + this.selectorStack = new int[oldStackLength + StackIncrement]; + System.arraycopy(oldSelectorStack, 0, this.selectorStack, 0, oldStackLength); + this.selectorStack[this.invocationPtr] = selectorIdPtr; + } +} +public void reset(){ + this.flushAssistState(); +} +/* + * Reset context so as to resume to regular parse loop + */ +protected void resetStacks() { + super.resetStacks(); + this.inFieldInitializationStack[this.inFieldInitializationPtr = 0] = false; + this.inMethodStack[this.inMethodPtr = 0] = false; +} +/* + * Reset context so as to resume to regular parse loop + * If unable to reset for resuming, answers false. + * + * Move checkpoint location, reset internal stacks and + * decide which grammar goal is activated. + */ +protected boolean resumeAfterRecovery() { + + // reset internal stacks + astPtr = -1; + astLengthPtr = -1; + expressionPtr = -1; + expressionLengthPtr = -1; + identifierPtr = -1; + identifierLengthPtr = -1; + intPtr = -1; + dimensions = 0 ; + recoveredStaticInitializerStart = 0; + + // if in diet mode, reset the diet counter because we're going to restart outside an initializer. + if (diet) dietInt = 0; + + /* attempt to move checkpoint location */ + if (!this.moveRecoveryCheckpoint()) return false; + + initInMethodAndInFieldInitializationStack(currentElement); + + // only look for headers + if (referenceContext instanceof CompilationUnitDeclaration + || this.assistNode != null){ + + if(inMethodStack[inMethodPtr] && + insideFieldInitialization() && + this.assistNode == null + ){ + this.prepareForBlockStatements(); + goForBlockStatementsOrMethodHeaders(); + } else { + nestedMethod[nestedType = 0] = 0; + variablesCounter[nestedType] = 0; + realBlockStack[realBlockPtr = 0] = 0; + goForHeaders(); + diet = true; // passed this point, will not consider method bodies + } + return true; + } + if (referenceContext instanceof AbstractMethodDeclaration + || referenceContext instanceof TypeDeclaration){ + + if (currentElement instanceof RecoveredType){ + nestedMethod[nestedType = 0] = 0; + variablesCounter[nestedType] = 0; + realBlockStack[realBlockPtr = 0] = 0; + goForHeaders(); + } else { + this.prepareForBlockStatements(); + goForBlockStatementsOrMethodHeaders(); + } + return true; + } + // does not know how to restart + return false; +} +public abstract void setAssistIdentifier(char[] assistIdent); +/** + * If the given ast node is inside an explicit constructor call + * then wrap it with a fake constructor call. + * Returns the wrapped completion node or the completion node itself. + */ +protected AstNode wrapWithExplicitConstructorCallIfNeeded(AstNode ast) { + int selector; + if (ast != null && this.invocationPtr >= 0 && ast instanceof Expression && + (((selector = this.selectorStack[this.invocationPtr]) == THIS_CONSTRUCTOR) || + (selector == SUPER_CONSTRUCTOR))) { + ExplicitConstructorCall call = new ExplicitConstructorCall( + (selector == THIS_CONSTRUCTOR) ? + ExplicitConstructorCall.This : + ExplicitConstructorCall.Super + ); + call.arguments = new Expression[] {(Expression)ast}; + call.sourceStart = ast.sourceStart; + call.sourceEnd = ast.sourceEnd; + return call; + } else { + return ast; + } +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/Engine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/Engine.java new file mode 100644 index 0000000..35a3dc9 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/impl/Engine.java @@ -0,0 +1,192 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.impl; + +import java.util.Map; + +import net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment; +import net.sourceforge.phpdt.internal.compiler.*; +import net.sourceforge.phpdt.internal.compiler.env.*; + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; +import net.sourceforge.phpdt.internal.compiler.parser.*; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; +import net.sourceforge.phpdt.internal.compiler.impl.*; + + +public abstract class Engine implements ITypeRequestor { + + public LookupEnvironment lookupEnvironment; + + protected CompilationUnitScope unitScope; + protected ISearchableNameEnvironment nameEnvironment; + + public AssistOptions options; + public CompilerOptions compilerOptions; + + public Engine(Map settings){ + this.options = new AssistOptions(settings); + this.compilerOptions = new CompilerOptions(settings); + } + + /** + * Add an additional binary type + */ + public void accept(IBinaryType binaryType, PackageBinding packageBinding) { + lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding); + } + + /** + * Add an additional compilation unit. + */ + public void accept(ICompilationUnit sourceUnit) { + CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = + this.getParser().dietParse(sourceUnit, result); + + + lookupEnvironment.buildTypeBindings(parsedUnit); + lookupEnvironment.completeTypeBindings(parsedUnit, true); + } + + /** + * Add additional source types (the first one is the requested type, the rest is formed by the + * secondary types defined in the same compilation unit). + */ + public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding) { + CompilationResult result = + new CompilationResult(sourceTypes[0].getFileName(), 1, 1, this.compilerOptions.maxProblemsPerUnit); + CompilationUnitDeclaration unit = + SourceTypeConverter.buildCompilationUnit( + sourceTypes, + true, + true, + lookupEnvironment.problemReporter, + result); + + if (unit != null) { + lookupEnvironment.buildTypeBindings(unit); + lookupEnvironment.completeTypeBindings(unit, true); + } + } + + public abstract AssistParser getParser(); + + protected boolean mustQualifyType( + char[] packageName, + char[] typeName) { + + // If there are no types defined into the current CU yet. + if (unitScope == null) + return true; + + char[][] compoundPackageName = CharOperation.splitOn('.', packageName); + char[] readableTypeName = CharOperation.concat(packageName, typeName, '.'); + + if (CharOperation.equals(unitScope.fPackage.compoundName, compoundPackageName)) + return false; + + ImportBinding[] imports = unitScope.imports; + if (imports != null){ + for (int i = 0, length = imports.length; i < length; i++) { + if (imports[i].onDemand) { + if (CharOperation.equals(imports[i].compoundName, compoundPackageName)) { + for (int j = 0; j < imports.length; j++) { + if(i != j){ + if(imports[j].onDemand) { + if(nameEnvironment.findType(typeName, imports[j].compoundName) != null){ + return true; + } + } else { + if(CharOperation.equals(CharOperation.lastSegment(imports[j].readableName(), '.'), typeName)) { + return true; + } + } + } + } + return false; // how do you match p1.p2.A.* ? + } + + } else + + if (CharOperation.equals(imports[i].readableName(), readableTypeName)) { + return false; + } + } + } + return true; + } + + protected void parseMethod(CompilationUnitDeclaration unit, int position) { + for (int i = unit.types.length; --i >= 0;) { + TypeDeclaration type = unit.types[i]; + if (type.declarationSourceStart < position + && type.declarationSourceEnd >= position) { + getParser().scanner.setSource( + unit.compilationResult.compilationUnit.getContents()); + parseMethod(type, unit, position); + return; + } + } + } + + private void parseMethod( + TypeDeclaration type, + CompilationUnitDeclaration unit, + int position) { + //members + TypeDeclaration[] memberTypes = type.memberTypes; + if (memberTypes != null) { + for (int i = memberTypes.length; --i >= 0;) { + TypeDeclaration memberType = memberTypes[i]; + if (memberType.bodyStart > position) + continue; + if (memberType.declarationSourceEnd >= position) { + parseMethod(memberType, unit, position); + return; + } + } + } + //methods + AbstractMethodDeclaration[] methods = type.methods; + if (methods != null) { + for (int i = methods.length; --i >= 0;) { + AbstractMethodDeclaration method = methods[i]; + if (method.bodyStart > position) + continue; + if (method.declarationSourceEnd >= position) { + getParser().parseBlockStatements(method, unit); + return; + } + } + } + //initializers + FieldDeclaration[] fields = type.fields; + if (fields != null) { + for (int i = fields.length; --i >= 0;) { + if (!(fields[i] instanceof Initializer)) + continue; + Initializer initializer = (Initializer) fields[i]; + if (initializer.bodyStart > position) + continue; + if (initializer.declarationSourceEnd >= position) { + getParser().parseBlockStatements(initializer, type, unit); + return; + } + } + } + } + + protected void reset() { + lookupEnvironment.reset(); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionNodeFound.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionNodeFound.java new file mode 100644 index 0000000..6d8a66f --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionNodeFound.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class SelectionNodeFound extends RuntimeException { + public Binding binding; +public SelectionNodeFound() { + this(null); // we found a problem in the selection node +} +public SelectionNodeFound(Binding binding) { + this.binding = binding; +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnArgumentName.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnArgumentName.java new file mode 100644 index 0000000..06a6783 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnArgumentName.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +import net.sourceforge.phpdt.internal.compiler.ast.Argument; +import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnArgumentName extends Argument { + public SelectionOnArgumentName(char[] name , long posNom , TypeReference tr , int modifiers){ + super(name, posNom, tr, modifiers); + } + + public void resolve(BlockScope scope) { + super.resolve(scope); + throw new SelectionNodeFound(binding); + } + + public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { + super.bind(scope, typeBinding, used); + + throw new SelectionNodeFound(binding); + } + + public String toString(int tab) { + String s = tabString(tab); + s += " class X { + * void foo() { + * + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.*; + +public class SelectionOnExplicitConstructorCall extends ExplicitConstructorCall { +public SelectionOnExplicitConstructorCall(int accessMode) { + super(accessMode); +} +public void resolve(BlockScope scope) { + super.resolve(scope); + + // tolerate some error cases + if (binding == null || + !(binding.isValidBinding() || + binding.problemId() == ProblemReasons.NotVisible)) + throw new SelectionNodeFound(); + else + throw new SelectionNodeFound(binding); +} +public String toString(int tab) { + String s = tabString(tab); + s += " class X { + * void foo() { + * + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.FieldReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnFieldReference extends FieldReference { +public SelectionOnFieldReference(char[] source , long pos) { + super(source, pos); +} +public TypeBinding resolveType(BlockScope scope) { + super.resolveType(scope); + + // tolerate some error cases + if (binding == null || + !(binding.isValidBinding() || + binding.problemId() == ProblemReasons.NotVisible + || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName + || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation + || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) + throw new SelectionNodeFound(); + else + throw new SelectionNodeFound(binding); +} +public String toStringExpression(){ + return ""; //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnFieldType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnFieldType.java new file mode 100644 index 0000000..aaa85c6 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnFieldType.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +import net.sourceforge.phpdt.internal.compiler.ast.FieldDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; + +public class SelectionOnFieldType extends FieldDeclaration { + public SelectionOnFieldType(TypeReference type) { + super(); + this.sourceStart = type.sourceStart; + this.sourceEnd = type.sourceEnd; + this.type = type; + this.name = NoChar; + } + public String toString(int tab) { + return type.toString(tab); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnImportReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnImportReference.java new file mode 100644 index 0000000..210eeb2 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnImportReference.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce an import reference containing the assist identifier. + * e.g. + * + * import java.[start]io[end].*; + * class X { + * void foo() { + * } + * } + * + * ---> + * class X { + * void foo() { + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.ImportReference; + +public class SelectionOnImportReference extends ImportReference { + +public SelectionOnImportReference(char[][] tokens , long[] positions) { + super(tokens, positions, false); +} +public String toString(int tab, boolean withOnDemand) { + + StringBuffer buffer = new StringBuffer(tabString(tab)); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnLocalName.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnLocalName.java new file mode 100644 index 0000000..da3cc76 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnLocalName.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +import net.sourceforge.phpdt.internal.compiler.ast.Expression; +import net.sourceforge.phpdt.internal.compiler.ast.LocalDeclaration; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; + +public class SelectionOnLocalName extends LocalDeclaration{ + public SelectionOnLocalName(Expression expr, char[] name, int sourceStart, int sourceEnd) { + super(expr, name, sourceStart, sourceEnd); + } + + public void resolve(BlockScope scope) { + super.resolve(scope); + throw new SelectionNodeFound(binding); + } + + public String toString(int tab) { + String s = tabString(tab); + s += " class X { + * void foo() { + * + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.MessageSend; +import net.sourceforge.phpdt.internal.compiler.ast.ThisReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnMessageSend extends MessageSend { + + public TypeBinding resolveType(BlockScope scope) { + super.resolveType(scope); + + // tolerate some error cases + if(binding == null || + !(binding.isValidBinding() || + binding.problemId() == ProblemReasons.NotVisible + || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName + || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation + || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) { + throw new SelectionNodeFound(); + } else { + throw new SelectionNodeFound(binding); + } + } + + public String toStringExpression() { + String s = ""; //$NON-NLS-1$ + return s; + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnPackageReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnPackageReference.java new file mode 100644 index 0000000..87a344b --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnPackageReference.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce an package statement containing the assist identifier. + * e.g. + * + * package java.[start]io[end]; + * class X { + * void foo() { + * } + * } + * + * ---> + * class X { + * void foo() { + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.ImportReference; + +public class SelectionOnPackageReference extends ImportReference { +public SelectionOnPackageReference(char[][] tokens , long[] positions) { + super(tokens, positions, true); +} +public String toString(int tab, boolean withOnDemand) { + StringBuffer buffer = new StringBuffer(tabString(tab)); + buffer. append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java new file mode 100644 index 0000000..d679001 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedAllocationExpression.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce an allocation expression containing the cursor. + * If the allocation expression is not qualified, the enclosingInstance field + * is null. + * e.g. + * + * class X { + * void foo() { + * new [start]Bar[end](1, 2) + * } + * } + * + * ---> class X { + * void foo() { + * + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.AnonymousLocalTypeDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.ConstructorDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.QualifiedAllocationExpression; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnQualifiedAllocationExpression extends QualifiedAllocationExpression { +public SelectionOnQualifiedAllocationExpression() { +} +public SelectionOnQualifiedAllocationExpression(AnonymousLocalTypeDeclaration anonymous) { + anonymousType = anonymous ; +} +public TypeBinding resolveType(BlockScope scope) { + super.resolveType(scope); + + // tolerate some error cases + if (binding == null || + !(binding.isValidBinding() || + binding.problemId() == ProblemReasons.NotVisible)) + throw new SelectionNodeFound(); + if (anonymousType == null) + throw new SelectionNodeFound(binding); + + // if selecting a type for an anonymous type creation, we have to + // find its target super constructor (if extending a class) or its target + // super interface (if extending an interface) + if (anonymousType.binding.superInterfaces == NoSuperInterfaces) { + // find the constructor binding inside the super constructor call + ConstructorDeclaration constructor = (ConstructorDeclaration) anonymousType.declarationOf(binding); + throw new SelectionNodeFound(constructor.constructorCall.binding); + } else { + // open on the only superinterface + throw new SelectionNodeFound(anonymousType.binding.superInterfaces[0]); + } +} +public String toStringExpression(int tab) { + return + ((this.enclosingInstance == null) ? + ""; //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java new file mode 100644 index 0000000..3fd7a85 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedNameReference.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce a qualified name reference containing the assist identifier. + * e.g. + * + * class X { + * Y y; + * void foo() { + * y.fred.[start]ba[end] + * } + * } + * + * ---> class X { + * Y y; + * void foo() { + * + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.QualifiedNameReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.FieldBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemFieldBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReferenceBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + +public class SelectionOnQualifiedNameReference extends QualifiedNameReference { + public long[] sourcePositions; // positions of each token, the last one being the positions of the completion identifier +public SelectionOnQualifiedNameReference(char[][] previousIdentifiers, char[] selectionIdentifier, long[] positions) { + super( + CharOperation.arrayConcat(previousIdentifiers, selectionIdentifier), + (int) (positions[0] >>> 32), + (int) positions[positions.length - 1]); + this.sourcePositions = positions; +} +public TypeBinding resolveType(BlockScope scope) { + // it can be a package, type, member type, local variable or field + binding = scope.getBinding(tokens, this); + if (!binding.isValidBinding()) { + if (binding instanceof ProblemFieldBinding) { + // tolerate some error cases + if (binding.problemId() == ProblemReasons.NotVisible + || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName + || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation + || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext) { + throw new SelectionNodeFound(binding); + } + scope.problemReporter().invalidField(this, (FieldBinding) binding); + } else if (binding instanceof ProblemReferenceBinding) { + // tolerate some error cases + if (binding.problemId() == ProblemReasons.NotVisible){ + throw new SelectionNodeFound(binding); + } + scope.problemReporter().invalidType(this, (TypeBinding) binding); + } else { + scope.problemReporter().unresolvableReference(this, binding); + } + throw new SelectionNodeFound(); + } + throw new SelectionNodeFound(binding); +} +public String toStringExpression() { + + StringBuffer buffer = new StringBuffer(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedSuperReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedSuperReference.java new file mode 100644 index 0000000..b6cfe20 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedSuperReference.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce a qualified super reference containing the assist identifier. + * e.g. + * + * class X extends Z { + * class Y { + * void foo() { + * X.[start]super[end].bar(); + * } + * } + * } + * + * ---> class X { + * class Y { + * void foo() { + * + * } + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.QualifiedSuperReference; +import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnQualifiedSuperReference extends QualifiedSuperReference { +public SelectionOnQualifiedSuperReference(TypeReference name, int pos, int sourceEnd) { + super(name, pos, sourceEnd); +} +public TypeBinding resolveType(BlockScope scope) { + TypeBinding binding = super.resolveType(scope); + + if (binding == null || !binding.isValidBinding()) + throw new SelectionNodeFound(); + else + throw new SelectionNodeFound(binding); +} +public String toStringExpression(){ + + StringBuffer buffer = new StringBuffer(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java new file mode 100644 index 0000000..5d49dfb --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnQualifiedTypeReference.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce a type reference containing the completion identifier as part + * of a qualified name. + * e.g. + * + * class X extends java.lang.[start]Object[end] + * + * ---> class X extends + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.QualifiedTypeReference; +import net.sourceforge.phpdt.internal.compiler.lookup.Binding; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.Scope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + +public class SelectionOnQualifiedTypeReference extends QualifiedTypeReference { +public SelectionOnQualifiedTypeReference(char[][] previousIdentifiers, char[] selectionIdentifier, long[] positions) { + super( + CharOperation.arrayConcat(previousIdentifiers, selectionIdentifier), + positions); +} +public void aboutToResolve(Scope scope) { + getTypeBinding(scope.parent); // step up from the ClassScope +} +public TypeBinding getTypeBinding(Scope scope) { + // it can be a package, type or member type + Binding binding = scope.getTypeOrPackage(tokens); + if (!binding.isValidBinding()) { + // tolerate some error cases + if (binding.problemId() == ProblemReasons.NotVisible){ + throw new SelectionNodeFound(binding); + } + scope.problemReporter().invalidType(this, (TypeBinding) binding); + throw new SelectionNodeFound(); + } + + throw new SelectionNodeFound(binding); +} +public String toStringExpression(int tab) { + + StringBuffer buffer = new StringBuffer(); + buffer.append(""); //$NON-NLS-1$ + return buffer.toString(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleNameReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleNameReference.java new file mode 100644 index 0000000..9589df2 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleNameReference.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce a single name reference containing the assist identifier. + * e.g. + * + * class X { + * void foo() { + * [start]ba[end] + * } + * } + * + * ---> class X { + * void foo() { + * + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.SingleNameReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.FieldBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemFieldBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReferenceBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnSingleNameReference extends SingleNameReference { +public SelectionOnSingleNameReference(char[] source, long pos) { + super(source, pos); +} +public TypeBinding resolveType(BlockScope scope) { + // it can be a package, type, member type, local variable or field + binding = scope.getBinding(token, VARIABLE | TYPE | PACKAGE, this); + if (!binding.isValidBinding()) { + if (binding instanceof ProblemFieldBinding) { + // tolerate some error cases + if (binding.problemId() == ProblemReasons.NotVisible + || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName + || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation + || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext){ + throw new SelectionNodeFound(binding); + } + scope.problemReporter().invalidField(this, (FieldBinding) binding); + } else if (binding instanceof ProblemReferenceBinding) { + // tolerate some error cases + if (binding.problemId() == ProblemReasons.NotVisible){ + throw new SelectionNodeFound(binding); + } + scope.problemReporter().invalidType(this, (TypeBinding) binding); + } else { + scope.problemReporter().unresolvableReference(this, binding); + } + throw new SelectionNodeFound(); + } + + throw new SelectionNodeFound(binding); +} +public String toStringExpression() { + return ""; //$NON-NLS-2$ //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleTypeReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleTypeReference.java new file mode 100644 index 0000000..7b4e42c --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSingleTypeReference.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce a type reference containing the selection identifier as a single + * name reference. + * e.g. + * + * class X extends [start]Object[end] + * + * ---> class X extends + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.SingleTypeReference; +import net.sourceforge.phpdt.internal.compiler.lookup.Binding; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons; +import net.sourceforge.phpdt.internal.compiler.lookup.ReferenceBinding; +import net.sourceforge.phpdt.internal.compiler.lookup.Scope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnSingleTypeReference extends SingleTypeReference { +public SelectionOnSingleTypeReference(char[] source, long pos) { + super(source, pos); +} +public void aboutToResolve(Scope scope) { + getTypeBinding(scope.parent); // step up from the ClassScope +} +public TypeBinding getTypeBinding(Scope scope) { + // it can be a package, type or member type + Binding binding = scope.getTypeOrPackage(new char[][] {token}); + if (!binding.isValidBinding()) { + scope.problemReporter().invalidType(this, (TypeBinding) binding); + throw new SelectionNodeFound(); + } + + throw new SelectionNodeFound(binding); +} +public TypeBinding resolveTypeEnclosing(BlockScope scope, ReferenceBinding enclosingType) { + super.resolveTypeEnclosing(scope, enclosingType); + + // tolerate some error cases + if (binding == null || + !(binding.isValidBinding() || + binding.problemId() == ProblemReasons.NotVisible)) + throw new SelectionNodeFound(); + else + throw new SelectionNodeFound(binding); +} +public String toStringExpression(int tab){ + + return "" ; //$NON-NLS-2$ //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSuperReference.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSuperReference.java new file mode 100644 index 0000000..13582bf --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionOnSuperReference.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Selection node build by the parser in any case it was intending to + * reduce a super reference containing the assist identifier. + * e.g. + * + * class X extends Z { + * class Y { + * void foo() { + * [start]super[end].bar(); + * } + * } + * } + * + * ---> class X { + * class Y { + * void foo() { + * + * } + * } + * } + * + */ + +import net.sourceforge.phpdt.internal.compiler.ast.SuperReference; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; + +public class SelectionOnSuperReference extends SuperReference { + +public SelectionOnSuperReference(int pos, int sourceEnd) { + super(pos, sourceEnd); +} +public TypeBinding resolveType(BlockScope scope) { + TypeBinding binding = super.resolveType(scope); + + if (binding == null || !binding.isValidBinding()) + throw new SelectionNodeFound(); + else + throw new SelectionNodeFound(binding); +} +public String toStringExpression(){ + + return ""; //$NON-NLS-2$ //$NON-NLS-1$ + +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionParser.java new file mode 100644 index 0000000..99f38b0 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionParser.java @@ -0,0 +1,686 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Parser able to build specific completion parse nodes, given a cursorLocation. + * + * Cursor location denotes the position of the last character behind which completion + * got requested: + * -1 means completion at the very beginning of the source + * 0 means completion behind the first character + * n means completion behind the n-th character + */ + +import net.sourceforge.phpdt.internal.compiler.*; +import net.sourceforge.phpdt.internal.compiler.env.*; + +import net.sourceforge.phpdt.internal.codeassist.impl.*; +import net.sourceforge.phpdt.internal.compiler.ast.*; +import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope; +import net.sourceforge.phpdt.internal.compiler.lookup.TypeBinding; +import net.sourceforge.phpdt.internal.compiler.parser.*; +import net.sourceforge.phpdt.internal.compiler.problem.*; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + +public class SelectionParser extends AssistParser { + + /* public fields */ + + public int selectionStart, selectionEnd; + + public static final char[] SUPER = "super".toCharArray(); //$NON-NLS-1$ + public static final char[] THIS = "this".toCharArray(); //$NON-NLS-1$ + +public SelectionParser(ProblemReporter problemReporter, boolean assertMode) { + super(problemReporter, assertMode); +} +public char[] assistIdentifier(){ + return ((SelectionScanner)scanner).selectionIdentifier; +} +protected void attachOrphanCompletionNode(){ + if (isOrphanCompletionNode){ + AstNode orphan = this.assistNode; + isOrphanCompletionNode = false; + + + /* if in context of a type, then persists the identifier into a fake field return type */ + if (currentElement instanceof RecoveredType){ + RecoveredType recoveredType = (RecoveredType)currentElement; + /* filter out cases where scanner is still inside type header */ + if (recoveredType.foundOpeningBrace) { + /* generate a pseudo field with a completion on type reference */ + if (orphan instanceof TypeReference){ + currentElement = currentElement.add(new SelectionOnFieldType((TypeReference)orphan), 0); + return; + } + } + } + + Statement statement = (Statement)wrapWithExplicitConstructorCallIfNeeded(orphan); + currentElement = currentElement.add(statement, 0); + currentToken = 0; // given we are not on an eof, we do not want side effects caused by looked-ahead token + } +} + +private boolean checkRecoveredType() { + if (currentElement instanceof RecoveredType){ + /* check if current awaiting identifier is the completion identifier */ + if (this.indexOfAssistIdentifier() < 0) return false; + + if ((lastErrorEndPosition >= selectionStart) + && (lastErrorEndPosition <= selectionEnd+1)){ + return false; + } + RecoveredType recoveredType = (RecoveredType)currentElement; + /* filter out cases where scanner is still inside type header */ + if (recoveredType.foundOpeningBrace) { + this.assistNode = this.getTypeReference(0); + this.lastCheckPoint = this.assistNode.sourceEnd + 1; + this.isOrphanCompletionNode = true; + return true; + } + } + return false; +} +protected void classInstanceCreation(boolean alwaysQualified) { + + // 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..... + + int length; + if (((length = astLengthStack[astLengthPtr]) == 1) + && (astStack[astPtr] == null)) { + + if (this.indexOfAssistIdentifier() < 0) { + super.classInstanceCreation(alwaysQualified); + return; + } + QualifiedAllocationExpression alloc; + astPtr--; + astLengthPtr--; + alloc = new SelectionOnQualifiedAllocationExpression(); + alloc.sourceEnd = endPosition; //the position has been stored explicitly + + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy( + expressionStack, + expressionPtr + 1, + alloc.arguments = new Expression[length], + 0, + length); + } + // trick to avoid creating a selection on type reference + char [] oldIdent = this.assistIdentifier(); + this.setAssistIdentifier(null); + alloc.type = getTypeReference(0); + this.setAssistIdentifier(oldIdent); + + //the default constructor with the correct number of argument + //will be created and added by the TC (see createsInternalConstructorWithBinding) + alloc.sourceStart = intStack[intPtr--]; + pushOnExpressionStack(alloc); + + this.assistNode = alloc; + this.lastCheckPoint = alloc.sourceEnd + 1; + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; + } else { + super.classInstanceCreation(alwaysQualified); + } +} + +protected void consumeArrayCreationExpression() { + // ArrayCreationExpression ::= 'new' PrimitiveType DimWithOrWithOutExprs ArrayInitializeropt + // ArrayCreationExpression ::= 'new' ClassOrInterfaceType DimWithOrWithOutExprs ArrayInitializeropt + + super.consumeArrayCreationExpression(); + + ArrayAllocationExpression alloc = (ArrayAllocationExpression)expressionStack[expressionPtr]; + if (alloc.type == assistNode){ + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; + } +} +protected void consumeEnterAnonymousClassBody() { + // EnterAnonymousClassBody ::= $empty + + if (this.indexOfAssistIdentifier() < 0) { + super.consumeEnterAnonymousClassBody(); + return; + } + QualifiedAllocationExpression alloc; + AnonymousLocalTypeDeclaration anonymousType = + new AnonymousLocalTypeDeclaration(this.compilationUnit.compilationResult); + alloc = + anonymousType.allocation = new SelectionOnQualifiedAllocationExpression(anonymousType); + markCurrentMethodWithLocalType(); + pushOnAstStack(anonymousType); + + alloc.sourceEnd = rParenPos; //the position has been stored explicitly + int argumentLength; + if ((argumentLength = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= argumentLength; + System.arraycopy( + expressionStack, + expressionPtr + 1, + alloc.arguments = new Expression[argumentLength], + 0, + argumentLength); + } + // trick to avoid creating a selection on type reference + char [] oldIdent = this.assistIdentifier(); + this.setAssistIdentifier(null); + alloc.type = getTypeReference(0); + this.setAssistIdentifier(oldIdent); + + anonymousType.sourceEnd = alloc.sourceEnd; + //position at the type while it impacts the anonymous declaration + anonymousType.sourceStart = anonymousType.declarationSourceStart = alloc.type.sourceStart; + alloc.sourceStart = intStack[intPtr--]; + pushOnExpressionStack(alloc); + + assistNode = alloc; + this.lastCheckPoint = alloc.sourceEnd + 1; + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; + + anonymousType.bodyStart = scanner.currentPosition; + listLength = 0; // will be updated when reading super-interfaces + // recovery + if (currentElement != null){ + lastCheckPoint = anonymousType.bodyStart; + currentElement = currentElement.add(anonymousType, 0); // the recoveryTokenCheck will deal with the open brace + lastIgnoredToken = -1; + } +} +protected void consumeEnterVariable() { + // EnterVariable ::= $empty + // do nothing by default + + super.consumeEnterVariable(); + + AbstractVariableDeclaration variable = (AbstractVariableDeclaration) astStack[astPtr]; + if (variable.type == assistNode){ + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + isOrphanCompletionNode = false; // already attached inside variable decl + } +} + +protected void consumeExitVariableWithInitialization() { + super.consumeExitVariableWithInitialization(); + + // does not keep the initialization if selection is not inside + AbstractVariableDeclaration variable = (AbstractVariableDeclaration) astStack[astPtr]; + int start = variable.initialization.sourceStart; + int end = variable.initialization.sourceEnd; + if ((selectionStart < start) && (selectionEnd < start) || + (selectionStart > end) && (selectionEnd > end)) { + variable.initialization = null; + } +} + +protected void consumeFieldAccess(boolean isSuperAccess) { + // FieldAccess ::= Primary '.' 'Identifier' + // FieldAccess ::= 'super' '.' 'Identifier' + + if (this.indexOfAssistIdentifier() < 0) { + super.consumeFieldAccess(isSuperAccess); + return; + } + FieldReference fieldReference = + new SelectionOnFieldReference( + identifierStack[identifierPtr], + identifierPositionStack[identifierPtr--]); + identifierLengthPtr--; + if (isSuperAccess) { //considerates the fieldReferenceerence beginning at the 'super' .... + fieldReference.sourceStart = intStack[intPtr--]; + fieldReference.receiver = new SuperReference(fieldReference.sourceStart, endPosition); + pushOnExpressionStack(fieldReference); + } else { //optimize push/pop + if ((fieldReference.receiver = expressionStack[expressionPtr]).isThis()) { //fieldReferenceerence begins at the this + fieldReference.sourceStart = fieldReference.receiver.sourceStart; + } + expressionStack[expressionPtr] = fieldReference; + } + assistNode = fieldReference; + this.lastCheckPoint = fieldReference.sourceEnd + 1; + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; +} +protected void consumeFormalParameter() { + if (this.indexOfAssistIdentifier() < 0) { + super.consumeFormalParameter(); + } else { + + identifierLengthPtr--; + char[] name = identifierStack[identifierPtr]; + long namePositions = identifierPositionStack[identifierPtr--]; + TypeReference type = getTypeReference(intStack[intPtr--] + intStack[intPtr--]); + intPtr -= 2; + Argument arg = + new SelectionOnArgumentName( + name, + namePositions, + type, + intStack[intPtr + 1] & ~AccDeprecated); // modifiers + pushOnAstStack(arg); + + assistNode = arg; + this.lastCheckPoint = (int) namePositions; + isOrphanCompletionNode = true; + + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + + /* if incomplete method header, listLength counter will not have been reset, + indicating that some arguments are available on the stack */ + listLength++; + } +} +protected void consumeInstanceOfExpression(int op) { + if (indexOfAssistIdentifier() < 0) { + super.consumeInstanceOfExpression(op); + } else { + getTypeReference(intStack[intPtr--]); + this.isOrphanCompletionNode = true; + this.restartRecovery = true; + this.lastIgnoredToken = -1; + } +} +protected void consumeMethodInvocationName() { + // MethodInvocation ::= Name '(' ArgumentListopt ')' + + // when the name is only an identifier...we have a message send to "this" (implicit) + + char[] selector = identifierStack[identifierPtr]; + int accessMode; + if(selector == this.assistIdentifier()) { + if(CharOperation.equals(selector, SUPER)) { + accessMode = ExplicitConstructorCall.Super; + } else if(CharOperation.equals(selector, THIS)) { + accessMode = ExplicitConstructorCall.This; + } else { + super.consumeMethodInvocationName(); + return; + } + } else { + super.consumeMethodInvocationName(); + return; + } + + final ExplicitConstructorCall constructorCall = new SelectionOnExplicitConstructorCall(accessMode); + constructorCall.sourceEnd = rParenPos; + constructorCall.sourceStart = (int) (identifierPositionStack[identifierPtr] >>> 32); + int length; + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, constructorCall.arguments = new Expression[length], 0, length); + } + + if (!diet){ + pushOnAstStack(constructorCall); + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } else { + pushOnExpressionStack(new Expression(){ + public TypeBinding resolveType(BlockScope scope) { + constructorCall.resolve(scope); + return null; + } + }); + } + this.assistNode = constructorCall; + this.lastCheckPoint = constructorCall.sourceEnd + 1; + this.isOrphanCompletionNode = true; +} +protected void consumeMethodInvocationPrimary() { + //optimize the push/pop + //MethodInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' + + char[] selector = identifierStack[identifierPtr]; + int accessMode; + if(selector == this.assistIdentifier()) { + if(CharOperation.equals(selector, SUPER)) { + accessMode = ExplicitConstructorCall.Super; + } else if(CharOperation.equals(selector, THIS)) { + accessMode = ExplicitConstructorCall.This; + } else { + super.consumeMethodInvocationPrimary(); + return; + } + } else { + super.consumeMethodInvocationPrimary(); + return; + } + + final ExplicitConstructorCall constructorCall = new SelectionOnExplicitConstructorCall(accessMode); + constructorCall.sourceEnd = rParenPos; + int length; + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy(expressionStack, expressionPtr + 1, constructorCall.arguments = new Expression[length], 0, length); + } + constructorCall.qualification = expressionStack[expressionPtr--]; + constructorCall.sourceStart = constructorCall.qualification.sourceStart; + + if (!diet){ + pushOnAstStack(constructorCall); + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } else { + pushOnExpressionStack(new Expression(){ + public TypeBinding resolveType(BlockScope scope) { + constructorCall.resolve(scope); + return null; + } + }); + } + + this.assistNode = constructorCall; + this.lastCheckPoint = constructorCall.sourceEnd + 1; + this.isOrphanCompletionNode = true; +} +protected void consumeTypeImportOnDemandDeclarationName() { + // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*' + /* push an ImportRef build from the last name + stored in the identifier stack. */ + + int index; + + /* no need to take action if not inside assist identifiers */ + if ((index = indexOfAssistIdentifier()) < 0) { + super.consumeTypeImportOnDemandDeclarationName(); + return; + } + /* retrieve identifiers subset and whole positions, the assist node positions + should include the entire replaced source. */ + int length = identifierLengthStack[identifierLengthPtr]; + char[][] subset = identifierSubSet(index+1); // include the assistIdentifier + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + + /* build specific assist node on import statement */ + ImportReference reference = this.createAssistImportReference(subset, positions); + reference.onDemand = true; + assistNode = reference; + this.lastCheckPoint = reference.sourceEnd + 1; + + pushOnAstStack(reference); + + if (currentToken == TokenNameSEMICOLON){ + reference.declarationSourceEnd = scanner.currentPosition - 1; + } else { + reference.declarationSourceEnd = (int) positions[length-1]; + } + //endPosition is just before the ; + reference.declarationSourceStart = intStack[intPtr--]; + // flush annotations defined prior to import statements + reference.declarationSourceEnd = this.flushAnnotationsDefinedPriorTo(reference.declarationSourceEnd); + + // recovery + if (currentElement != null){ + lastCheckPoint = reference.declarationSourceEnd+1; + currentElement = currentElement.add(reference, 0); + lastIgnoredToken = -1; + restartRecovery = true; // used to avoid branching back into the regular automaton + } +} +public ImportReference createAssistImportReference(char[][] tokens, long[] positions){ + return new SelectionOnImportReference(tokens, positions); +} +public ImportReference createAssistPackageReference(char[][] tokens, long[] positions){ + return new SelectionOnPackageReference(tokens, positions); +} +protected LocalDeclaration createLocalDeclaration(Expression initialization,char[] name,int sourceStart,int sourceEnd) { + if (this.indexOfAssistIdentifier() < 0) { + return super.createLocalDeclaration(initialization, name, sourceStart, sourceEnd); + } else { + SelectionOnLocalName local = new SelectionOnLocalName(initialization, name, sourceStart, sourceEnd); + this.assistNode = local; + this.lastCheckPoint = sourceEnd + 1; + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + return local; + } +} +public NameReference createQualifiedAssistNameReference(char[][] previousIdentifiers, char[] name, long[] positions){ + return new SelectionOnQualifiedNameReference( + previousIdentifiers, + name, + positions); +} +public TypeReference createQualifiedAssistTypeReference(char[][] previousIdentifiers, char[] name, long[] positions){ + return new SelectionOnQualifiedTypeReference( + previousIdentifiers, + name, + positions); +} +public NameReference createSingleAssistNameReference(char[] name, long position) { + return new SelectionOnSingleNameReference(name, position); +} +public TypeReference createSingleAssistTypeReference(char[] name, long position) { + return new SelectionOnSingleTypeReference(name, position); +} +public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int selectionStart, int selectionEnd) { + + this.selectionStart = selectionStart; + this.selectionEnd = selectionEnd; + SelectionScanner selectionScanner = (SelectionScanner)this.scanner; + selectionScanner.selectionIdentifier = null; + selectionScanner.selectionStart = selectionStart; + selectionScanner.selectionEnd = selectionEnd; + return this.dietParse(sourceUnit, compilationResult); +} +protected NameReference getUnspecifiedReference() { + /* build a (unspecified) NameReference which may be qualified*/ + + int completionIndex; + + /* no need to take action if not inside completed identifiers */ + if ((completionIndex = indexOfAssistIdentifier()) < 0) { + return super.getUnspecifiedReference(); + } + + int length = identifierLengthStack[identifierLengthPtr]; + if (CharOperation.equals(assistIdentifier(), SUPER)){ + Reference reference; + if (completionIndex > 0){ // qualified super + // discard 'super' from identifier stacks + identifierLengthStack[identifierLengthPtr] = completionIndex; + int ptr = identifierPtr -= (length - completionIndex); + reference = + new SelectionOnQualifiedSuperReference( + getTypeReference(0), + (int)(identifierPositionStack[ptr+1] >>> 32), + (int) identifierPositionStack[ptr+1]); + } else { // standard super + identifierPtr -= length; + identifierLengthPtr--; + reference = new SelectionOnSuperReference((int)(identifierPositionStack[identifierPtr+1] >>> 32), (int) identifierPositionStack[identifierPtr+1]); + } + pushOnAstStack(reference); + this.assistNode = reference; + this.lastCheckPoint = reference.sourceEnd + 1; + if (!diet || dietInt != 0){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; + return new SingleNameReference(new char[0], 0); // dummy reference + } + NameReference nameReference; + /* retrieve identifiers subset and whole positions, the completion node positions + should include the entire replaced source. */ + char[][] subset = identifierSubSet(completionIndex); + identifierLengthPtr--; + identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy( + identifierPositionStack, + identifierPtr + 1, + positions, + 0, + length); + /* build specific completion on name reference */ + if (completionIndex == 0) { + /* completion inside first identifier */ + nameReference = this.createSingleAssistNameReference(assistIdentifier(), positions[0]); + } else { + /* completion inside subsequent identifier */ + nameReference = this.createQualifiedAssistNameReference(subset, assistIdentifier(), positions); + } + assistNode = nameReference; + this.lastCheckPoint = nameReference.sourceEnd + 1; + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; + return nameReference; +} +/* + * Copy of code from superclass with the following change: + * In the case of qualified name reference if the cursor location is on the + * qualified name reference, then create a CompletionOnQualifiedNameReference + * instead. + */ +protected NameReference getUnspecifiedReferenceOptimized() { + + int index = indexOfAssistIdentifier(); + NameReference reference = super.getUnspecifiedReferenceOptimized(); + + if (index >= 0){ + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + this.isOrphanCompletionNode = true; + } + return reference; +} +public void initializeScanner(){ + this.scanner = new SelectionScanner(this.assertMode); +} +protected MessageSend newMessageSend() { + // '(' ArgumentListopt ')' + // the arguments are on the expression stack + + char[] selector = identifierStack[identifierPtr]; + if (selector != this.assistIdentifier()){ + return super.newMessageSend(); + } + MessageSend messageSend = new SelectionOnMessageSend(); + int length; + if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) { + expressionPtr -= length; + System.arraycopy( + expressionStack, + expressionPtr + 1, + messageSend.arguments = new Expression[length], + 0, + length); + }; + assistNode = messageSend; + if (!diet){ + this.restartRecovery = true; // force to restart in recovery mode + this.lastIgnoredToken = -1; + } + + this.isOrphanCompletionNode = true; + return messageSend; +} +public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult, int selectionStart, int selectionEnd) { + + this.selectionStart = selectionStart; + this.selectionEnd = selectionEnd; + SelectionScanner selectionScanner = (SelectionScanner)this.scanner; + selectionScanner.selectionIdentifier = null; + selectionScanner.selectionStart = selectionStart; + selectionScanner.selectionEnd = selectionEnd; + return this.parse(sourceUnit, compilationResult); +} +/* + * Reset context so as to resume to regular parse loop + * If unable to reset for resuming, answers false. + * + * Move checkpoint location, reset internal stacks and + * decide which grammar goal is activated. + */ +protected boolean resumeAfterRecovery() { + + /* if reached assist node inside method body, but still inside nested type, + should continue in diet mode until the end of the method body */ + if (this.assistNode != null + && !(referenceContext instanceof CompilationUnitDeclaration)){ + currentElement.preserveEnclosingBlocks(); + if (currentElement.enclosingType() == null){ + this.resetStacks(); + return false; + } + } + return super.resumeAfterRecovery(); +} + +public void selectionIdentifierCheck(){ + if (checkRecoveredType()) return; +} +public void setAssistIdentifier(char[] assistIdent){ + ((SelectionScanner)scanner).selectionIdentifier = assistIdent; +} +/* + * Update recovery state based on current parser/scanner state + */ +protected void updateRecoveryState() { + + /* expose parser state to recovery state */ + currentElement.updateFromParserState(); + + /* may be able to retrieve completionNode as an orphan, and then attach it */ + this.selectionIdentifierCheck(); + this.attachOrphanCompletionNode(); + + /* check and update recovered state based on current token, + this action is also performed when shifting token after recovery + got activated once. + */ + this.recoveryTokenCheck(); +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionScanner.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionScanner.java new file mode 100644 index 0000000..fafb5e7 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/select/SelectionScanner.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.codeassist.select; + +/* + * Scanner aware of a selection range. If finding an identifier which source range is exactly + * the same, then will record it so that the parser can make use of it. + * + * Source positions are zero-based and inclusive. + */ +import net.sourceforge.phpdt.core.compiler.InvalidInputException; +import net.sourceforge.phpdt.internal.compiler.parser.Scanner; + +public class SelectionScanner extends Scanner { + + public char[] selectionIdentifier; + public int selectionStart, selectionEnd; +/* + * Truncate the current identifier if it is containing the cursor location. Since completion is performed + * on an identifier prefix. + * + */ + +public SelectionScanner(boolean assertMode) { + super(false, false, false, assertMode); +} + +public char[] getCurrentIdentifierSource() { + + if (selectionIdentifier == null){ + if (selectionStart == startPosition && selectionEnd == currentPosition-1){ + if (withoutUnicodePtr != 0){ // check unicode scenario + System.arraycopy(withoutUnicodeBuffer, 1, selectionIdentifier = new char[withoutUnicodePtr], 0, withoutUnicodePtr); + } else { + int length = currentPosition - startPosition; + // no char[] sharing around completionIdentifier, we want it to be unique so as to use identity checks + System.arraycopy(source, startPosition, (selectionIdentifier = new char[length]), 0, length); + } + return selectionIdentifier; + } + } + return super.getCurrentIdentifierSource(); +} +/* + * In case we actually read a keyword which corresponds to the selected + * range, we pretend we read an identifier. + */ +public int scanIdentifierOrKeyword() throws InvalidInputException { + + int id = super.scanIdentifierOrKeyword(); + + // convert completed keyword into an identifier + if (id != TokenNameIdentifier + && startPosition == selectionStart + && currentPosition == selectionEnd+1){ + return TokenNameIdentifier; + } + return id; +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java new file mode 100644 index 0000000..cbc4cbb --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BasicCompilationUnit.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.core; + +import java.io.File; +import java.io.IOException; + +import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit; +import net.sourceforge.phpdt.internal.compiler.util.Util; + +/** + * A basic implementation of ICompilationUnit + * for use in the SourceMapper. + * @see ICompilationUnit + */ +public class BasicCompilationUnit implements ICompilationUnit { + protected char[] contents; + protected char[] fileName; + protected char[][] packageName; + protected char[] mainTypeName; + protected String encoding; + +public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, String encoding) { + this.contents = contents; + this.fileName = fileName.toCharArray(); + this.packageName = packageName; + + int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$ + if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$ + start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$ + + int end = fileName.lastIndexOf("."); //$NON-NLS-1$ + if (end == -1) + end = fileName.length(); + + this.mainTypeName = fileName.substring(start, end).toCharArray(); + this.encoding = encoding; +} +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(fileName)), this.encoding); + } catch (IOException e) { + } + return new char[0]; +} +public char[] getFileName() { + return this.fileName; +} +public char[] getMainTypeName() { + return this.mainTypeName; +} +public char[][] getPackageName() { + return this.packageName; +} +public String toString(){ + return "CompilationUnit: "+new String(fileName); //$NON-NLS-1$ +} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java new file mode 100644 index 0000000..ef69dd2 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementInfo.java @@ -0,0 +1,128 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.core; + +import net.sourceforge.phpdt.core.IJavaElement; + +/** + * Holds cached structure and properties for a Java element. + * Subclassed to carry properties for specific kinds of elements. + */ +/* package */ class JavaElementInfo { + + /** + * Collection of handles of immediate children of this + * object. This is an empty array if this element has + * no children. + */ + protected IJavaElement[] fChildren; + + /** + * Shared empty collection used for efficiency. + */ + protected static IJavaElement[] fgEmptyChildren = new IJavaElement[]{}; + /** + * Is the structure of this element known + * @see IJavaElement#isStructureKnown() + */ + protected boolean fIsStructureKnown = false; + + /** + * Shared empty collection used for efficiency. + */ + static Object[] NO_NON_JAVA_RESOURCES = new Object[] {}; + protected JavaElementInfo() { + fChildren = fgEmptyChildren; + } + public void addChild(IJavaElement child) { + if (fChildren == fgEmptyChildren) { + setChildren(new IJavaElement[] {child}); + } else { + if (!includesChild(child)) { + setChildren(growAndAddToArray(fChildren, child)); + } + } + } + public Object clone() { + try { + return super.clone(); + } + catch (CloneNotSupportedException e) { + throw new Error(); + } + } + public IJavaElement[] getChildren() { + return fChildren; + } + /** + * Adds the new element to a new array that contains all of the elements of the old array. + * Returns the new array. + */ + protected IJavaElement[] growAndAddToArray(IJavaElement[] array, IJavaElement addition) { + IJavaElement[] old = array; + array = new IJavaElement[old.length + 1]; + System.arraycopy(old, 0, array, 0, old.length); + array[old.length] = addition; + return array; + } + /** + * Returns true if this child is in my children collection + */ + protected boolean includesChild(IJavaElement child) { + + for (int i= 0; i < fChildren.length; i++) { + if (fChildren[i].equals(child)) { + return true; + } + } + return false; + } + /** + * @see IJavaElement#isStructureKnown() + */ + public boolean isStructureKnown() { + return fIsStructureKnown; + } + /** + * Returns an array with all the same elements as the specified array except for + * the element to remove. Assumes that the deletion is contained in the array. + */ + protected IJavaElement[] removeAndShrinkArray(IJavaElement[] array, IJavaElement deletion) { + IJavaElement[] old = array; + array = new IJavaElement[old.length - 1]; + int j = 0; + for (int i = 0; i < old.length; i++) { + if (!old[i].equals(deletion)) { + array[j] = old[i]; + } else { + System.arraycopy(old, i + 1, array, j, old.length - (i + 1)); + return array; + } + j++; + } + return array; + } + public void removeChild(IJavaElement child) { + if (includesChild(child)) { + setChildren(removeAndShrinkArray(fChildren, child)); + } + } + public void setChildren(IJavaElement[] children) { + fChildren = children; + } + /** + * Sets whether the structure of this element known + * @see IJavaElement#isStructureKnown() + */ + public void setIsStructureKnown(boolean newIsStructureKnown) { + fIsStructureKnown = newIsStructureKnown; + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java new file mode 100644 index 0000000..3945211 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelStatus.java @@ -0,0 +1,327 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.core; + +import org.eclipse.core.resources.IResourceStatus; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; + +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IJavaModelStatus; +import net.sourceforge.phpdt.core.IJavaModelStatusConstants; +//import net.sourceforge.phpdt.core.IPackageFragment; +//import net.sourceforge.phpdt.core.JavaCore; + +/** + * @see IJavaModelStatus + */ + +public class JavaModelStatus extends Status implements IJavaModelStatus, IJavaModelStatusConstants, IResourceStatus { + + /** + * The elements related to the failure, or null + * if no elements are involved. + */ + protected IJavaElement[] fElements = new IJavaElement[0]; + /** + * The path related to the failure, or null + * if no path is involved. + */ + protected IPath fPath; + /** + * The String related to the failure, or null + * if no String is involved. + */ + protected String fString; + /** + * Empty children + */ + protected final static IStatus[] fgEmptyChildren = new IStatus[] {}; + protected IStatus[] fChildren= fgEmptyChildren; + + /** + * Singleton OK object + */ + public static final IJavaModelStatus VERIFIED_OK = new JavaModelStatus(OK); + + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus() { + // no code for an multi-status + super(ERROR, PHPeclipsePlugin.PLUGIN_ID, 0, "JavaModelStatus", null); //$NON-NLS-1$ + } + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(int code) { + super(ERROR, PHPeclipsePlugin.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ + fElements= JavaElementInfo.fgEmptyChildren; + } +// /** +// * Constructs an Java model status with the given corresponding +// * elements. +// */ +// public JavaModelStatus(int code, IJavaElement[] elements) { +// super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ +// fElements= elements; +// fPath= null; +// } + /** + * Constructs an Java model status with no corresponding elements. + */ +// public JavaModelStatus(int code, String string) { +// super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ +// fElements= JavaElementInfo.fgEmptyChildren; +// fPath= null; +// fString = string; +// } +// /** +// * Constructs an Java model status with no corresponding elements. +// */ + public JavaModelStatus(int code, Throwable throwable) { + super(ERROR, PHPeclipsePlugin.PLUGIN_ID, code, "JavaModelStatus", throwable); //$NON-NLS-1$ + fElements= JavaElementInfo.fgEmptyChildren; + } +// /** +// * Constructs an Java model status with no corresponding elements. +// */ +// public JavaModelStatus(int code, IPath path) { +// super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null); //$NON-NLS-1$ +// fElements= JavaElementInfo.fgEmptyChildren; +// fPath= path; +// } + /** + * Constructs an Java model status with the given corresponding + * element. + */ +// public JavaModelStatus(int code, IJavaElement element) { +// this(code, new IJavaElement[]{element}); +// } +// /** +// * Constructs an Java model status with the given corresponding +// * element and string +// */ +// public JavaModelStatus(int code, IJavaElement element, String string) { +// this(code, new IJavaElement[]{element}); +// fString= string; +// } + /** + * Constructs an Java model status with no corresponding elements. + */ + public JavaModelStatus(CoreException coreException) { + super(ERROR, PHPeclipsePlugin.PLUGIN_ID, CORE_EXCEPTION, "JavaModelStatus", coreException); //$NON-NLS-1$ + fElements= JavaElementInfo.fgEmptyChildren; + } + protected int getBits() { + int severity = 1 << (getCode() % 100 / 33); + int category = 1 << ((getCode() / 100) + 3); + return severity | category; + } + /** + * @see IStatus + */ + public IStatus[] getChildren() { + return fChildren; + } + /** + * @see IJavaModelStatus + */ + public IJavaElement[] getElements() { + return fElements; + } + /** + * Returns the message that is relevant to the code of this status. + */ +// public String getMessage() { +// if (getException() == null) { +// switch (getCode()) { +// case CORE_EXCEPTION : +// return Util.bind("status.coreException"); //$NON-NLS-1$ +// case BUILDER_INITIALIZATION_ERROR: +// return Util.bind("build.initializationError"); //$NON-NLS-1$ +// case BUILDER_SERIALIZATION_ERROR: +// return Util.bind("build.serializationError"); //$NON-NLS-1$ +// case DEVICE_PATH: +// return Util.bind("status.cannotUseDeviceOnPath", getPath().toString()); //$NON-NLS-1$ +// case DOM_EXCEPTION: +// return Util.bind("status.JDOMError"); //$NON-NLS-1$ +// case ELEMENT_DOES_NOT_EXIST: +// return Util.bind("element.doesNotExist",fElements[0].getElementName()); //$NON-NLS-1$ +// case EVALUATION_ERROR: +// return Util.bind("status.evaluationError", getString()); //$NON-NLS-1$ +// case INDEX_OUT_OF_BOUNDS: +// return Util.bind("status.indexOutOfBounds"); //$NON-NLS-1$ +// case INVALID_CONTENTS: +// return Util.bind("status.invalidContents"); //$NON-NLS-1$ +// case INVALID_DESTINATION: +// return Util.bind("status.invalidDestination", fElements[0].getElementName()); //$NON-NLS-1$ +// case INVALID_ELEMENT_TYPES: +// StringBuffer buff= new StringBuffer(Util.bind("operation.notSupported")); //$NON-NLS-1$ +// for (int i= 0; i < fElements.length; i++) { +// if (i > 0) { +// buff.append(", "); //$NON-NLS-1$ +// } +// buff.append(fElements[0].getElementName()); +// } +// return buff.toString(); +// case INVALID_NAME: +// return Util.bind("status.invalidName", getString()); //$NON-NLS-1$ +// case INVALID_PACKAGE: +// return Util.bind("status.invalidPackage", getString()); //$NON-NLS-1$ +// case INVALID_PATH: +// return Util.bind("status.invalidPath", getPath() == null ? "null" : getPath().toString()); //$NON-NLS-1$ //$NON-NLS-2$ +// case INVALID_PROJECT: +// return Util.bind("status.invalidProject", getString()); //$NON-NLS-1$ +// case INVALID_RESOURCE: +// return Util.bind("status.invalidResource", getString()); //$NON-NLS-1$ +// case INVALID_RESOURCE_TYPE: +// return Util.bind("status.invalidResourceType", getString()); //$NON-NLS-1$ +// case INVALID_SIBLING: +// return Util.bind("status.invalidSibling", fElements[0].getElementName()); //$NON-NLS-1$ +// case IO_EXCEPTION: +// return Util.bind("status.IOException"); //$NON-NLS-1$ +// case NAME_COLLISION: +// if (fElements != null && fElements.length > 0) { +// IJavaElement element = fElements[0]; +// String name = element.getElementName(); +// if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { +// return Util.bind("operation.cannotRenameDefaultPackage"); //$NON-NLS-1$ +// } +// } +// return Util.bind("status.nameCollision"); //$NON-NLS-1$ +// case NO_ELEMENTS_TO_PROCESS: +// return Util.bind("operation.needElements"); //$NON-NLS-1$ +// case NULL_NAME: +// return Util.bind("operation.needName"); //$NON-NLS-1$ +// case NULL_PATH: +// return Util.bind("operation.needPath"); //$NON-NLS-1$ +// case NULL_STRING: +// return Util.bind("operation.needString"); //$NON-NLS-1$ +// case PATH_OUTSIDE_PROJECT: +// return Util.bind("operation.pathOutsideProject", getString(), fElements[0].getElementName()); //$NON-NLS-1$ +// case READ_ONLY: +// IJavaElement element = fElements[0]; +// String name = element.getElementName(); +// if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) { +// return Util.bind("status.defaultPackageReadOnly"); //$NON-NLS-1$ +// } +// return Util.bind("status.readOnly", name); //$NON-NLS-1$ +// case RELATIVE_PATH: +// return Util.bind("operation.needAbsolutePath", getPath().toString()); //$NON-NLS-1$ +// case TARGET_EXCEPTION: +// return Util.bind("status.targetException"); //$NON-NLS-1$ +// case UPDATE_CONFLICT: +// return Util.bind("status.updateConflict"); //$NON-NLS-1$ +// case NO_LOCAL_CONTENTS : +// return Util.bind("status.noLocalContents", getPath().toString()); //$NON-NLS-1$ +// } +// return getString(); +// } else { +// return getException().getMessage(); +// } +// } + /** + * @see IJavaModelStatus#getPath() + */ + public IPath getPath() { + return fPath; + } + /** + * @see IStatus#getSeverity() + */ + public int getSeverity() { + if (fChildren == fgEmptyChildren) return super.getSeverity(); + int severity = -1; + for (int i = 0, max = fChildren.length; i < max; i++) { + int childrenSeverity = fChildren[i].getSeverity(); + if (childrenSeverity > severity) { + severity = childrenSeverity; + } + } + return severity; + } + /** + * @see IJavaModelStatus#getString() + */ + public String getString() { + return fString; + } + /** + * @see IJavaModelStatus#isDoesNotExist() + */ + public boolean isDoesNotExist() { + return getCode() == ELEMENT_DOES_NOT_EXIST; + } + /** + * @see IStatus#isMultiStatus() + */ + public boolean isMultiStatus() { + return fChildren != fgEmptyChildren; + } + /** + * @see IStatus#isOK() + */ + public boolean isOK() { + return getCode() == OK; + } + /** + * @see IStatus#matches(int) + */ + public boolean matches(int mask) { + if (! isMultiStatus()) { + return matches(this, mask); + } else { + for (int i = 0, max = fChildren.length; i < max; i++) { + if (matches((JavaModelStatus) fChildren[i], mask)) + return true; + } + return false; + } + } + /** + * Helper for matches(int). + */ + protected boolean matches(JavaModelStatus status, int mask) { + int severityMask = mask & 0x7; + int categoryMask = mask & ~0x7; + int bits = status.getBits(); + return ((severityMask == 0) || (bits & severityMask) != 0) && ((categoryMask == 0) || (bits & categoryMask) != 0); + } + /** + * Creates and returns a new IJavaModelStatus that is a + * a multi-status status. + * + * @see IStatus#isMultiStatus() + */ + public static IJavaModelStatus newMultiStatus(IJavaModelStatus[] children) { + JavaModelStatus jms = new JavaModelStatus(); + jms.fChildren = children; + return jms; + } + /** + * Returns a printable representation of this exception for debugging + * purposes. + */ + public String toString() { + if (this == VERIFIED_OK){ + return "JavaModelStatus[OK]"; //$NON-NLS-1$ + } + StringBuffer buffer = new StringBuffer(); + buffer.append("Java Model Status ["); //$NON-NLS-1$ + buffer.append(getMessage()); + buffer.append("]"); //$NON-NLS-1$ + return buffer.toString(); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeConverter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeConverter.java new file mode 100644 index 0000000..dc7ef2a --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/TypeConverter.java @@ -0,0 +1,245 @@ +/******************************************************************************* + * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v0.5 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v05.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ +package net.sourceforge.phpdt.internal.core; + +import net.sourceforge.phpdt.core.IField; +import net.sourceforge.phpdt.core.IMethod; +import net.sourceforge.phpdt.core.IType; +import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.Signature; +import net.sourceforge.phpdt.internal.compiler.CompilationResult; +import net.sourceforge.phpdt.internal.compiler.ast.AbstractMethodDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.Argument; +import net.sourceforge.phpdt.internal.compiler.ast.ArrayQualifiedTypeReference; +import net.sourceforge.phpdt.internal.compiler.ast.ArrayTypeReference; +import net.sourceforge.phpdt.internal.compiler.ast.CompilationUnitDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.ConstructorDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.FieldDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.ImportReference; +import net.sourceforge.phpdt.internal.compiler.ast.MemberTypeDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.MethodDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.QualifiedTypeReference; +import net.sourceforge.phpdt.internal.compiler.ast.SingleTypeReference; +import net.sourceforge.phpdt.internal.compiler.ast.TypeDeclaration; +import net.sourceforge.phpdt.internal.compiler.ast.TypeReference; +import net.sourceforge.phpdt.internal.compiler.lookup.CompilerModifiers; +import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter; +import net.sourceforge.phpdt.internal.compiler.util.CharOperation; + +/** + * Converter from a type to an AST type declaration. + */ +public class TypeConverter { + + /** + * Convert a type into an AST type declaration and put it in the given compilation unit. + */ +// public static TypeDeclaration buildTypeDeclaration(IType type, CompilationUnitDeclaration compilationUnit, CompilationResult compilationResult, ProblemReporter problemReporter) throws JavaModelException { +// char[] packageName = type.getPackageFragment().getElementName().toCharArray(); +// +// if (packageName != null && packageName.length > 0) { +// compilationUnit.currentPackage = new ImportReference(CharOperation.splitOn('.', packageName), new long[]{0}, false); +// } +// +// /* convert type */ +// TypeDeclaration typeDeclaration = convert(type, null, null, compilationResult); +// +// IType alreadyComputedMember = type; +// IType parent = type.getDeclaringType(); +// TypeDeclaration previousDeclaration = typeDeclaration; +// while(parent != null) { +// TypeDeclaration declaration = convert(parent, alreadyComputedMember, (MemberTypeDeclaration)previousDeclaration, compilationResult); +// +// alreadyComputedMember = parent; +// previousDeclaration = declaration; +// parent = parent.getDeclaringType(); +// } +// +// compilationUnit.types = new TypeDeclaration[]{previousDeclaration}; +// +// return typeDeclaration; +// } + + private static FieldDeclaration convert(IField field, IType type) throws JavaModelException { + + FieldDeclaration fieldDeclaration = new FieldDeclaration(); + + fieldDeclaration.name = field.getElementName().toCharArray(); + fieldDeclaration.type = createTypeReference(Signature.toString(field.getTypeSignature()).toCharArray(), type); + fieldDeclaration.modifiers = field.getFlags(); + + return fieldDeclaration; + } + + private static AbstractMethodDeclaration convert(IMethod method, IType type, CompilationResult compilationResult) throws JavaModelException { + + AbstractMethodDeclaration methodDeclaration; + + if (method.isConstructor()) { + ConstructorDeclaration decl = new ConstructorDeclaration(compilationResult); + decl.isDefaultConstructor = false; + methodDeclaration = decl; + } else { + MethodDeclaration decl = new MethodDeclaration(compilationResult); + /* convert return type */ + decl.returnType = createTypeReference(Signature.toString(method.getReturnType()).toCharArray(), type); + methodDeclaration = decl; + } + methodDeclaration.selector = method.getElementName().toCharArray(); + methodDeclaration.modifiers = method.getFlags(); + + /* convert arguments */ + String[] argumentTypeNames = method.getParameterTypes(); + String[] argumentNames = method.getParameterNames(); + int argumentCount = argumentTypeNames == null ? 0 : argumentTypeNames.length; + methodDeclaration.arguments = new Argument[argumentCount]; + for (int i = 0; i < argumentCount; i++) { + methodDeclaration.arguments[i] = new Argument( + argumentNames[i].toCharArray(), + 0, + createTypeReference(Signature.toString(argumentTypeNames[i]).toCharArray(), type), + CompilerModifiers.AccDefault); + // do not care whether was final or not + } + + /* convert thrown exceptions */ + String[] exceptionTypeNames = method.getExceptionTypes(); + int exceptionCount = exceptionTypeNames == null ? 0 : exceptionTypeNames.length; + if(exceptionCount > 0) { + methodDeclaration.thrownExceptions = new TypeReference[exceptionCount]; + for (int i = 0; i < exceptionCount; i++) { + methodDeclaration.thrownExceptions[i] = + createTypeReference(Signature.toString(exceptionTypeNames[i]).toCharArray(), type); + } + } + return methodDeclaration; + } + + private static TypeDeclaration convert(IType type, IType alreadyComputedMember,MemberTypeDeclaration alreadyComputedMemberDeclaration, CompilationResult compilationResult) throws JavaModelException { + /* create type declaration - can be member type */ + TypeDeclaration typeDeclaration; + if (type.getDeclaringType() == null) { + typeDeclaration = new TypeDeclaration(compilationResult); + } else { + typeDeclaration = new MemberTypeDeclaration(compilationResult); + } + typeDeclaration.name = type.getElementName().toCharArray(); + typeDeclaration.modifiers = type.getFlags(); + + + /* set superclass and superinterfaces */ + if (type.getSuperclassName() != null) { + typeDeclaration.superclass = createTypeReference(type.getSuperclassName().toCharArray(), type); + } + String[] interfaceNames = type.getSuperInterfaceNames(); + int interfaceCount = interfaceNames == null ? 0 : interfaceNames.length; + typeDeclaration.superInterfaces = new TypeReference[interfaceCount]; + for (int i = 0; i < interfaceCount; i++) { + typeDeclaration.superInterfaces[i] = createTypeReference(interfaceNames[i].toCharArray(), type); + } + + /* convert member types */ + IType[] memberTypes = type.getTypes(); + int memberTypeCount = memberTypes == null ? 0 : memberTypes.length; + typeDeclaration.memberTypes = new MemberTypeDeclaration[memberTypeCount]; + for (int i = 0; i < memberTypeCount; i++) { + if(alreadyComputedMember != null && alreadyComputedMember.getFullyQualifiedName().equals(memberTypes[i].getFullyQualifiedName())) { + typeDeclaration.memberTypes[i] = alreadyComputedMemberDeclaration; + } else { + typeDeclaration.memberTypes[i] = + (MemberTypeDeclaration) convert(memberTypes[i], null, null, compilationResult); + } + } + + /* convert fields */ + IField[] fields = type.getFields(); + int fieldCount = fields == null ? 0 : fields.length; + typeDeclaration.fields = new FieldDeclaration[fieldCount]; + for (int i = 0; i < fieldCount; i++) { + typeDeclaration.fields[i] = convert(fields[i], type); + } + + /* convert methods - need to add default constructor if necessary */ + IMethod[] methods = type.getMethods(); + int methodCount = methods == null ? 0 : methods.length; + + /* source type has a constructor ? */ + /* by default, we assume that one is needed. */ + int neededCount = 1; + for (int i = 0; i < methodCount; i++) { + if (methods[i].isConstructor()) { + neededCount = 0; + // Does not need the extra constructor since one constructor already exists. + break; + } + } + typeDeclaration.methods = new AbstractMethodDeclaration[methodCount + neededCount]; + if (neededCount != 0) { // add default constructor in first position + typeDeclaration.methods[0] = typeDeclaration.createsInternalConstructor(false, false); + } + boolean isInterface = type.isInterface(); + for (int i = 0; i < methodCount; i++) { + AbstractMethodDeclaration method =convert(methods[i], type, compilationResult); + if (isInterface || method.isAbstract()) { // fix-up flag + method.modifiers |= CompilerModifiers.AccSemicolonBody; + } + typeDeclaration.methods[neededCount + i] = method; + } + return typeDeclaration; + } + + private static TypeReference createTypeReference(char[] type, IType contextType) { + try { + String[][] resolvedName = contextType.resolveType(new String(type)); + char[] superClassName = null; + if(resolvedName != null && resolvedName.length == 1) { + type= CharOperation.concat(resolvedName[0][0].toCharArray(), resolvedName[0][1].toCharArray(), '.'); + } + } catch (JavaModelException e) { + + } + + /* count identifiers and dimensions */ + int max = type.length; + int dimStart = max; + int dim = 0; + int identCount = 1; + for (int i = 0; i < max; i++) { + switch (type[i]) { + case '[' : + if (dim == 0) + dimStart = i; + dim++; + break; + case '.' : + identCount++; + break; + } + } + /* rebuild identifiers and dimensions */ + if (identCount == 1) { // simple type reference + if (dim == 0) { + return new SingleTypeReference(type, 0); + } else { + char[] identifier = new char[dimStart]; + System.arraycopy(type, 0, identifier, 0, dimStart); + return new ArrayTypeReference(identifier, dim, 0); + } + } else { // qualified type reference + char[][] identifiers = CharOperation.splitOn('.', type, 0, dimStart - 1); + if (dim == 0) { + return new QualifiedTypeReference(identifiers, new long[]{0}); + } else { + return new ArrayQualifiedTypeReference(identifiers, dim, new long[]{0}); + } + } + } +} -- 1.7.1 From 44a43315b9015552f0b198badf0983dbfc39e38c Mon Sep 17 00:00:00 2001 From: khartlage Date: Thu, 30 Jan 2003 20:07:47 +0000 Subject: [PATCH 14/16] new html templates --- .../internal/corext/template/default-templates.xml | 67 +++++++++++++++++++- 1 files changed, 64 insertions(+), 3 deletions(-) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/default-templates.xml b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/default-templates.xml index 287f71a..8696cb5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/default-templates.xml +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/default-templates.xml @@ -121,11 +121,72 @@ -