Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPhilipe Mulet2001-08-08 19:01:30 +0000
committerPhilipe Mulet2001-08-08 19:01:30 +0000
commita3aa7d6a20313fec5f40ade15850401f2659cfd4 (patch)
tree7ad6421ffcbf16ebe4730dfef28439208f02b0f0
parent4d25a674b4e5705e8102342b077bebde5e2c3b54 (diff)
downloadeclipse.jdt.core-a3aa7d6a20313fec5f40ade15850401f2659cfd4.tar.gz
eclipse.jdt.core-a3aa7d6a20313fec5f40ade15850401f2659cfd4.tar.xz
eclipse.jdt.core-a3aa7d6a20313fec5f40ade15850401f2659cfd4.zip
129_04_synchronize_with_stream
-rw-r--r--org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java183
-rw-r--r--org.eclipse.jdt.core/changes.txt8
-rw-r--r--org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java27
-rw-r--r--org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ConfigurableOption.java667
-rw-r--r--org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java667
-rw-r--r--org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/ConfigurableProblems.java1
-rw-r--r--org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java2
-rw-r--r--org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java3836
-rw-r--r--org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java96
-rw-r--r--org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java4
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java9
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java2040
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java3
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java379
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties1
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java5
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java989
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java2
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java1
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java3
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java2
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java24
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java158
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java11
-rw-r--r--org.eclipse.jdt.core/plugin.jars9
25 files changed, 4956 insertions, 4171 deletions
diff --git a/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java b/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java
index 8ed6d50395..a332b3c3a4 100644
--- a/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java
+++ b/org.eclipse.jdt.core/batch/org/eclipse/jdt/internal/compiler/batch/Main.java
@@ -20,28 +20,32 @@ import java.io.*;
import java.util.*;
public class Main implements ConfigurableProblems, ProblemSeverities {
+ private ConfigurableOption[] options;
+ private static final String[] problemOption ={
+ CompilerOptions.OPTION_ReportMethodWithConstructorName,
+ CompilerOptions.OPTION_ReportHiddenCatchBlock,
+ CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
+ CompilerOptions.OPTION_ReportDeprecation,
+ CompilerOptions.OPTION_ReportUnusedLocal,
+ CompilerOptions.OPTION_ReportUnusedParameter,
+ CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
+ CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
+ CompilerOptions.OPTION_ReportInvalidImport,
+ CompilerOptions.OPTION_ReportUnreachableCode,
+ CompilerOptions.OPTION_ReportAssertIdentifier,
+ };
+ private boolean noWarn = false;
+
PrintWriter out;
boolean systemExitWhenFinished = true;
boolean proceedOnError = false;
- int warningMask =
- ParsingOptionalError |
- MethodWithConstructorName | OverriddenPackageDefaultMethod |
- UsingDeprecatedAPI | MaskedCatchBlock |
- UnusedLocalVariable | UnusedArgument |
- TemporaryWarning | OverriddenPackageDefaultMethod |
- AccessEmulation;
- int debugMask = CompilerOptions.Lines | CompilerOptions.Source;
- int targetJDK = CompilerOptions.JDK1_1;
- boolean assertMode = false;
boolean verbose = false;
boolean produceRefInfo = false;
- boolean importProblemIsError = true;
boolean timer = false;
boolean showProgress = false;
public long time = 0;
long lineCount;
- boolean preserveAllLocalVariables = false; // The unused and final local variables will be optimized
String[] filenames;
String[] classpaths;
@@ -77,6 +81,7 @@ protected Main(PrintWriter writer, boolean systemExitWhenFinished) {
this.out = writer;
this.systemExitWhenFinished = systemExitWhenFinished;
exportedClassFilesCounter = 0;
+ options = Compiler.getDefaultOptions(Locale.getDefault());
}
/*
* Low-level API performing the actual compilation
@@ -243,6 +248,15 @@ public static void compile(String commandLine, PrintWriter writer) {
System.arraycopy(argv, 0, argv = new String[count], 0, count);
new Main(writer, false).compile(argv);
}
+private void setOptionValueIndex(String id,int valueIndex){
+ for(int i = 0 ; i < options.length ; i++){
+ if(options[i].getID().equals(id)){
+ options[i].setValueIndex(valueIndex);
+ return;
+ }
+ }
+}
+
/*
Decode the command line arguments
*/
@@ -254,11 +268,11 @@ private void configure(String[] argv) throws InvalidInputException {
final int TargetSetting = 4;
final int InsideLog = 8;
final int InsideRepetition = 16;
+ final int InsideSource = 32;
final int Default = 0;
- final int SourceOption = 32;
int DEFAULT_SIZE_CLASSPATH = 4;
- boolean noWarnOptionInUsed = false;
boolean warnOptionInUsed = false;
+ boolean noWarnOptionInUsed = false;
int pathCount = 0;
int index = -1, filesCount = 0, argCount = argv.length;
int mode = Default;
@@ -291,6 +305,10 @@ private void configure(String[] argv) throws InvalidInputException {
mode = InsideRepetition;
continue;
}
+ if (currentArg.equals("-source"/*nonNLS*/)) {
+ mode = InsideSource;
+ continue;
+ }
if (currentArg.equals("-d"/*nonNLS*/)) {
if (destinationPath != null)
throw new InvalidInputException(Main.bind("configure.duplicateOutputPath"/*nonNLS*/,currentArg));
@@ -329,7 +347,7 @@ private void configure(String[] argv) throws InvalidInputException {
}
if (currentArg.equals("-noImportError"/*nonNLS*/)) {
mode = Default;
- importProblemIsError = false;
+ setOptionValueIndex("org.eclipse.jdt.internal.compiler.Compiler.problemInvalidImport"/*nonNLS*/,2);
continue;
}
if (currentArg.equals("-noExit"/*nonNLS*/)) {
@@ -349,25 +367,29 @@ private void configure(String[] argv) throws InvalidInputException {
}
if (currentArg.startsWith("-g"/*nonNLS*/)) {
mode = Default;
- debugMask = 0; // reinitialize the default value
String debugOption = currentArg;
int length = currentArg.length();
if (length == 2) {
- debugMask = CompilerOptions.Lines | CompilerOptions.Vars | CompilerOptions.Source;
+ setOptionValueIndex(CompilerOptions.OPTION_LocalVariableAttribute, 0);
+ setOptionValueIndex(CompilerOptions.OPTION_LineNumberAttribute, 0);
+ setOptionValueIndex(CompilerOptions.OPTION_SourceFileAttribute, 0);
continue;
}
if (length > 3) {
+ setOptionValueIndex(CompilerOptions.OPTION_LocalVariableAttribute, 1);
+ setOptionValueIndex(CompilerOptions.OPTION_LineNumberAttribute, 1);
+ setOptionValueIndex(CompilerOptions.OPTION_SourceFileAttribute, 1);
if (length == 7 && debugOption.equals("-g:none"/*nonNLS*/))
continue;
StringTokenizer tokenizer = new StringTokenizer(debugOption.substring(3, debugOption.length()), ","/*nonNLS*/);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equals("vars"/*nonNLS*/)) {
- debugMask |= CompilerOptions.Vars;
+ setOptionValueIndex(CompilerOptions.OPTION_LocalVariableAttribute, 0);
} else if (token.equals("lines"/*nonNLS*/)) {
- debugMask |= CompilerOptions.Lines;
+ setOptionValueIndex(CompilerOptions.OPTION_LineNumberAttribute, 0);
} else if (token.equals("source"/*nonNLS*/)) {
- debugMask |= CompilerOptions.Source;
+ setOptionValueIndex(CompilerOptions.OPTION_SourceFileAttribute, 0);
} else {
throw new InvalidInputException(Main.bind("configure.invalidDebugOption"/*nonNLS*/,debugOption));
}
@@ -378,10 +400,10 @@ private void configure(String[] argv) throws InvalidInputException {
}
if (currentArg.startsWith("-nowarn"/*nonNLS*/)) {
noWarnOptionInUsed = true;
+ noWarn = true;
if (warnOptionInUsed)
throw new InvalidInputException(Main.bind("configure.duplicateWarningConfiguration"/*nonNLS*/));
- mode = Default;
- warningMask = TemporaryWarning; // reinitialize the default value (still see TemporaryWarning)
+ mode = Default;
continue;
}
if (currentArg.startsWith("-warn"/*nonNLS*/)) {
@@ -392,35 +414,45 @@ private void configure(String[] argv) throws InvalidInputException {
String warningOption = currentArg;
int length = currentArg.length();
if (length == 10 && warningOption.equals("-warn:none"/*nonNLS*/)) {
- warningMask = TemporaryWarning; // reinitialize the default value (still see TemporaryWarning)
+ noWarn = true;
continue;
}
if (length < 6)
throw new InvalidInputException(Main.bind("configure.invalidWarningConfiguration"/*nonNLS*/,warningOption));
StringTokenizer tokenizer = new StringTokenizer(warningOption.substring(6, warningOption.length()), ","/*nonNLS*/);
int tokenCounter = 0;
- warningMask = 0; // reinitialize the default value
+
+ setOptionValueIndex(CompilerOptions.OPTION_ReportMethodWithConstructorName, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportHiddenCatchBlock, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportDeprecation, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportUnusedLocal, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportUnusedParameter, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportSyntheticAccessEmulation, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, 2);
+ setOptionValueIndex(CompilerOptions.OPTION_ReportAssertIdentifier, 2);
+
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
tokenCounter++;
if (token.equals("constructorName"/*nonNLS*/)) {
- warningMask |= CompilerOptions.MethodWithConstructorName;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportMethodWithConstructorName, 1);
} else if (token.equals("packageDefaultMethod"/*nonNLS*/)) {
- warningMask |= CompilerOptions.OverriddenPackageDefaultMethod;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod, 1);
} else if (token.equals("maskedCatchBlocks"/*nonNLS*/)) {
- warningMask |= CompilerOptions.MaskedCatchBlock;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportHiddenCatchBlock, 1);
} else if (token.equals("deprecation"/*nonNLS*/)) {
- warningMask |= CompilerOptions.UsingDeprecatedAPI;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportDeprecation, 1);
} else if (token.equals("unusedLocals"/*nonNLS*/)) {
- warningMask |= CompilerOptions.UnusedLocalVariable;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportUnusedLocal, 1);
} else if (token.equals("unusedArguments"/*nonNLS*/)) {
- warningMask |= CompilerOptions.UnusedArgument;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportUnusedParameter, 1);
} else if (token.equals("syntheticAccess"/*nonNLS*/)){
- warningMask |= CompilerOptions.AccessEmulation;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportSyntheticAccessEmulation, 1);
} else if (token.equals("nls"/*nonNLS*/)){
- warningMask |= CompilerOptions.NonExternalizedString;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportNonExternalizedStringLiteral, 1);
} else if (token.equals("assertIdentifier"/*nonNLS*/)){
- warningMask |= CompilerOptions.AssertUsedAsAnIdentifier;
+ setOptionValueIndex(CompilerOptions.OPTION_ReportAssertIdentifier/*nonNLS*/, 1);
} else {
throw new InvalidInputException(Main.bind("configure.invalidWarning"/*nonNLS*/,token));
}
@@ -434,30 +466,14 @@ private void configure(String[] argv) throws InvalidInputException {
continue;
}
if (currentArg.equals("-preserveAllLocals"/*nonNLS*/)) {
- preserveAllLocalVariables = true;
- continue;
- }
- if (currentArg.equals("-source"/*nonNLS*/)) {
- mode = SourceOption;
+ setOptionValueIndex(CompilerOptions.OPTION_PreserveUnusedLocal, 0);
continue;
}
-
- if (mode == SourceOption) {
- if (currentArg.equals("1.4"/*nonNLS*/)) {
- assertMode = true;
- } else if (currentArg.equals("1.3"/*nonNLS*/)) {
- assertMode = false;
- } else {
- throw new InvalidInputException(Main.bind("configure.sourceOption"/*nonNLS*/,currentArg));
- }
- mode = Default;
- continue;
- }
if (mode == TargetSetting) {
if (currentArg.equals("1.1"/*nonNLS*/)) {
- targetJDK = CompilerOptions.JDK1_1;
+ setOptionValueIndex(CompilerOptions.OPTION_TargetPlatform, 0);
} else if (currentArg.equals("1.2"/*nonNLS*/)) {
- targetJDK = CompilerOptions.JDK1_2;
+ setOptionValueIndex(CompilerOptions.OPTION_TargetPlatform, 1);
} else {
throw new InvalidInputException(Main.bind("configure.targetJDK"/*nonNLS*/,currentArg));
}
@@ -481,6 +497,17 @@ private void configure(String[] argv) throws InvalidInputException {
mode = Default;
continue;
}
+ if (mode == InsideSource){
+ if (currentArg.equals("1.3"/*nonNLS*/)) {
+ setOptionValueIndex(CompilerOptions.OPTION_Source, 0);
+ } else if (currentArg.equals("1.4"/*nonNLS*/)) {
+ setOptionValueIndex(CompilerOptions.OPTION_Source, 1);
+ } else {
+ throw new InvalidInputException(Main.bind("configure.source"/*nonNLS*/,currentArg));
+ }
+ mode = Default;
+ continue;
+ }
if (mode == InsideDestinationPath) {
destinationPath = currentArg;
mode = Default;
@@ -526,6 +553,15 @@ private void configure(String[] argv) throws InvalidInputException {
continue;
}
+ if(noWarn){
+ for(int i = 0; i < problemOption.length ; i++){
+ for(int j = 0 ; j < options.length ; j++){
+ if(options[j].getID().equals(problemOption[i]) && options[j].getValueIndex() == 1){
+ options[j].setValueIndex(2);
+ }
+ }
+ }
+ }
/*
* Standalone options
*/
@@ -689,14 +725,7 @@ protected FileSystem getLibraryAccess() {
* Low-level API performing the actual compilation
*/
protected ConfigurableOption[] getOptions() {
- CompilerOptions options = new CompilerOptions();
- options.produceDebugAttributes(debugMask);
- options.preserveAllLocalVariables(preserveAllLocalVariables);
- options.handleImportProblemAsError(importProblemIsError);
- options.setWarningThreshold(warningMask);
- options.setTargetJDK(targetJDK);
- options.setAssertMode(this.assertMode);
- return options.getConfigurableOptions(Locale.getDefault());
+ return options;
}
protected IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
@@ -750,43 +779,15 @@ protected void performCompilation() throws InvalidInputException {
getOptions(),
getBatchRequestor(),
getProblemFactory());
- CompilerOptions options = batchCompiler.options;
- // set the non-externally configurable options.
+ CompilerOptions options = batchCompiler.options;
+
+ // set the non-externally configurable options.
options.setVerboseMode(verbose);
options.produceReferenceInfo(produceRefInfo);
batchCompiler.compile(getCompilationUnits());
}
private void printUsage() {
out.println(Main.bind("misc.usage"/*nonNLS*/,this.versionID));
- /*out.println(
- "Eclipse Java Compiler "+ this.versionID + ", Copyright IBM Corp 2000\n\n" +
- "Usage: <options> <source files | directories>\n\n" +
- "where options include:\n" +
- "-version or -v\tdisplays the version number (standalone option)\n" +
- "-help\tdisplay this help message (standalone option)\n" +
- "-noExit\tPrevent the compiler to call System.exit at the end of the compilation process\n" +
- "-classpath <dir 1>;<dir 2>;...;<dir P>\n" +
- "-d <dir>\tdestination directory\n\t\t, specified '-d none' if you don't want to dump files\n" +
- "-verbose\tprint accessed/processed compilation units \n" +
- "-time\t\tdisplay total compilation time" +
- "\n\t\tand speed if line attributes are enabled\n" +
- "-log <filename>\tspecify a log file for recording problems\n" +
- "-progress\t\tshow progress (only in -log mode)\n" +
- "-g[:<level>]\tspecify the level of details for debug attributes" +
- "\n\t\t-g\tgenerate all debug info"+
- "\n\t\t-g:none\tno debug info"+
- "\n\t\t-g:{lines,vars,source}\tonly some debug info\n" +
- "-nowarn\t\tdo not report warnings \n" +
- "-warn:<mask>\tspecify the level of details for warnings\n" +
- "\t\t-warn:none no warning\n"+
- "\t\t-warn:{constructorName, packageDefaultMethod, deprecation,\n" +
- "\t\t\tmaskedCatchBlocks, unusedLocals, unusedArguments, \n" +
- "\t\t\tsyntheticAccess, nls, assertIdentifier}\n" +
- "-noImportError\tdo not report errors on incorrect imports\n" +
- "-proceedOnError\tkeep compiling when error, \n\t\tdumping class files with problem methods\n" +
- "-referenceInfo\tcompute reference info\n" +
- "-preserveAllLocals\trequest code gen preserve all local variables\n" +
- "-repeat <n>\trepeat compilation process for performance analysis\n");*/
out.flush();
}
diff --git a/org.eclipse.jdt.core/changes.txt b/org.eclipse.jdt.core/changes.txt
index 1604d6f39b..2943bacea3 100644
--- a/org.eclipse.jdt.core/changes.txt
+++ b/org.eclipse.jdt.core/changes.txt
@@ -4,18 +4,22 @@ What's new in this drop (since 0.9)
==================================================================================
* JCK1.3a compliant.
* All messages have been externalized.
- * Added 2 new APIs on JavaConventions:
+ * Added 2 new APIs on JavaConventions for classpath validation.
- IJavaModelStatus validateClasspath(IJavaProject project, IClasspathEntry[] classpath, IPath outputLocation)
- IJavaModelStatus validateClasspathEntry(IJavaProject project, IClasspathEntry entry, boolean checkSourceAttachment)
* Ant Eclipse compiler task added (org.eclipse.jdt.core.ant.Jdtcom)
* Assertions support enabled: by default the compiler is 1.3 compliant, but it can optionally be turned into source 1.4 mode cf. JavaCore options.
+ * Added new APIs on JavaCore so as to change optional settings (compiler, formatter, codeassist, ...).
+ - Description of available options is available in JavaCore.ini along with default values.
+ - Option settings are globally kept on JavaCore.
PRs Fixed in this Release (since 1.0NL stream)
==================================================================================
+1GE4ILR: ITPJCORE:ALL - Eval - Evaluation in Binary Project fails
+1GI3LLC: ITPJCORE:ALL - Incorrect formatting for the new keyword
1GHU6O5: ITPJCORE:WINNT - RMIC test fail
1GHH6O7: ITPJCORE:ALL - Need to tune the exception analysis for AssertStatement
1GHUW7T: ITPJCORE:WIN2000 - Build Problem
-1GFQT1W: ITPJUI:WIN2000 - Error changing classpath to not use /bin
1GHU4PK: ITPJCORE:WINNT - NoSuchMethodError when running program
1GHONAX: ITPJCORE:WIN2000 - Compiler uses different name lookup for refactoring
1GEJYAJ: ITPJCORE:WIN2000 - Compiler - Binding of QualifiedNameReference is null
diff --git a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java
index 57cf839ef3..47ce744e9a 100644
--- a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java
+++ b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/Compiler.java
@@ -273,16 +273,6 @@ public class Compiler implements ITypeRequestor, ProblemSeverities {
}
}
- /**
- * Answer an array of descriptions for the configurable options.
- * The descriptions may be changed and passed back to a different
- * compiler.
- *
- * @return ConfigurableOption[] - array of configurable options
- */
- public static ConfigurableOption[] getDefaultOptions(Locale locale) {
- return new CompilerOptions().getConfigurableOptions(locale);
- }
protected void getMethodBodies(CompilationUnitDeclaration unit, int place) {
//fill the methods bodies in order for the code to be generated
@@ -503,4 +493,21 @@ public class Compiler implements ITypeRequestor, ProblemSeverities {
// this.reset();
}
}
+
+ /**
+ * Returns all the options of the compiler to be shown by the UI
+ *
+ * @param locale java.util.Locale
+ * @return org.eclipse.jdt.internal.compiler.ConfigurableOption[]
+ */
+ public static ConfigurableOption[] getDefaultOptions(Locale locale) {
+ String[] ids = ConfigurableOption.getIDs(Compiler.class.getName(),locale);
+
+ ConfigurableOption[] result = new ConfigurableOption[ids.length];
+ for(int i = 0 ; i < ids.length ; i++){
+ result[i] = new ConfigurableOption(ids[i],locale);
+ }
+
+ return result;
+ }
} \ No newline at end of file
diff --git a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ConfigurableOption.java b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ConfigurableOption.java
index 6a88d97064..201235d941 100644
--- a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ConfigurableOption.java
+++ b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ConfigurableOption.java
@@ -7,206 +7,501 @@ package org.eclipse.jdt.internal.compiler;
/**
* Generic option description, which can be modified independently from the
* component it belongs to.
+ *
+ * File to modify when adding an option :
+ * Add option in option file of component
+ * Modify setOption method of component option class
+ *
+ * Option file syntax
+ * <code>
+ * com.foo.Bar.optionOne.category=Category One
+ * com.foo.Bar.optionOne.name=Option One
+ * com.foo.Bar.optionOne.possibleValues=2|Value 1|Value 2
+ * com.foo.Bar.optionOne.description=Description of Option One
+ * com.foo.Bar.optionOne.default=0
+ *
+ * com.foo.Bar.optionTwo.category=Category One
+ * com.foo.Bar.optionTwo.name=Option Two
+ * com.foo.Bar.optionTwo.possibleValues=-1|string
+ * com.foo.Bar.optionTwo.description=Description of Option Two
+ * com.foo.Bar.optionTwo.default=Value
+ *
+ * com.foo.Bar.optionThree.category=Category Two
+ * com.foo.Bar.optionThree.name=Option Three
+ * com.foo.Bar.optionThree.possibleValues=-1|int|0|no
+ * com.foo.Bar.optionThree.description=Description of Option Three
+ * com.foo.Bar.optionThree.default=4
+ * </code>
+ *
+ * possibleValues values :
+ * - A positive number and the list of the value
+ * - Value -1 following by type. If type is a number
+ * there is min and max value (with value no if there is no max or min
+ *
+ * e.g.
+ * 2|Value 1|Value 2
+ * 3|Value 1|Value 2|Value 3
+ * -1|string
+ * -1|int|0|20
+ * -1|int|no|20
+ * -1|int|-10|no
+ * -1|int|no|no
+ * -1|int
+ * -1|float|0.0|20.0
+ * -1|float|no|20.0
+ * -1|float|-10.0|no
+ * -1|float|no|no
+ * -1|float
+ *
*/
-
import java.util.*;
public class ConfigurableOption {
- private String componentName;
- private int id;
+ public final static String STRING = "string"/*nonNLS*/;
+ public final static String INT = "int"/*nonNLS*/;
+ public final static String FLOAT = "float"/*nonNLS*/;
+ public final static String DISCRETE = "discrete"/*nonNLS*/;
+
+ // special value for <possibleValues> indicating that
+ // the <currentValueIndex> is the actual value
+ public final static String[] NoDiscreteValue = {};
+ private String id;
+ private String value;
+ private int valueIndex = -1;
+ private String defaultValue;
+ private int defaultValueIndex = -1;
private String category;
private String name;
private String description;
- private int currentValueIndex;
- private int defaultValueIndex;
private String[] possibleValues;
+ private int order;
+
+ private String type;
+ private boolean maxExisting = false;
+ private boolean minExisting = false;
+ private int maxInt;
+ private int minInt;
+ private float maxFloat;
+ private float minFloat;
+
+
+ private Locale loc;
- // special value for <possibleValues> indicating that
- // the <currentValueIndex> is the actual value
- public final static String[] NoDiscreteValue = {};
-/**
- * INTERNAL USE ONLY
- *
- * Initialize an instance of this class according to a specific locale
- *
- * @param loc java.util.Locale
- */
-public ConfigurableOption(
- String componentName,
- String optionName,
- Locale loc,
- int currentValueIndex) {
+ private String componentName;
+ private String missing;
- this.componentName = componentName;
- this.currentValueIndex = currentValueIndex;
-
- ResourceBundle resource = null;
- try {
- String location = componentName.substring(0, componentName.lastIndexOf('.'));
- resource = ResourceBundle.getBundle(location + ".Options"/*nonNLS*/, loc);
- } catch (MissingResourceException e) {
- category = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
- name = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
- description = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
- possibleValues = new String[0];
- id = -1;
- }
- if (resource == null) return;
- try {
- id = Integer.parseInt(resource.getString(optionName + ".number"/*nonNLS*/));
- } catch (MissingResourceException e) {
- id = -1;
- } catch (NumberFormatException e) {
- id = -1;
- }
- try {
- category = resource.getString(optionName + ".category"/*nonNLS*/);
- } catch (MissingResourceException e) {
- category = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
- }
- try {
- name = resource.getString(optionName + ".name"/*nonNLS*/);
- } catch (MissingResourceException e) {
- name = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
- }
- try {
- StringTokenizer tokenizer = new StringTokenizer(resource.getString(optionName + ".possibleValues"/*nonNLS*/), "|"/*nonNLS*/);
- int numberOfValues = Integer.parseInt(tokenizer.nextToken());
- if(numberOfValues == -1){
+ public ConfigurableOption(String id, Locale loc) {
+ this.id = id;
+ this.value = value;
+ this.loc = loc;
+
+ this.componentName = id.substring(0,id.lastIndexOf('.'));
+
+ ResourceBundle bundle = null;
+ missing = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
+ try {
+ bundle = ResourceBundle.getBundle(componentName,loc);
+ } catch (MissingResourceException e) {
+ id = missing;
+ defaultValue = missing;
+ category = missing;
+ name = missing;
+ description = missing;
possibleValues = NoDiscreteValue;
- } else {
- possibleValues = new String[numberOfValues];
- int index = 0;
- while (tokenizer.hasMoreTokens()) {
- possibleValues[index] = tokenizer.nextToken();
- index++;
+ }
+ if (bundle == null) return;
+ try{
+ StringTokenizer tokenizer =
+ new StringTokenizer(
+ bundle.getString(id + ".possibleValues"/*nonNLS*/),
+ "|"/*nonNLS*/);
+ int numberOfValues = Integer.parseInt(tokenizer.nextToken());
+ if (numberOfValues == -1) {
+ // the possible value are not discrete
+ possibleValues = NoDiscreteValue;
+
+ String token = tokenizer.nextToken();
+ type = token;
+ if(token.equals(STRING)){
+
+ }
+ else if(token.equals(INT) && tokenizer.hasMoreTokens()){
+ token = tokenizer.nextToken();
+ if(!token.equals("no"/*nonNLS*/)){
+ minExisting = true;
+ minInt = Integer.parseInt(token);
+ }
+ token = tokenizer.nextToken();
+ if(!token.equals("no"/*nonNLS*/)){
+ maxExisting = true;
+ maxInt = Integer.parseInt(token);
+ }
+ }
+ else if(token.equals(FLOAT) && tokenizer.hasMoreTokens()){
+ token = tokenizer.nextToken();
+ if(!token.equals("no"/*nonNLS*/)){
+ minExisting = true;
+ minFloat = Float.parseFloat(token);
+ }
+ token = tokenizer.nextToken();
+ if(!token.equals("no"/*nonNLS*/)){
+ maxExisting = true;
+ maxFloat = Float.parseFloat(token);
+ }
+ }
+ } else {
+ // possible value are discrete
+ type = DISCRETE;
+ possibleValues = new String[numberOfValues];
+ int index = 0;
+ while (tokenizer.hasMoreTokens()) {
+ possibleValues[index] = tokenizer.nextToken();
+ index++;
+ }
}
+
+ } catch (MissingResourceException e) {
+ possibleValues = NoDiscreteValue;
+ type = missing;
+ } catch (NoSuchElementException e) {
+ possibleValues = NoDiscreteValue;
+ type = missing;
+ } catch (NumberFormatException e) {
+ possibleValues = NoDiscreteValue;
+ type = missing;
+ }
+ try{
+ if(possibleValues == NoDiscreteValue){
+ defaultValue = bundle.getString(id + ".default"/*nonNLS*/);
+ }
+ else{
+ defaultValueIndex = Integer.parseInt(bundle.getString(id + ".default"/*nonNLS*/));
+ }
+ } catch (MissingResourceException e) {
+ defaultValue = missing;
+ } catch (NumberFormatException e) {
+ defaultValueIndex = -1;
+ }
+ try{
+ order = Integer.parseInt(bundle.getString(id + ".order"/*nonNLS*/));
+ } catch (NumberFormatException e) {
+ order = -1;
+ } catch (MissingResourceException e) {
+ order = -1;
+ }
+ try{
+ category = bundle.getString(id + ".category"/*nonNLS*/);
+ } catch (MissingResourceException e) {
+ category = missing;
+ }
+ try{
+ name = bundle.getString(id + ".name"/*nonNLS*/);
+ } catch (MissingResourceException e) {
+ name = missing;
+ }
+ try{
+ description = bundle.getString(id + ".description"/*nonNLS*/);
+ } catch (MissingResourceException e) {
+ description = missing;
}
- } catch (MissingResourceException e) {
- possibleValues = new String[0];
- } catch (NoSuchElementException e) {
- possibleValues = new String[0];
- } catch (NumberFormatException e) {
- possibleValues = new String[0];
}
- try {
- description = resource.getString(optionName + ".description"/*nonNLS*/);
- } catch (MissingResourceException e) {
- description = "Missing ressources entries for"/*nonNLS*/ + componentName + " options"/*nonNLS*/;
+
+ /**
+ * Internal ID which allows the configurable component to identify this particular option.
+ *
+ * @return String
+ */
+ public String getID() {
+ return id;
}
-}
-/**
- * Return a String that represents the localized category of the receiver.
- * @return java.lang.String
- */
-public String getCategory() {
- return category;
-}
-/**
- * Return a String that identifies the component owner (typically the qualified
- * type name of the class which it corresponds to).
- *
- * e.g. "org.eclipse.jdt.internal.compiler.api.Compiler"
- *
- * @return java.lang.String
- */
-public String getComponentName() {
- return componentName;
-}
-/**
- * Answer the index (in possibleValues array) of the current setting for this
- * particular option.
- *
- * In case the set of possibleValues is NoDiscreteValue, then this index is the
- * actual value (e.g. max line lenght set to 80).
- *
- * @return int
- */
-public int getCurrentValueIndex() {
- return currentValueIndex;
-}
-/**
- * Answer the index (in possibleValues array) of the default setting for this
- * particular option.
- *
- * In case the set of possibleValues is NoDiscreteValue, then this index is the
- * actual value (e.g. max line lenght set to 80).
- *
- * @return int
- */
-public int getDefaultValueIndex() {
- return defaultValueIndex;
-}
-/**
- * Return an String that represents the localized description of the receiver.
- *
- * @return java.lang.String
- */
-public String getDescription() {
- return description;
-}
-/**
- * Internal ID which allows the configurable component to identify this particular option.
- *
- * @return int
- */
-public int getID() {
- return id;
-}
-/**
- * Return a String that represents the localized name of the receiver.
- * @return java.lang.String
- */
-public String getName() {
- return name;
-}
-/**
- * Return an array of String that represents the localized possible values of the receiver.
- * @return java.lang.String[]
- */
-public String[] getPossibleValues() {
- return possibleValues;
-}
-/**
- * Change the index (in possibleValues array) of the current setting for this
- * particular option.
- *
- * In case the set of possibleValues is NoDiscreteValue, then this index is the
- * actual value (e.g. max line lenght set to 80).
- *
- * @return int
- */
-public void setValueIndex(int newIndex) {
- currentValueIndex = newIndex;
-}
-public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Configurable option for "/*nonNLS*/);
- buffer.append(this.componentName).append("\n"/*nonNLS*/);
- buffer.append("- category: "/*nonNLS*/).append(this.category).append("\n"/*nonNLS*/);
- buffer.append("- name: "/*nonNLS*/).append(this.name).append("\n"/*nonNLS*/);
- /* display current value */
- buffer.append("- current value: "/*nonNLS*/);
- if (possibleValues == NoDiscreteValue){
- buffer.append(this.currentValueIndex);
- } else {
- buffer.append(this.possibleValues[this.currentValueIndex]);
- }
- buffer.append("\n"/*nonNLS*/);
- /* display possible values */
- if (possibleValues != NoDiscreteValue){
- buffer.append("- possible values: ["/*nonNLS*/);
- for (int i = 0, max = possibleValues.length; i < max; i++) {
- if (i != 0)
- buffer.append(", "/*nonNLS*/);
- buffer.append(possibleValues[i]);
- }
- buffer.append("]\n"/*nonNLS*/);
- buffer.append("- curr. val. index: "/*nonNLS*/).append(currentValueIndex).append("\n"/*nonNLS*/);
- }
- buffer.append("- description: "/*nonNLS*/).append(description).append("\n"/*nonNLS*/);
- return buffer.toString();
-}
-}
+ /**
+ * Answer the value of the current setting for this particular option.
+ *
+ * @return String
+ */
+ public String getValue() {
+ if(possibleValues == NoDiscreteValue){
+ if (value == null)
+ return getDefaultValue();
+ return value;
+ }
+ else {
+ if (valueIndex == -1)
+ return getDefaultValue();
+ return possibleValues[valueIndex];
+ }
+ }
+
+ /**
+ * Change the value of the current setting for this particular option.
+ *
+ * @param value String
+ */
+ public void setValue(String value) {
+ if(possibleValues == NoDiscreteValue){
+ this.value = value;
+ }
+ else{
+ for(int i = 0 ; i < possibleValues.length ; i++){
+ if(possibleValues[i].equals(value)){
+ this.valueIndex = i;
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Gets the valueIndex
+ * @return Returns a int
+ */
+ public int getValueIndex() {
+ if(possibleValues == NoDiscreteValue)
+ return -1;
+ if (valueIndex == -1)
+ return getDefaultValueIndex();
+ return valueIndex;
+ }
+ /**
+ * Sets the valueIndex
+ * @param valueIndex The valueIndex to set
+ */
+ public void setValueIndex(int valueIndex) {
+ if(valueIndex < 0 || valueIndex >= possibleValues.length){
+ this.valueIndex = -1;
+ }
+ else {
+ this.valueIndex = valueIndex;
+ }
+ }
+
+ /**
+ * Answer the value of the default setting for this particular option.
+ *
+ * @return String
+ */
+ public String getDefaultValue() {
+ if(possibleValues != NoDiscreteValue){
+ if(defaultValueIndex == -1)
+ return missing;
+ return possibleValues[defaultValueIndex];
+ }
+ return defaultValue;
+ }
+
+ /**
+ * Change the value of the default setting for this particular option.
+ *
+ * @param value String
+ */
+ public void setDefaultValue(String defaultValue) {
+ if(possibleValues == NoDiscreteValue){
+ this.defaultValue = defaultValue;
+ }
+ else{
+ for(int i = 0 ; i < possibleValues.length ; i++){
+ if(possibleValues[i].equals(defaultValue)){
+ this.defaultValueIndex = i;
+ break;
+ }
+ }
+ }
+ }
+
+ public void setToDefault(){
+ value = null;
+ valueIndex = -1;
+ }
+
+ /**
+ * Gets the defaultValueIndex
+ * @return Returns a int
+ */
+ public int getDefaultValueIndex() {
+ if(possibleValues == NoDiscreteValue)
+ return -1;
+
+ return defaultValueIndex;
+ }
+ /**
+ * Sets the defaultValueIndex
+ * @param defaultValueIndex The defaultValueIndex to set
+ */
+ public void setDefaultValueIndex(int defaultValueIndex) {
+ if(defaultValueIndex < 0 || defaultValueIndex >= possibleValues.length){
+ this.defaultValueIndex = -1;
+ }
+ else {
+ this.defaultValueIndex = defaultValueIndex;
+ }
+ }
+ /**
+ * Return a String that represents the localized category of the receiver.
+ * @return java.lang.String
+ */
+ public String getCategory() {
+ return category;
+ }
+
+ /**
+ * Return a String that represents the localized name of the receiver.
+ * @return java.lang.String
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Return an String that represents the localized description of the receiver.
+ *
+ * @return java.lang.String
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Return an array of String that represents the localized possible values of the receiver.
+ *
+ * @return java.lang.String[]
+ */
+ public String[] getPossibleValues() {
+ return possibleValues;
+ }
+
+ /**
+ * Return a String that identifies the component owner (typically the qualified
+ * type name of the class which it corresponds to).
+ *
+ * e.g. "org.eclipse.jdt.internal.compiler.api.Compiler"
+ *
+ * @return java.lang.String
+ */
+ public String getComponentName() {
+ return componentName;
+ }
+
+ /**
+ * Gets the type
+ * @return Returns a int
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * Gets the max
+ * @return Returns a Number
+ */
+ public Number getMax() {
+ if(possibleValues == NoDiscreteValue){
+ if(type.equals(INT)){
+ if(maxExisting){
+ return new Integer(maxInt);
+ }
+ else {
+ return new Integer(Integer.MAX_VALUE);
+ }
+ }
+ else if(type.equals(FLOAT)){
+ if(maxExisting){
+ return new Float(maxFloat);
+ }
+ else {
+ return new Float(Float.MAX_VALUE);
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Gets the min
+ * @return Returns a Number
+ */
+ public Number getMin() {
+ if(possibleValues == NoDiscreteValue){
+ if(type.equals(INT)){
+ if(minExisting){
+ return new Integer(minInt);
+ }
+ else {
+ return new Integer(Integer.MIN_VALUE);
+ }
+ }
+ else if(type.equals(FLOAT)){
+ if(minExisting){
+ return new Float(minFloat);
+ }
+ else {
+ return new Float(Float.MIN_VALUE);
+ }
+ }
+ }
+ return null;
+ }
+
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Configurable option for "/*nonNLS*/);
+ buffer.append(this.componentName).append("\n"/*nonNLS*/);
+ buffer.append("- category: "/*nonNLS*/).append(this.category).append("\n"/*nonNLS*/);
+ buffer.append("- name: "/*nonNLS*/).append(this.name).append("\n"/*nonNLS*/);
+ /* display current value */
+ buffer.append("- current value: "/*nonNLS*/).append(this.value).append("\n"/*nonNLS*/);
+ /* display possible values */
+ if (possibleValues != NoDiscreteValue){
+ buffer.append("- possible values: ["/*nonNLS*/);
+ for (int i = 0, max = possibleValues.length; i < max; i++) {
+ if (i != 0)
+ buffer.append(", "/*nonNLS*/);
+ buffer.append(possibleValues[i]);
+ }
+ buffer.append("]\n"/*nonNLS*/);
+ }
+ buffer.append("- description: "/*nonNLS*/).append(description).append("\n"/*nonNLS*/);
+ return buffer.toString();
+ }
+
+ public static String[] getIDs(String componentName,Locale locale){
+ try {
+ ResourceBundle bundle = ResourceBundle.getBundle(componentName,locale);
+ Enumeration bundleKeys = bundle.getKeys();
+
+ String partialResult[] = new String[100];
+ int resultCount = 0;
+
+ while(bundleKeys.hasMoreElements()){
+ String bundleKey = (String)bundleKeys.nextElement();
+ if(bundleKey.endsWith("order"/*nonNLS*/)){
+ int order;
+ try{
+ order = Integer.parseInt(bundle.getString(bundleKey));
+
+ String id = bundleKey.substring(0,bundleKey.lastIndexOf('.'));
+ if(partialResult.length <= order)
+ System.arraycopy(partialResult,0,partialResult = new String[order+1],0,partialResult.length);
+ partialResult[order]= id;
+ resultCount++;
+ } catch (NumberFormatException e) {
+ //if order can not be read, option is not add
+ }
+ }
+ }
+ String[] result = new String[resultCount];
+ resultCount = 0;
+ for(int i = 0; i < partialResult.length;i++){
+ if(partialResult[i]!= null){
+ result[resultCount++]=partialResult[i];
+
+ }
+ }
+ return result;
+
+ } catch (MissingResourceException e) {
+ return new String[0];
+ }
+ }
+} \ No newline at end of file
diff --git a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
index 22c40aabc5..9d395d9f48 100644
--- a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
+++ b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java
@@ -11,6 +11,27 @@ import org.eclipse.jdt.internal.compiler.problem.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
public class CompilerOptions implements ConfigurableProblems, ProblemIrritants, ProblemReasons, ProblemSeverities {
+
+ /**
+ * Option IDs
+ */
+ public static final String OPTION_LocalVariableAttribute = Compiler.class.getName() + ".localVariableAttribute"/*nonNLS*/;
+ public static final String OPTION_LineNumberAttribute = Compiler.class.getName() + ".lineNumberAttribute"/*nonNLS*/;
+ public static final String OPTION_SourceFileAttribute = Compiler.class.getName() + ".sourceFileAttribute"/*nonNLS*/;
+ public static final String OPTION_PreserveUnusedLocal = Compiler.class.getName() + ".preserveUnusedLocal"/*nonNLS*/;
+ public static final String OPTION_ReportUnreachableCode = Compiler.class.getName() + ".reportUnreachableCode"/*nonNLS*/;
+ public static final String OPTION_ReportInvalidImport = Compiler.class.getName() + ".reportInvalidImport"/*nonNLS*/;
+ public static final String OPTION_ReportMethodWithConstructorName = Compiler.class.getName() + ".reportMethodWithConstructorName"/*nonNLS*/;
+ public static final String OPTION_ReportOverridingPackageDefaultMethod = Compiler.class.getName() + ".reportOverridingPackageDefaultMethod"/*nonNLS*/;
+ public static final String OPTION_ReportDeprecation = Compiler.class.getName() + ".reportDeprecation"/*nonNLS*/;
+ public static final String OPTION_ReportHiddenCatchBlock = Compiler.class.getName() + ".reportHiddenCatchBlock"/*nonNLS*/;
+ public static final String OPTION_ReportUnusedLocal = Compiler.class.getName() + ".reportUnusedLocal"/*nonNLS*/;
+ public static final String OPTION_ReportUnusedParameter = Compiler.class.getName() + ".reportUnusedParameter"/*nonNLS*/;
+ public static final String OPTION_ReportSyntheticAccessEmulation = Compiler.class.getName() + ".reportSyntheticAccessEmulation"/*nonNLS*/;
+ public static final String OPTION_ReportNonExternalizedStringLiteral = Compiler.class.getName() + ".reportNonExternalizedStringLiteral"/*nonNLS*/;
+ public static final String OPTION_Source = Compiler.class.getName() + ".source"/*nonNLS*/;
+ public static final String OPTION_TargetPlatform = Compiler.class.getName() + ".targetPlatform"/*nonNLS*/;
+ public static final String OPTION_ReportAssertIdentifier = Compiler.class.getName() + ".reportAssertIdentifier"/*nonNLS*/;
// class file output
// these are the bits used to buld a mask to know which debug
@@ -24,8 +45,7 @@ public class CompilerOptions implements ConfigurableProblems, ProblemIrritants,
// default severity level for handlers
public int errorThreshold = UnreachableCode | ImportProblem;
- public int warningThreshold =
- ParsingOptionalError |
+ public int warningThreshold =
MethodWithConstructorName | OverriddenPackageDefaultMethod |
UsingDeprecatedAPI | MaskedCatchBlock |
UnusedLocalVariable | AssertUsedAsAnIdentifier |
@@ -63,6 +83,7 @@ public CompilerOptions(){
*/
public CompilerOptions(ConfigurableOption[] settings){
if (settings == null) return;
+
// filter options which are related to the compiler component
String componentName = Compiler.class.getName();
for (int i = 0, max = settings.length; i < max; i++){
@@ -71,209 +92,191 @@ public CompilerOptions(ConfigurableOption[] settings){
}
}
}
-/**
- * Returns all the options of the compiler to be shown by the UI
- *
- * @param locale java.util.Locale
- * @return org.eclipse.jdt.internal.compiler.ConfigurableOption[]
- */
-public ConfigurableOption[] getConfigurableOptions(Locale locale) {
- String componentName = Compiler.class.getName();
- return new ConfigurableOption[] {
- new ConfigurableOption(
- componentName,
- "debug.vars"/*nonNLS*/,
- locale,
- (produceDebugAttributes & Vars) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "debug.lines"/*nonNLS*/,
- locale,
- (produceDebugAttributes & Lines) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "debug.source"/*nonNLS*/,
- locale,
- (produceDebugAttributes & Source) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "debug.preserveAllLocals"/*nonNLS*/,
- locale,
- preserveAllLocalVariables ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalError.unReachableCode"/*nonNLS*/,
- locale,
- (errorThreshold & UnreachableCode) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalError.importProblem"/*nonNLS*/,
- locale,
- (errorThreshold & ImportProblem) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.methodWithConstructorName"/*nonNLS*/,
- locale,
- (warningThreshold & MethodWithConstructorName) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.overridingPackageDefaultMethod"/*nonNLS*/,
- locale,
- (warningThreshold & OverriddenPackageDefaultMethod) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.deprecated"/*nonNLS*/,
- locale,
- (warningThreshold & UsingDeprecatedAPI) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.maskedCatchBlock"/*nonNLS*/,
- locale,
- (warningThreshold & MaskedCatchBlock) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.unusedLocalVariable"/*nonNLS*/,
- locale,
- (warningThreshold & UnusedLocalVariable) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.unusedArgument"/*nonNLS*/,
- locale,
- (warningThreshold & UnusedArgument) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "binaryCompatibility.targetJDK"/*nonNLS*/,
- locale,
- targetJDK),
- new ConfigurableOption(
- componentName,
- "optionalWarning.accessEmulation"/*nonNLS*/,
- locale,
- (warningThreshold & AccessEmulation) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.nonExternalizedString"/*nonNLS*/,
- locale,
- (warningThreshold & NonExternalizedString) != 0 ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "source"/*nonNLS*/,
- locale,
- assertMode ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "optionalWarning.assertIdentifier"/*nonNLS*/,
- locale,
- (warningThreshold & AssertUsedAsAnIdentifier) != 0 ? 0 : 1)
- };
-}
+
public int getDebugAttributesMask() {
return this.produceDebugAttributes;
}
public int getTargetJDK() {
return this.targetJDK;
}
-
public boolean getAssertMode() {
return this.assertMode;
}
-
-public void handleAccessEmulationAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= AccessEmulation;
- } else {
- warningThreshold &= ~AccessEmulation;
- }
-}
-public void handleDeprecationUseAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= UsingDeprecatedAPI;
- } else {
- warningThreshold &= ~UsingDeprecatedAPI;
+public void setAccessEmulationSeverity(int flag) {
+ errorThreshold &= ~AccessEmulation;
+ warningThreshold &= ~AccessEmulation;
+ switch(flag){
+ case Error :
+ errorThreshold |= AccessEmulation;
+ break;
+ case Warning :
+ warningThreshold |= AccessEmulation;
+ break;
}
}
-public void handleImportProblemAsError(boolean flag) {
- if (flag) {
- errorThreshold |= ImportProblem;
- warningThreshold &= ~ImportProblem;
- } else {
- errorThreshold &= ~ImportProblem;
- warningThreshold |= ImportProblem;
+public void setDeprecationUseSeverity(int flag) {
+ errorThreshold &= ~UsingDeprecatedAPI;
+ warningThreshold &= ~UsingDeprecatedAPI;
+ switch(flag){
+ case Error :
+ errorThreshold |= UsingDeprecatedAPI;
+ break;
+ case Warning :
+ warningThreshold |= UsingDeprecatedAPI;
+ break;
}
}
-public void handleMaskedCatchBlockAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= MaskedCatchBlock;
- } else {
- warningThreshold &= ~MaskedCatchBlock;
+public void setImportProblemSeverity(int flag) {
+ errorThreshold &= ~ImportProblem;
+ warningThreshold &= ~ImportProblem;
+ switch(flag){
+ case Error :
+ errorThreshold |= ImportProblem;
+ break;
+ case Warning :
+ warningThreshold |= ImportProblem;
+ break;
}
}
-public void handleMethodWithConstructorNameAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= MethodWithConstructorName;
- } else {
- warningThreshold &= ~MethodWithConstructorName;
+public void setMaskedCatchBlockSeverity(int flag) {
+ errorThreshold &= ~MaskedCatchBlock;
+ warningThreshold &= ~MaskedCatchBlock;
+ switch(flag){
+ case Error :
+ errorThreshold |= MaskedCatchBlock;
+ break;
+ case Warning :
+ warningThreshold |= MaskedCatchBlock;
+ break;
}
}
-public void handleObsoleteLiteralAsError(boolean flag) {
- if (flag) {
- errorThreshold |= ParsingOptionalError;
- warningThreshold &= ~ParsingOptionalError;
- } else {
- errorThreshold &= ~ParsingOptionalError;
- warningThreshold |= ParsingOptionalError;
+public void setMethodWithConstructorNameSeverity(int flag) {
+ errorThreshold &= ~MethodWithConstructorName;
+ warningThreshold &= ~MethodWithConstructorName;
+ switch(flag){
+ case Error :
+ errorThreshold |= MethodWithConstructorName;
+ break;
+ case Warning :
+ warningThreshold |= MethodWithConstructorName;
+ break;
}
}
-public void handleOverriddenPackageDefaultMethodAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= OverriddenPackageDefaultMethod;
- } else {
- warningThreshold &= ~OverriddenPackageDefaultMethod;
+
+public void setOverriddenPackageDefaultMethodSeverity(int flag) {
+ errorThreshold &= ~OverriddenPackageDefaultMethod;
+ warningThreshold &= ~OverriddenPackageDefaultMethod;
+ switch(flag){
+ case Error :
+ errorThreshold |= OverriddenPackageDefaultMethod;
+ break;
+ case Warning :
+ warningThreshold |= OverriddenPackageDefaultMethod;
+ break;
}
}
-public void handleUnreachableCodeAsError(boolean flag) {
- if (flag) {
- errorThreshold |= UnreachableCode;
- warningThreshold &= ~UnreachableCode;
- } else {
- errorThreshold &= ~UnreachableCode;
- warningThreshold |= UnreachableCode;
+public void setUnreachableCodeSeverity(int flag) {
+ errorThreshold &= ~UnreachableCode;
+ warningThreshold &= ~UnreachableCode;
+ switch(flag){
+ case Error :
+ errorThreshold |= UnreachableCode;
+ break;
+ case Warning :
+ warningThreshold |= UnreachableCode;
+ break;
}
}
-public void handleUnusedArgumentAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= UnusedArgument;
- } else {
- warningThreshold &= ~UnusedArgument;
+public void setUnusedArgumentSeverity(int flag) {
+ errorThreshold &= ~UnusedArgument;
+ warningThreshold &= ~UnusedArgument;
+ switch(flag){
+ case Error :
+ errorThreshold |= UnusedArgument;
+ break;
+ case Warning :
+ warningThreshold |= UnusedArgument;
+ break;
}
}
-public void handleUnusedLocalVariableAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= UnusedLocalVariable;
- } else {
- warningThreshold &= ~UnusedLocalVariable;
+public void setUnusedLocalVariableSeverity(int flag) {
+ errorThreshold &= ~UnusedLocalVariable;
+ warningThreshold &= ~UnusedLocalVariable;
+ switch(flag){
+ case Error :
+ errorThreshold |= UnusedLocalVariable;
+ break;
+ case Warning :
+ warningThreshold |= UnusedLocalVariable;
+ break;
}
}
-public boolean isAccessEmulationHandledAsWarning() {
- return (warningThreshold & AccessEmulation) != 0;
-}
-public boolean isDeprecationUseHandledAsWarning() {
- return (warningThreshold & UsingDeprecatedAPI) != 0;
-}
-public boolean isImportProblemHandledAsError() {
- return (errorThreshold & ImportProblem) != 0;
-}
-public boolean isMaskedCatchBlockHandledAsWarning() {
- return (warningThreshold & MaskedCatchBlock) != 0;
+public void setNonExternalizedStringLiteralSeverity(int flag) {
+ errorThreshold &= ~NonExternalizedString;
+ warningThreshold &= ~NonExternalizedString;
+ switch(flag){
+ case Error :
+ errorThreshold |= NonExternalizedString;
+ break;
+ case Warning :
+ warningThreshold |= NonExternalizedString;
+ break;
+ }
}
-public boolean isMethodWithConstructorNameHandledAsWarning() {
- return (warningThreshold & MethodWithConstructorName) != 0;
+public void setAssertIdentifierSeverity(int flag) {
+ errorThreshold &= ~AssertUsedAsAnIdentifier;
+ warningThreshold &= ~AssertUsedAsAnIdentifier;
+ switch(flag){
+ case Error :
+ errorThreshold |= AssertUsedAsAnIdentifier;
+ break;
+ case Warning :
+ warningThreshold |= AssertUsedAsAnIdentifier;
+ break;
+ }
}
-public boolean isObsoleteLiteralAsHandledError() {
- return (errorThreshold & ParsingOptionalError) != 0;
+public int getAccessEmulationSeverity() {
+ if((warningThreshold & AccessEmulation) != 0)
+ return Warning;
+ if((errorThreshold & AccessEmulation) != 0)
+ return Error;
+ return Ignore;
+}
+public int getDeprecationUseSeverity() {
+ if((warningThreshold & UsingDeprecatedAPI) != 0)
+ return Warning;
+ if((errorThreshold & UsingDeprecatedAPI) != 0)
+ return Error;
+ return Ignore;
+}
+public int getImportProblemSeverity() {
+ if((warningThreshold & ImportProblem) != 0)
+ return Warning;
+ if((errorThreshold & ImportProblem) != 0)
+ return Error;
+ return Ignore;
+}
+public int getMaskedCatchBlockSeverity() {
+ if((warningThreshold & MaskedCatchBlock) != 0)
+ return Warning;
+ if((errorThreshold & MaskedCatchBlock) != 0)
+ return Error;
+ return Ignore;
+}
+public int getMethodWithConstructorNameSeverity() {
+ if((warningThreshold & MethodWithConstructorName) != 0)
+ return Warning;
+ if((errorThreshold & MethodWithConstructorName) != 0)
+ return Error;
+ return Ignore;
}
-public boolean isOverriddenPackageDefaultMethodHandledAsWarning() {
- return (warningThreshold & OverriddenPackageDefaultMethod) != 0;
+
+public int getOverriddenPackageDefaultMethodSeverity() {
+ if((warningThreshold & OverriddenPackageDefaultMethod) != 0)
+ return Warning;
+ if((errorThreshold & OverriddenPackageDefaultMethod) != 0)
+ return Error;
+ return Ignore;
}
public boolean isPreservingAllLocalVariables() {
return this.preserveAllLocalVariables ;
@@ -281,14 +284,40 @@ public boolean isPreservingAllLocalVariables() {
public boolean isPrivateConstructorAccessChangingVisibility() {
return isPrivateConstructorAccessChangingVisibility;
}
-public boolean isUnreachableCodeHandledAsError() {
- return (errorThreshold & UnreachableCode) != 0;
-}
-public boolean isUnusedArgumentHandledAsWarning() {
- return (warningThreshold & UnusedArgument) != 0;
-}
-public boolean isUnusedLocalVariableHandledAsWarning() {
- return (warningThreshold & UnusedLocalVariable) != 0;
+public int getUnreachableCodeHandledAsError() {
+ if((warningThreshold & UnreachableCode) != 0)
+ return Warning;
+ if((errorThreshold & UnreachableCode) != 0)
+ return Error;
+ return Ignore;
+}
+public int getUnusedArgumentSeverity() {
+ if((warningThreshold & UnusedArgument) != 0)
+ return Warning;
+ if((errorThreshold & UnusedArgument) != 0)
+ return Error;
+ return Ignore;
+}
+public int getUnusedLocalVariableSeverity() {
+ if((warningThreshold & UnusedLocalVariable) != 0)
+ return Warning;
+ if((errorThreshold & UnusedLocalVariable) != 0)
+ return Error;
+ return Ignore;
+}
+public int getNonExternalizedStringLiteralSeverity() {
+ if((warningThreshold & NonExternalizedString) != 0)
+ return Warning;
+ if((errorThreshold & NonExternalizedString) != 0)
+ return Error;
+ return Ignore;
+}
+public int getAssertIdentifierSeverity() {
+ if((warningThreshold & NonExternalizedString) != 0)
+ return Warning;
+ if((errorThreshold & NonExternalizedString) != 0)
+ return Error;
+ return Ignore;
}
public void preserveAllLocalVariables(boolean flag) {
this.preserveAllLocalVariables = flag;
@@ -306,98 +335,184 @@ public void setErrorThreshold(int errorMask) {
this.errorThreshold = errorMask;
}
/**
- * Change the value of the option corresponding to the option number
- *
- * @param optionNumber <CODE>int</CODE>
- * @param setting.getCurrentValueIndex() <CODE>int</CODE>
+ * Change the value of the option corresponding to the option ID
*/
void setOption(ConfigurableOption setting) {
+ String componentName = Compiler.class.getName();
- switch (setting.getID()) {
- case 1 : // Local variable table attribute
- if (setting.getCurrentValueIndex() == 0) {
- // set the debug flag with Vars.
- produceDebugAttributes |= Vars;
- } else {
- produceDebugAttributes &= ~Vars;
- }
- break;
- case 2 : // Line number attribute
- if (setting.getCurrentValueIndex() == 0) {
- // set the debug flag with Lines
- produceDebugAttributes |= Lines;
- } else {
- produceDebugAttributes &= ~Lines;
- }
- break;
- case 3 : // source file attribute
- if (setting.getCurrentValueIndex() == 0) {
- // set the debug flag with Source.
- produceDebugAttributes |= Source;
- } else {
- produceDebugAttributes &= ~Source;
- }
- break;
- case 4 : // preserveAllLocals flag
- preserveAllLocalVariables(setting.getCurrentValueIndex() == 0);
- break;
- case 5 : // unreachable code reported as error
- handleUnreachableCodeAsError(setting.getCurrentValueIndex() == 0);
- break;
- case 6 : // invalid import
- handleImportProblemAsError(setting.getCurrentValueIndex() == 0);
- break;
- case 7 : // methods with constructor name
- handleMethodWithConstructorNameAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 8 : // overridden package default method
- handleOverriddenPackageDefaultMethodAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 9 : // use of deprecated API
- handleDeprecationUseAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 10 : // catch block hidden by another one
- handleMaskedCatchBlockAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 11 : // local variable not used
- handleUnusedLocalVariableAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 12 : // argument not used
- handleUnusedArgumentAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 13 : // temporary warning
- if (setting.getCurrentValueIndex() == 0) {
- warningThreshold |= TemporaryWarning;
- }
- break;
- case 14 : // target JDK
- setTargetJDK(setting.getCurrentValueIndex() == 0 ? JDK1_1 : JDK1_2);
- break;
- case 15: // synthetic access emulation
- handleAccessEmulationAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 16: // non externalized string literal
- handleNonExternalizedStringLiteralAsWarning(setting.getCurrentValueIndex() == 0);
- break;
- case 17: // assertion mode
- setAssertMode(setting.getCurrentValueIndex() == 0);
- break;
- case 18: // warn on assert identifier
- handleAssertIdentifierAsWarning(setting.getCurrentValueIndex() == 0);
- break;
+ String optionID = setting.getID();
+
+ if(optionID.equals(OPTION_LocalVariableAttribute)){
+ if (setting.getValueIndex() == 0) {
+ // set the debug flag with Vars.
+ produceDebugAttributes |= Vars;
+ } else {
+ produceDebugAttributes &= ~Vars;
+ }
+ } else if(optionID.equals(OPTION_LineNumberAttribute)) {
+ if (setting.getValueIndex() == 0) {
+ // set the debug flag with Lines
+ produceDebugAttributes |= Lines;
+ } else {
+ produceDebugAttributes &= ~Lines;
+ }
+ }else if(optionID.equals(OPTION_SourceFileAttribute)) {
+ if (setting.getValueIndex() == 0) {
+ // set the debug flag with Source.
+ produceDebugAttributes |= Source;
+ } else {
+ produceDebugAttributes &= ~Source;
+ }
+ }else if(optionID.equals(OPTION_PreserveUnusedLocal)){
+ preserveAllLocalVariables(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_ReportUnreachableCode)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setUnreachableCodeSeverity(Error);
+ break;
+ case 1 :
+ setUnreachableCodeSeverity(Warning);
+ break;
+ case 2 :
+ setUnreachableCodeSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportInvalidImport)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setImportProblemSeverity(Error);
+ break;
+ case 1 :
+ setImportProblemSeverity(Warning);
+ break;
+ case 2 :
+ setImportProblemSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_TargetPlatform)){
+ setTargetJDK(setting.getValueIndex() == 0 ? JDK1_1 : JDK1_2);
+ }else if(optionID.equals(OPTION_ReportMethodWithConstructorName)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setMethodWithConstructorNameSeverity(Error);
+ break;
+ case 1 :
+ setMethodWithConstructorNameSeverity(Warning);
+ break;
+ case 2 :
+ setMethodWithConstructorNameSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportOverridingPackageDefaultMethod)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setOverriddenPackageDefaultMethodSeverity(Error);
+ break;
+ case 1 :
+ setOverriddenPackageDefaultMethodSeverity(Warning);
+ break;
+ case 2 :
+ setOverriddenPackageDefaultMethodSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportDeprecation)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setDeprecationUseSeverity(Error);
+ break;
+ case 1 :
+ setDeprecationUseSeverity(Warning);
+ break;
+ case 2 :
+ setDeprecationUseSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportHiddenCatchBlock)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setMaskedCatchBlockSeverity(Error);
+ break;
+ case 1 :
+ setMaskedCatchBlockSeverity(Warning);
+ break;
+ case 2 :
+ setMaskedCatchBlockSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportUnusedLocal)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setUnusedLocalVariableSeverity(Error);
+ break;
+ case 1 :
+ setUnusedLocalVariableSeverity(Warning);
+ break;
+ case 2 :
+ setUnusedLocalVariableSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportUnusedParameter)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setUnusedArgumentSeverity(Error);
+ break;
+ case 1 :
+ setUnusedArgumentSeverity(Warning);
+ break;
+ case 2 :
+ setUnusedArgumentSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportSyntheticAccessEmulation)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setAccessEmulationSeverity(Error);
+ break;
+ case 1 :
+ setAccessEmulationSeverity(Warning);
+ break;
+ case 2 :
+ setAccessEmulationSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportNonExternalizedStringLiteral)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setNonExternalizedStringLiteralSeverity(Error);
+ break;
+ case 1 :
+ setNonExternalizedStringLiteralSeverity(Warning);
+ break;
+ case 2 :
+ setNonExternalizedStringLiteralSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_ReportAssertIdentifier)){
+ switch(setting.getValueIndex()){
+ case 0 :
+ setAssertIdentifierSeverity(Error);
+ break;
+ case 1 :
+ setAssertIdentifierSeverity(Warning);
+ break;
+ case 2 :
+ setAssertIdentifierSeverity(Ignore);
+ break;
+ }
+ }else if(optionID.equals(OPTION_Source)){
+ setAssertMode(setting.getValueIndex() == 1);
}
}
+
public void setTargetJDK(int vmID) {
this.targetJDK = vmID;
}
-
-public void setAssertMode(boolean assertMode) {
- this.assertMode = assertMode;
-}
-
public void setVerboseMode(boolean flag) {
this.verbose = flag;
}
+public void setAssertMode(boolean assertMode) {
+ this.assertMode = assertMode;
+}
public void setWarningThreshold(int warningMask) {
this.warningThreshold = warningMask;
}
@@ -527,28 +642,4 @@ public String toString() {
buf.append("\n-runtime exception name for compile error : "/*nonNLS*/ + runtimeExceptionNameForCompileError);
return buf.toString();
}
-
-public void handleNonExternalizedStringLiteralAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= NonExternalizedString;
- } else {
- warningThreshold &= ~NonExternalizedString;
- }
-}
-
-public boolean isNonExternalizedStringLiteralHandledAsWarning() {
- return (warningThreshold & NonExternalizedString) != 0;
-}
-
-public void handleAssertIdentifierAsWarning(boolean flag) {
- if (flag) {
- warningThreshold |= AssertUsedAsAnIdentifier;
- } else {
- warningThreshold &= ~AssertUsedAsAnIdentifier;
- }
-}
-
-public boolean isAssertIdentifierHandledAsWarning() {
- return (warningThreshold & AssertUsedAsAnIdentifier) != 0;
-}
}
diff --git a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/ConfigurableProblems.java b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/ConfigurableProblems.java
index ca927af95b..033843d507 100644
--- a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/ConfigurableProblems.java
+++ b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/ConfigurableProblems.java
@@ -9,7 +9,6 @@ import org.eclipse.jdt.internal.compiler.*;
public interface ConfigurableProblems {
final int UnreachableCode = 0x100;
- final int ParsingOptionalError = 0x200;
final int ImportProblem = 0x400;
final int MethodWithConstructorName = 0x1000;
final int OverriddenPackageDefaultMethod = 0x2000;
diff --git a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
index a3a4c7efcd..bcfd3dd956 100644
--- a/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
+++ b/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/parser/Parser.java
@@ -6055,7 +6055,7 @@ public void initialize() {
lastErrorEndPosition = -1;
}
public void initializeScanner(){
- this.scanner = new Scanner(false, false, this.problemReporter.options.isNonExternalizedStringLiteralHandledAsWarning(), this.assertMode);
+ this.scanner = new Scanner(false, false, this.problemReporter.options.getNonExternalizedStringLiteralSeverity() != ProblemSeverities.Ignore , this.assertMode);
}
public final static void initTables() throws java.io.IOException {
diff --git a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java
index 85c49c1353..ccef17092b 100644
--- a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java
+++ b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java
@@ -22,112 +22,112 @@ import java.util.Locale;
public class CodeFormatter implements TerminalSymbols {
- public FormatterOptions options;
-
- /**
- * Represents a block in the <code>constructions</code> stack.
- */
- public static final int BLOCK = TerminalSymbols.TokenNameLBRACE;
- /**
- * Represents a block following a control statement in the <code>constructions</code> stack.
- */
- public static final int NONINDENT_BLOCK = -100;
- /**
- * Contains the formatted output.
- */
- StringBuffer formattedSource;
- /**
- * Contains the current line.<br>
- * Will be dumped at the next "newline"
- */
- StringBuffer currentLineBuffer;
-
- /**
- * Used during the formatting to get each token.
- */
- Scanner scanner;
-
- /**
- * Contains the tokens responsible for the current indentation level
- * and the blocks not closed yet.
- */
- private int[] constructions;
- /**
- * Index in the <code>constructions</code> array.
- */
- private int constructionsCount;
- /**
- * Level of indentation of the current token (number of tab char put in front of it).
- */
- private int indentationLevel;
-
- /**
- * Regular level of indentation of all the lines
- */
- private int initialIndentationLevel;
-
- /**
- * Used to split a line.
- */
- Scanner splitScanner;
- /**
- * To remember the offset between the beginning of the line and the
- * beginning of the comment.
- */
- int currentCommentOffset;
- int currentLineIndentationLevel;
- int maxLineSize = 30;
- private boolean containsOpenCloseBraces;
- private int indentationLevelForOpenCloseBraces;
-
- /**
- * Collections of positions to map
- */
- private int[] positionsToMap;
-
- /**
- * Collections of mapped positions
- */
- private int[] mappedPositions;
-
- private int indexToMap;
-
- private int indexInMap;
-
- private int globalDelta;
-
- private int lineDelta;
-
- private int splitDelta;
-
- private int beginningOfLineIndex;
+ public FormatterOptions options;
+
+ /**
+ * Represents a block in the <code>constructions</code> stack.
+ */
+ public static final int BLOCK = TerminalSymbols.TokenNameLBRACE;
+ /**
+ * Represents a block following a control statement in the <code>constructions</code> stack.
+ */
+ public static final int NONINDENT_BLOCK = -100;
+ /**
+ * Contains the formatted output.
+ */
+ StringBuffer formattedSource;
+ /**
+ * Contains the current line.<br>
+ * Will be dumped at the next "newline"
+ */
+ StringBuffer currentLineBuffer;
+
+ /**
+ * Used during the formatting to get each token.
+ */
+ Scanner scanner;
+
+ /**
+ * Contains the tokens responsible for the current indentation level
+ * and the blocks not closed yet.
+ */
+ private int[] constructions;
+ /**
+ * Index in the <code>constructions</code> array.
+ */
+ private int constructionsCount;
+ /**
+ * Level of indentation of the current token (number of tab char put in front of it).
+ */
+ private int indentationLevel;
+
+ /**
+ * Regular level of indentation of all the lines
+ */
+ private int initialIndentationLevel;
+
+ /**
+ * Used to split a line.
+ */
+ Scanner splitScanner;
+ /**
+ * To remember the offset between the beginning of the line and the
+ * beginning of the comment.
+ */
+ int currentCommentOffset;
+ int currentLineIndentationLevel;
+ int maxLineSize = 30;
+ private boolean containsOpenCloseBraces;
+ private int indentationLevelForOpenCloseBraces;
+
+ /**
+ * Collections of positions to map
+ */
+ private int[] positionsToMap;
+
+ /**
+ * Collections of mapped positions
+ */
+ private int[] mappedPositions;
+
+ private int indexToMap;
+
+ private int indexInMap;
+
+ private int globalDelta;
+
+ private int lineDelta;
+
+ private int splitDelta;
+
+ private int beginningOfLineIndex;
/**
* Creates a new instance of Code Formatter using the FormattingOptions object
* given as argument
* @deprecated Use CodeFormatter(ConfigurableOption[]) instead
*/
public CodeFormatter() {
- this(null);
+ this(null);
}
/**
* Creates a new instance of Code Formatter using the given settings.
*/
public CodeFormatter(ConfigurableOption[] settings) {
- // initialize internal state
- constructionsCount = 0;
- constructions = new int[10];
- currentLineIndentationLevel = indentationLevel = initialIndentationLevel;
- currentCommentOffset = -1;
-
- // initialize primary and secondary scanners
- scanner = new Scanner(true,true); // regular scanner for forming lines
- scanner.recordLineSeparator = true; // to remind of the position of the beginning of the line.
- splitScanner = new Scanner(true,true); // secondary scanner to split long lines formed by primary scanning
-
- // initialize current line buffer
- currentLineBuffer = new StringBuffer();
- this.options = new FormatterOptions(settings);
+ // initialize internal state
+ constructionsCount = 0;
+ constructions = new int[10];
+ currentLineIndentationLevel = indentationLevel = initialIndentationLevel;
+ currentCommentOffset = -1;
+
+ // initialize primary and secondary scanners
+ scanner = new Scanner(true,true); // regular scanner for forming lines
+ scanner.recordLineSeparator = true; // to remind of the position of the beginning of the line.
+ splitScanner = new Scanner(true,true); // secondary scanner to split long lines formed by primary scanning
+
+ // initialize current line buffer
+ currentLineBuffer = new StringBuffer();
+ this.options = new FormatterOptions(settings);
}
/**
* Sets the behaviour of the formatter about the braces using the given flag.<br>
@@ -140,761 +140,761 @@ public CodeFormatter(ConfigurableOption[] settings) {
/** */
public void addNewLineOnOpeningBrace(boolean flag) {
- options.setNewLineBeforeOpeningBraceMode(flag);
+ options.setNewLineBeforeOpeningBraceMode(flag);
}
/**
* Returns true if a lineSeparator has to be inserted before <code>operator</code>
* false otherwise.
*/
private static boolean breakLineBeforeOperator(int operator) {
- switch (operator) {
- case TokenNameCOMMA :
- case TokenNameSEMICOLON :
- case TokenNameEQUAL :
- return false;
- default :
- return true;
- }
+ switch (operator) {
+ case TokenNameCOMMA :
+ case TokenNameSEMICOLON :
+ case TokenNameEQUAL :
+ return false;
+ default :
+ return true;
+ }
}
/**
* Returns the end of the source code.
*/
private final String copyRemainingSource() {
- char str[] = scanner.source;
- int startPosition = scanner.startPosition;
- int length = str.length - startPosition;
- StringBuffer bufr = new StringBuffer(length);
- if (startPosition < str.length) {
- bufr.append(str, startPosition, length);
- }
- return (bufr.toString());
+ char str[] = scanner.source;
+ int startPosition = scanner.startPosition;
+ int length = str.length - startPosition;
+ StringBuffer bufr = new StringBuffer(length);
+ if (startPosition < str.length) {
+ bufr.append(str, startPosition, length);
+ }
+ return (bufr.toString());
}
/**
* Inserts <code>tabCount</code> tab character or their equivalent number of spaces.
*/
private void dumpTab(int tabCount) {
- if (options.indentWithTab) {
- for (int j = 0; j < tabCount; j++) {
- formattedSource.append('\t');
- increaseSplitDelta(1);
- }
- } else {
- for (int i = 0, max = options.tabSize * tabCount; i < max; i++) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- }
+ if (options.indentWithTab) {
+ for (int j = 0; j < tabCount; j++) {
+ formattedSource.append('\t');
+ increaseSplitDelta(1);
+ }
+ } else {
+ for (int i = 0, max = options.tabSize * tabCount; i < max; i++) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ }
}
/**
* Dumps <code>currentLineBuffer</code> into the formatted string.
*/
private void flushBuffer() {
- String currentString = currentLineBuffer.toString();
- splitDelta = 0;
- beginningOfLineIndex = formattedSource.length();
- if (options.maxLineLength!=0){
- if (containsOpenCloseBraces) {
- containsOpenCloseBraces = false;
- outputLine(currentString,
- false,
- indentationLevelForOpenCloseBraces,
- 0,
- -1,
- null,
- 0);
- indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
- } else {
- outputLine(currentString,
- false,
- currentLineIndentationLevel,
- 0,
- -1,
- null,
- 0);
- }
- } else {
- formattedSource.append(currentString);
- }
+ String currentString = currentLineBuffer.toString();
+ splitDelta = 0;
+ beginningOfLineIndex = formattedSource.length();
+ if (options.maxLineLength!=0){
+ if (containsOpenCloseBraces) {
+ containsOpenCloseBraces = false;
+ outputLine(currentString,
+ false,
+ indentationLevelForOpenCloseBraces,
+ 0,
+ -1,
+ null,
+ 0);
+ indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
+ } else {
+ outputLine(currentString,
+ false,
+ currentLineIndentationLevel,
+ 0,
+ -1,
+ null,
+ 0);
+ }
+ } else {
+ formattedSource.append(currentString);
+ }
}
/**
* Formats the input string.
*/
private void format() {
- int token = 0;
- int previousToken = 0;
- int previousCompilableToken = 0;
-
- int indentationOffset = 0;
-
- int newLinesInWhitespace = 0;
- // number of new lines in the previous whitespace token
- // (used to leave blank lines before comments)
- int pendingNewLines = 0;
- boolean expectingOpenBrace = false;
- boolean clearNonBlockIndents = false;
- // true if all indentations till the 1st { (usefull after } or ;)
- boolean pendingSpace = true;
- boolean pendingNewlineAfterParen = false;
- // true when a cr is to be put after a ) (in conditional statements)
- boolean inAssignment = false;
- boolean inArrayAssignment = false;
- boolean inThrowsClause = false;
- boolean inClassOrInterfaceHeader = false;
-
- // openBracketCount is used to count the number of open brackets not closed yet.
- int openBracketCount = 0;
-
- int unarySignModifier = 0;
-
- // openParenthesis[0] is used to count the parenthesis not belonging to a condition
- // (eg foo();). parenthesis in for (...) are count elsewhere in the array.
- int openParenthesisCount = 1;
- int[] openParenthesis = new int[10];
-
- // tokenBeforeColon is used to know what token goes along with the current :
- // it can be case or ?
- int tokenBeforeColonCount = 0;
- int[] tokenBeforeColon = new int[10];
-
- constructionsCount = 0; // initializes the constructions count.
-
- // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise.
- int nlicsToken = 0;
-
- // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and else
- boolean specialElse = false;
-
- // OPTION (IndentationLevel): initial indentation level may be non-zero.
- currentLineIndentationLevel += constructionsCount;
-
-
- // An InvalidInputException exception might cause the termination of this loop.
- try {
- while (true) {
- // Get the next token. Catch invalid input and output it
- // with minimal formatting, also catch end of input and
- // exit the loop.
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
- if (!handleInvalidToken(e)) {
- throw e;
- }
- token = 0;
- }
- if (token == Scanner.TokenNameEOF)
- break;
-
- /* ## MODIFYING the indentation level before generating new lines
- and indentation in the output string
- */
-
- // Removes all the indentations made by statements not followed by a block
- // except if the current token is ELSE, CATCH or if we are in a switch/case
-
- if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) {
-
- switch (token) {
- case TokenNameelse :
- if (constructionsCount > 0 && constructions[constructionsCount-1] == TokenNameelse){
- pendingNewLines = 1;
- specialElse = true;
- }
- indentationLevel += popInclusiveUntil(TokenNameif);
- break;
- case TokenNamecatch :
- indentationLevel += popInclusiveUntil(TokenNamecatch);
- break;
- case TokenNamefinally :
- indentationLevel += popInclusiveUntil(TokenNamecatch);
- break;
- case TokenNamewhile :
- if (nlicsToken == TokenNamedo) {
- indentationLevel += pop(TokenNamedo);
- break;
- }
- default :
- indentationLevel += popExclusiveUntilBlockOrCase();
- // clear until a CASE, DEFAULT or BLOCK is encountered.
- // Thus, the indentationLevel is correctly cleared either
- // in a switch/case statement or in any other situation.
- }
- clearNonBlockIndents = false;
- }
-
- // returns to the indentation level created by the SWITCH keyword
- // if the current token is a CASE or a DEFAULT
-
- if (token == TokenNamecase || token == TokenNamedefault) {
- indentationLevel += pop(TokenNamecase);
- }
-
- if (token == Scanner.TokenNamethrows) {
- inThrowsClause = true;
- }
-
- if (token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) {
- inClassOrInterfaceHeader = true;
- }
- /* ## APPEND newlines and indentations to the output string
- */
-
- // Do not add a new line between ELSE and IF, if the option elseIfOnSameLine is true.
- // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting
- if (pendingNewlineAfterParen && previousCompilableToken == TokenNameelse && token == TokenNameif && options.compactElseIfMode){
- pendingNewlineAfterParen = false;
- pendingNewLines = 0;
- indentationLevel += pop(TokenNameelse);
- // because else if is now one single statement,
- // the indentation level after it is increased by one and not by 2
- // (else = 1 indent, if = 1 indent, but else if = 1 indent, not 2).
- }
-
- // Add a newline & indent to the formatted source string if
- // a for/if-else/while statement was scanned and there is no block
- // following it.
-
- pendingNewlineAfterParen = pendingNewlineAfterParen || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE);
- if (pendingNewlineAfterParen && token != Scanner.TokenNameWHITESPACE) {
- pendingNewlineAfterParen = false;
-
- // Do to add a newline & indent sequence if the current token is an
- // open brace or a period or if the current token is a semi-colon and the
- // previous token is a close paren.
- // add a new line if a parenthesis belonging to a for() statement
- // has been closed and the current token is not an opening brace
-
- if (token != TokenNameLBRACE && !isComment(token)
- // to avoid adding new line between else and a comment
- && token != TokenNameDOT
- && ! (previousCompilableToken == TokenNameRPAREN
- && token == TokenNameSEMICOLON)) {
- newLine(1);
- currentLineIndentationLevel = indentationLevel;
- pendingNewLines = 0;
- pendingSpace = false;
- } else {
- if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) {
- newLine(1);
- if (constructionsCount > 0
- && constructions[constructionsCount - 1] != BLOCK
- && constructions[constructionsCount - 1] != NONINDENT_BLOCK) {
- currentLineIndentationLevel = indentationLevel - 1;
- } else {
- currentLineIndentationLevel = indentationLevel;
- }
- pendingNewLines = 0;
- pendingSpace = false;
- }
- }
- }
-
- if (token == TokenNameLBRACE
- && options.newLineBeforeOpeningBraceMode
- && constructionsCount > 0
- && constructions[constructionsCount - 1] == TokenNamedo) {
- newLine(1);
- currentLineIndentationLevel = indentationLevel - 1;
- pendingNewLines = 0;
- pendingSpace = false;
- }
-
- // see PR 1G5G8EC
- if (token == TokenNameLBRACE && inThrowsClause) {
- inThrowsClause = false;
- if (options.newLineBeforeOpeningBraceMode) {
- newLine(1);
- currentLineIndentationLevel = indentationLevel;
- pendingNewLines = 0;
- pendingSpace = false;
- }
- }
-
- // see PR 1G5G82G
- if (token == TokenNameLBRACE && inClassOrInterfaceHeader) {
- inClassOrInterfaceHeader = false;
- if (options.newLineBeforeOpeningBraceMode) {
- newLine(1);
- currentLineIndentationLevel = indentationLevel;
- pendingNewLines = 0;
- pendingSpace = false;
- }
- }
- // Add pending new lines to the formatted source string.
- // Note: pending new lines are not added if the current token
- // is a single line comment or whitespace.
- // if the comment is between parenthesis, there is no blank line preservation
- // (if it's a one-line comment, a blank line is added after it).
-
- if (((pendingNewLines > 0 && (!isComment(token)))
- || (newLinesInWhitespace > 0
- && (openParenthesisCount <= 1 && isComment(token)))
- || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE))
- && token != Scanner.TokenNameWHITESPACE) {
-
- // Do not add newline & indent between an adjoining close brace and
- // close paren. Anonymous inner classes may use this form.
-
- boolean closeBraceAndCloseParen =
- previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
-
- // OPTION (NewLineInCompoundStatement): do not add newline & indent
- // between close brace and else, (do) while, catch, and finally if
- // newlineInCompoundStatement is true.
-
- boolean nlicsOption =
- previousToken == TokenNameRBRACE
- && !options.newlineInControlStatementMode
- && (token == TokenNameelse
- || (token == TokenNamewhile && nlicsToken == TokenNamedo)
- || token == TokenNamecatch
- || token == TokenNamefinally);
-
- // Do not add a newline & indent between a close brace and semi-colon.
-
- boolean semiColonAndCloseBrace =
- previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
-
- // Do not add a new line & indent between a multiline comment and a opening brace
-
- boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
-
- // Do not add a newline & indent between a close brace and a colon (in array assignments, for example).
-
- boolean commaAndCloseBrace =
- previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
-
- // Add a newline and indent, if appropriate.
-
- if (specialElse || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) {
- // if clearAllBlankLinesMode=false, leaves the blank lines
- // inserted by the user
- // if clearAllBlankLinesMode=true, removes all of then
- // and insert only blank lines required by the formatting.
- if (!options.clearAllBlankLinesMode) {
- pendingNewLines =
- (pendingNewLines < newLinesInWhitespace)
+ int token = 0;
+ int previousToken = 0;
+ int previousCompilableToken = 0;
+
+ int indentationOffset = 0;
+
+ int newLinesInWhitespace = 0;
+ // number of new lines in the previous whitespace token
+ // (used to leave blank lines before comments)
+ int pendingNewLines = 0;
+ boolean expectingOpenBrace = false;
+ boolean clearNonBlockIndents = false;
+ // true if all indentations till the 1st { (usefull after } or ;)
+ boolean pendingSpace = true;
+ boolean pendingNewlineAfterParen = false;
+ // true when a cr is to be put after a ) (in conditional statements)
+ boolean inAssignment = false;
+ boolean inArrayAssignment = false;
+ boolean inThrowsClause = false;
+ boolean inClassOrInterfaceHeader = false;
+
+ // openBracketCount is used to count the number of open brackets not closed yet.
+ int openBracketCount = 0;
+
+ int unarySignModifier = 0;
+
+ // openParenthesis[0] is used to count the parenthesis not belonging to a condition
+ // (eg foo();). parenthesis in for (...) are count elsewhere in the array.
+ int openParenthesisCount = 1;
+ int[] openParenthesis = new int[10];
+
+ // tokenBeforeColon is used to know what token goes along with the current :
+ // it can be case or ?
+ int tokenBeforeColonCount = 0;
+ int[] tokenBeforeColon = new int[10];
+
+ constructionsCount = 0; // initializes the constructions count.
+
+ // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise.
+ int nlicsToken = 0;
+
+ // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and else
+ boolean specialElse = false;
+
+ // OPTION (IndentationLevel): initial indentation level may be non-zero.
+ currentLineIndentationLevel += constructionsCount;
+
+
+ // An InvalidInputException exception might cause the termination of this loop.
+ try {
+ while (true) {
+ // Get the next token. Catch invalid input and output it
+ // with minimal formatting, also catch end of input and
+ // exit the loop.
+ try {
+ token = scanner.getNextToken();
+ } catch (InvalidInputException e) {
+ if (!handleInvalidToken(e)) {
+ throw e;
+ }
+ token = 0;
+ }
+ if (token == Scanner.TokenNameEOF)
+ break;
+
+ /* ## MODIFYING the indentation level before generating new lines
+ and indentation in the output string
+ */
+
+ // Removes all the indentations made by statements not followed by a block
+ // except if the current token is ELSE, CATCH or if we are in a switch/case
+
+ if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) {
+
+ switch (token) {
+ case TokenNameelse :
+ if (constructionsCount > 0 && constructions[constructionsCount-1] == TokenNameelse){
+ pendingNewLines = 1;
+ specialElse = true;
+ }
+ indentationLevel += popInclusiveUntil(TokenNameif);
+ break;
+ case TokenNamecatch :
+ indentationLevel += popInclusiveUntil(TokenNamecatch);
+ break;
+ case TokenNamefinally :
+ indentationLevel += popInclusiveUntil(TokenNamecatch);
+ break;
+ case TokenNamewhile :
+ if (nlicsToken == TokenNamedo) {
+ indentationLevel += pop(TokenNamedo);
+ break;
+ }
+ default :
+ indentationLevel += popExclusiveUntilBlockOrCase();
+ // clear until a CASE, DEFAULT or BLOCK is encountered.
+ // Thus, the indentationLevel is correctly cleared either
+ // in a switch/case statement or in any other situation.
+ }
+ clearNonBlockIndents = false;
+ }
+
+ // returns to the indentation level created by the SWITCH keyword
+ // if the current token is a CASE or a DEFAULT
+
+ if (token == TokenNamecase || token == TokenNamedefault) {
+ indentationLevel += pop(TokenNamecase);
+ }
+
+ if (token == Scanner.TokenNamethrows) {
+ inThrowsClause = true;
+ }
+
+ if (token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) {
+ inClassOrInterfaceHeader = true;
+ }
+ /* ## APPEND newlines and indentations to the output string
+ */
+
+ // Do not add a new line between ELSE and IF, if the option elseIfOnSameLine is true.
+ // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting
+ if (pendingNewlineAfterParen && previousCompilableToken == TokenNameelse && token == TokenNameif && options.compactElseIfMode){
+ pendingNewlineAfterParen = false;
+ pendingNewLines = 0;
+ indentationLevel += pop(TokenNameelse);
+ // because else if is now one single statement,
+ // the indentation level after it is increased by one and not by 2
+ // (else = 1 indent, if = 1 indent, but else if = 1 indent, not 2).
+ }
+
+ // Add a newline & indent to the formatted source string if
+ // a for/if-else/while statement was scanned and there is no block
+ // following it.
+
+ pendingNewlineAfterParen = pendingNewlineAfterParen || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE);
+ if (pendingNewlineAfterParen && token != Scanner.TokenNameWHITESPACE) {
+ pendingNewlineAfterParen = false;
+
+ // Do to add a newline & indent sequence if the current token is an
+ // open brace or a period or if the current token is a semi-colon and the
+ // previous token is a close paren.
+ // add a new line if a parenthesis belonging to a for() statement
+ // has been closed and the current token is not an opening brace
+
+ if (token != TokenNameLBRACE && !isComment(token)
+ // to avoid adding new line between else and a comment
+ && token != TokenNameDOT
+ && ! (previousCompilableToken == TokenNameRPAREN
+ && token == TokenNameSEMICOLON)) {
+ newLine(1);
+ currentLineIndentationLevel = indentationLevel;
+ pendingNewLines = 0;
+ pendingSpace = false;
+ } else {
+ if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) {
+ newLine(1);
+ if (constructionsCount > 0
+ && constructions[constructionsCount - 1] != BLOCK
+ && constructions[constructionsCount - 1] != NONINDENT_BLOCK) {
+ currentLineIndentationLevel = indentationLevel - 1;
+ } else {
+ currentLineIndentationLevel = indentationLevel;
+ }
+ pendingNewLines = 0;
+ pendingSpace = false;
+ }
+ }
+ }
+
+ if (token == TokenNameLBRACE
+ && options.newLineBeforeOpeningBraceMode
+ && constructionsCount > 0
+ && constructions[constructionsCount - 1] == TokenNamedo) {
+ newLine(1);
+ currentLineIndentationLevel = indentationLevel - 1;
+ pendingNewLines = 0;
+ pendingSpace = false;
+ }
+
+ // see PR 1G5G8EC
+ if (token == TokenNameLBRACE && inThrowsClause) {
+ inThrowsClause = false;
+ if (options.newLineBeforeOpeningBraceMode) {
+ newLine(1);
+ currentLineIndentationLevel = indentationLevel;
+ pendingNewLines = 0;
+ pendingSpace = false;
+ }
+ }
+
+ // see PR 1G5G82G
+ if (token == TokenNameLBRACE && inClassOrInterfaceHeader) {
+ inClassOrInterfaceHeader = false;
+ if (options.newLineBeforeOpeningBraceMode) {
+ newLine(1);
+ currentLineIndentationLevel = indentationLevel;
+ pendingNewLines = 0;
+ pendingSpace = false;
+ }
+ }
+ // Add pending new lines to the formatted source string.
+ // Note: pending new lines are not added if the current token
+ // is a single line comment or whitespace.
+ // if the comment is between parenthesis, there is no blank line preservation
+ // (if it's a one-line comment, a blank line is added after it).
+
+ if (((pendingNewLines > 0 && (!isComment(token)))
+ || (newLinesInWhitespace > 0
+ && (openParenthesisCount <= 1 && isComment(token)))
+ || (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE))
+ && token != Scanner.TokenNameWHITESPACE) {
+
+ // Do not add newline & indent between an adjoining close brace and
+ // close paren. Anonymous inner classes may use this form.
+
+ boolean closeBraceAndCloseParen =
+ previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
+
+ // OPTION (NewLineInCompoundStatement): do not add newline & indent
+ // between close brace and else, (do) while, catch, and finally if
+ // newlineInCompoundStatement is true.
+
+
+ boolean nlicsOption =
+ previousToken == TokenNameRBRACE
+ && !options.newlineInControlStatementMode
+ && (token == TokenNameelse
+ || (token == TokenNamewhile && nlicsToken == TokenNamedo)
+ || token == TokenNamecatch
+ || token == TokenNamefinally);
+
+ // Do not add a newline & indent between a close brace and semi-colon.
+
+ boolean semiColonAndCloseBrace =
+ previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
+
+ // Do not add a new line & indent between a multiline comment and a opening brace
+
+ boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
+
+ // Do not add a newline & indent between a close brace and a colon (in array assignments, for example).
+
+ boolean commaAndCloseBrace =
+ previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
+
+ // Add a newline and indent, if appropriate.
+
+ if (specialElse || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) {
+ // if clearAllBlankLinesMode=false, leaves the blank lines
+ // inserted by the user
+ // if clearAllBlankLinesMode=true, removes all of then
+ // and insert only blank lines required by the formatting.
+ if (!options.clearAllBlankLinesMode) {
+ pendingNewLines =
+ (pendingNewLines < newLinesInWhitespace)
// (isComment(token))
- ? newLinesInWhitespace
- : pendingNewLines;
- pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
- }
-
- if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
- containsOpenCloseBraces = true;
- indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
- if (isComment(previousToken)) {
- newLine(pendingNewLines);
- } else {
+ ? newLinesInWhitespace
+ : pendingNewLines;
+ pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
+ }
+
+ if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
+ containsOpenCloseBraces = true;
+ indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
+ if (isComment(previousToken)) {
+ newLine(pendingNewLines);
+ } else {
/* if (!(constructionsCount > 1
- && constructions[constructionsCount-1] == NONINDENT_BLOCK
- && (constructions[constructionsCount-2] == TokenNamefor
- || constructions[constructionsCount-2] == TokenNamewhile))) {*/
- if (options.newLineInEmptyBlockMode) {
- if (inArrayAssignment) {
- newLine(1); // array assigment with an empty block
- } else {
- newLine(pendingNewLines);
- }
- }
+ && constructions[constructionsCount-1] == NONINDENT_BLOCK
+ && (constructions[constructionsCount-2] == TokenNamefor
+ || constructions[constructionsCount-2] == TokenNamewhile))) {*/
+ if (options.newLineInEmptyBlockMode) {
+ if (inArrayAssignment) {
+ newLine(1); // array assigment with an empty block
+ } else {
+ newLine(pendingNewLines);
+ }
+ }
// }
- }
- } else {
- // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment before the ';'
- if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_JAVADOC) && token == TokenNameSEMICOLON)) {
- newLine(pendingNewLines);
- }
- }
- if (((previousCompilableToken == TokenNameSEMICOLON)
- || (previousCompilableToken == TokenNameLBRACE)
- || (previousCompilableToken == TokenNameRBRACE)
- || (isComment(previousToken)))
- && (token == TokenNameRBRACE)) {
- indentationOffset = -1;
- indentationLevel += popExclusiveUntilBlock();
- }
-
- if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
- // PR 1FI5IPO
- currentLineIndentationLevel++;
- } else {
- currentLineIndentationLevel = indentationLevel + indentationOffset;
- }
-
- pendingSpace = false;
- indentationOffset = 0;
- }
- pendingNewLines = 0;
- newLinesInWhitespace = 0;
- specialElse = false;
-
- if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
- nlicsToken = 0;
- }
- }
-
- switch (token) {
- case TokenNameelse :
- case TokenNamefinally :
- expectingOpenBrace = true;
- pendingNewlineAfterParen = true;
- indentationLevel += pushControlStatement(token);
- break;
- case TokenNamecase :
- case TokenNamedefault :
- if (tokenBeforeColonCount == tokenBeforeColon.length) {
- System.arraycopy(
- tokenBeforeColon,
- 0,
- (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
- 0,
- tokenBeforeColonCount);
- }
- tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
- indentationLevel += pushControlStatement(TokenNamecase);
- break;
- case TokenNameQUESTION :
- if (tokenBeforeColonCount == tokenBeforeColon.length) {
- System.arraycopy(
- tokenBeforeColon,
- 0,
- (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
- 0,
- tokenBeforeColonCount);
- }
- tokenBeforeColon[tokenBeforeColonCount++] = token;
- break;
- case TokenNameswitch :
- case TokenNamefor :
- case TokenNameif :
- case TokenNamewhile :
- if (openParenthesisCount == openParenthesis.length) {
- System.arraycopy(
- openParenthesis,
- 0,
- (openParenthesis = new int[openParenthesisCount * 2]),
- 0,
- openParenthesisCount);
- }
- openParenthesis[openParenthesisCount++] = 0;
- expectingOpenBrace = true;
-
- indentationLevel += pushControlStatement(token);
- break;
- case TokenNametry :
- pendingNewlineAfterParen = true;
- case TokenNamecatch :
- // several CATCH statements can be contiguous.
- // a CATCH is encountered pop until first CATCH (if a CATCH follows a TRY it works the same way,
- // as CATCH and TRY are the same token in the stack).
- expectingOpenBrace = true;
- indentationLevel += pushControlStatement(TokenNamecatch);
- break;
-
- case TokenNamedo :
- expectingOpenBrace = true;
- indentationLevel += pushControlStatement(token);
- nlicsToken = token;
- break;
- case TokenNameLPAREN :
-
- // Put a space between the previous and current token if the
- // previous token was not a keyword, open paren, logical
- // compliment (eg: !), semi-colon, open brace, close brace,
- // super, or this.
-
- if (previousCompilableToken != TokenNameLBRACKET
- && previousToken != TokenNameIdentifier
- && previousToken != 0
- && previousToken != TokenNameNOT
- && previousToken != TokenNameLPAREN
- && previousToken != TokenNameTWIDDLE
- && previousToken != TokenNameSEMICOLON
- && previousToken != TokenNameLBRACE
- && previousToken != TokenNameRBRACE
- && previousToken != TokenNamesuper
- && previousToken != TokenNamethis) {
- space();
- }
-
- // If in a for/if/while statement, increase the parenthesis count
- // for the current openParenthesisCount
- // else increase the count for stand alone parenthesis.
- if (openParenthesisCount > 0)
- openParenthesis[openParenthesisCount - 1]++;
- else
- openParenthesis[0]++;
-
- pendingSpace = false;
- break;
- case TokenNameRPAREN :
-
- // Decrease the parenthesis count
- // if there is no more unclosed parenthesis,
- // a new line and indent may be append (depending on the next token).
-
- if ((openParenthesisCount > 1)
- && (openParenthesis[openParenthesisCount - 1] > 0)) {
- openParenthesis[openParenthesisCount - 1]--;
- if (openParenthesis[openParenthesisCount - 1] <= 0) {
- pendingNewlineAfterParen = true;
- inAssignment = false;
- openParenthesisCount--;
-
- }
- } else {
- openParenthesis[0]--;
- }
-
- pendingSpace = false;
- break;
- case TokenNameLBRACE :
- if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
+ }
+ } else {
+ // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment before the ';'
+ if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_JAVADOC) && token == TokenNameSEMICOLON)) {
+ newLine(pendingNewLines);
+ }
+ }
+ if (((previousCompilableToken == TokenNameSEMICOLON)
+ || (previousCompilableToken == TokenNameLBRACE)
+ || (previousCompilableToken == TokenNameRBRACE)
+ || (isComment(previousToken)))
+ && (token == TokenNameRBRACE)) {
+ indentationOffset = -1;
+ indentationLevel += popExclusiveUntilBlock();
+ }
+
+ if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
+ // PR 1FI5IPO
+ currentLineIndentationLevel++;
+ } else {
+ currentLineIndentationLevel = indentationLevel + indentationOffset;
+ }
+
+ pendingSpace = false;
+ indentationOffset = 0;
+ }
+ pendingNewLines = 0;
+ newLinesInWhitespace = 0;
+ specialElse = false;
+
+ if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
+ nlicsToken = 0;
+ }
+ }
+
+ switch (token) {
+ case TokenNameelse :
+ case TokenNamefinally :
+ expectingOpenBrace = true;
+ pendingNewlineAfterParen = true;
+ indentationLevel += pushControlStatement(token);
+ break;
+ case TokenNamecase :
+ case TokenNamedefault :
+ if (tokenBeforeColonCount == tokenBeforeColon.length) {
+ System.arraycopy(
+ tokenBeforeColon,
+ 0,
+ (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
+ 0,
+ tokenBeforeColonCount);
+ }
+ tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
+ indentationLevel += pushControlStatement(TokenNamecase);
+ break;
+ case TokenNameQUESTION :
+ if (tokenBeforeColonCount == tokenBeforeColon.length) {
+ System.arraycopy(
+ tokenBeforeColon,
+ 0,
+ (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
+ 0,
+ tokenBeforeColonCount);
+ }
+ tokenBeforeColon[tokenBeforeColonCount++] = token;
+ break;
+ case TokenNameswitch :
+ case TokenNamefor :
+ case TokenNameif :
+ case TokenNamewhile :
+ if (openParenthesisCount == openParenthesis.length) {
+ System.arraycopy(
+ openParenthesis,
+ 0,
+ (openParenthesis = new int[openParenthesisCount * 2]),
+ 0,
+ openParenthesisCount);
+ }
+ openParenthesis[openParenthesisCount++] = 0;
+ expectingOpenBrace = true;
+
+ indentationLevel += pushControlStatement(token);
+ break;
+ case TokenNametry :
+ pendingNewlineAfterParen = true;
+ case TokenNamecatch :
+ // several CATCH statements can be contiguous.
+ // a CATCH is encountered pop until first CATCH (if a CATCH follows a TRY it works the same way,
+ // as CATCH and TRY are the same token in the stack).
+ expectingOpenBrace = true;
+ indentationLevel += pushControlStatement(TokenNamecatch);
+ break;
+
+ case TokenNamedo :
+ expectingOpenBrace = true;
+ indentationLevel += pushControlStatement(token);
+ nlicsToken = token;
+ break;
+ case TokenNamenew :
+ break;
+ case TokenNameLPAREN :
+
+ // Put a space between the previous and current token if the
+ // previous token was not a keyword, open paren, logical
+ // compliment (eg: !), semi-colon, open brace, close brace,
+ // super, or this.
+
+ if (previousCompilableToken != TokenNameLBRACKET
+ && previousToken != TokenNameIdentifier
+ && previousToken != 0
+ && previousToken != TokenNameNOT
+ && previousToken != TokenNameLPAREN
+ && previousToken != TokenNameTWIDDLE
+ && previousToken != TokenNameSEMICOLON
+ && previousToken != TokenNameLBRACE
+ && previousToken != TokenNameRBRACE
+ && previousToken != TokenNamesuper
+ && previousToken != TokenNamethis) {
+ space();
+ }
+
+ // If in a for/if/while statement, increase the parenthesis count
+ // for the current openParenthesisCount
+ // else increase the count for stand alone parenthesis.
+ if (openParenthesisCount > 0)
+ openParenthesis[openParenthesisCount - 1]++;
+ else
+ openParenthesis[0]++;
+
+ pendingSpace = false;
+ break;
+ case TokenNameRPAREN :
+
+ // Decrease the parenthesis count
+ // if there is no more unclosed parenthesis,
+ // a new line and indent may be append (depending on the next token).
+
+ if ((openParenthesisCount > 1)
+ && (openParenthesis[openParenthesisCount - 1] > 0)) {
+ openParenthesis[openParenthesisCount - 1]--;
+ if (openParenthesis[openParenthesisCount - 1] <= 0) {
+ pendingNewlineAfterParen = true;
+ inAssignment = false;
+ openParenthesisCount--;
+
+ }
+ } else {
+ openParenthesis[0]--;
+ }
+
+ pendingSpace = false;
+ break;
+ case TokenNameLBRACE :
+ if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
// if (previousCompilableToken == TokenNameRBRACKET) {
- inArrayAssignment = true;
- inAssignment = false;
- }
- if (inArrayAssignment) {
- indentationLevel += pushBlock();
- } else {
- // Add new line and increase indentation level after open brace.
- pendingNewLines = 1;
- indentationLevel += pushBlock();
- }
- break;
- case TokenNameRBRACE :
- if (previousCompilableToken == TokenNameRPAREN) {
- pendingSpace = false;
- }
- if (inArrayAssignment) {
- inArrayAssignment = false;
- pendingNewLines = 1;
- indentationLevel += popInclusiveUntilBlock();
- } else {
- pendingNewLines = 1;
- indentationLevel += popInclusiveUntilBlock();
-
- if (previousCompilableToken == TokenNameRPAREN){
- // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
- currentLineBuffer.append(options.lineSeparatorSequence);
- increaseLineDelta(options.lineSeparatorSequence.length);
- }
-
- if (constructionsCount > 0) {
- switch (constructions[constructionsCount - 1]) {
- case TokenNamefor :
- //indentationLevel += popExclusiveUntilBlock();
- //break;
- case TokenNameswitch :
- case TokenNameif :
- case TokenNameelse :
- case TokenNametry :
- case TokenNamecatch :
- case TokenNamefinally :
- case TokenNamewhile :
- case TokenNamedo :
- clearNonBlockIndents = true;
- default :
- break;
- }
- }
-
- }
- break;
- case TokenNameLBRACKET :
- openBracketCount++;
- pendingSpace = false;
- break;
- case TokenNameRBRACKET :
- openBracketCount-=(openBracketCount>0)?1:0;
- // if there is no left bracket to close, the right bracket is ignored.
- pendingSpace = false;
- break;
- case TokenNamenew:
- unarySignModifier = 0;
- break;
- case TokenNameCOMMA :
- case TokenNameDOT :
- pendingSpace = false;
- break;
- case TokenNameSEMICOLON :
-
- // Do not generate line terminators in the definition of
- // the for statement.
- // if not in this case, jump a line and reduce indentation after the brace
- // if the block it closes belongs to a conditional statement (if, while, do...).
-
- if (openParenthesisCount <= 1) {
- pendingNewLines = 1;
- if (expectingOpenBrace) {
- clearNonBlockIndents = true;
- expectingOpenBrace = false;
- }
- }
- inAssignment = false;
- pendingSpace = false;
- break;
- case TokenNamePLUS_PLUS :
- case TokenNameMINUS_MINUS :
-
- // Do not put a space between a post-increment/decrement
- // and the identifier being modified.
-
- if (previousToken == TokenNameIdentifier
- || previousToken == TokenNameRBRACKET) {
- pendingSpace = false;
- }
- break;
- case TokenNamePLUS : // previously ADDITION
- case TokenNameMINUS :
-
- // Handle the unary operators plus and minus via a 3-state flag.
-
- if (!isLiteralToken(previousToken)
- && previousToken != TokenNameIdentifier
- && previousToken != TokenNameRPAREN
- && previousToken != TokenNameRBRACKET) {
- unarySignModifier = 2;
- }
- break;
- case TokenNameCOLON :
- // In a switch/case statement, add a newline & indent
- // when a colon is encountered.
- if (tokenBeforeColonCount > 0) {
- if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
- pendingNewLines = 1;
- }
- tokenBeforeColonCount--;
- }
- break;
- case TokenNameEQUAL :
- inAssignment = true;
- break;
- case Scanner.TokenNameCOMMENT_LINE :
- pendingNewLines = 1;
- if (inAssignment) {
- currentLineIndentationLevel++;
- }
- break; // a line is always inserted after a one-line comment
- case Scanner.TokenNameCOMMENT_JAVADOC :
- case Scanner.TokenNameCOMMENT_BLOCK :
- currentCommentOffset = getCurrentCommentOffset();
- if (openParenthesis[0]==0 && openBracketCount < 1){
- pendingNewLines = 1;
- // a new line is inserted only if the comment is not between parenthesis.
- }
- break;
- case Scanner.TokenNameWHITESPACE :
-
- // Count the number of line terminators in the whitespace so
- // line spacing can be preserved near comments.
-
- char[] source = scanner.source;
- newLinesInWhitespace = 0;
- for (
- int i = scanner.startPosition, max = scanner.currentPosition;
- i < max;
- i++) {
- if (source[i] == '\n') {
- newLinesInWhitespace++;
- }
- }
- increaseLineDelta(scanner.startPosition - scanner.currentPosition);
- break;
- default :
- if ((token == TokenNameIdentifier)
- || isLiteralToken(token)
- || token == TokenNamesuper
- || token == TokenNamethis) {
-
- // Do not put a space between a unary operator
- // (eg: ++, --, +, -) and the identifier being modified.
-
- unarySignModifier -= (unarySignModifier > 0) ? 1 : 0;
- if (previousToken == TokenNamePLUS_PLUS
- || previousToken == TokenNameMINUS_MINUS
- || (unarySignModifier > 0)) {
- pendingSpace = false;
- }
- }
- break;
- }
-
- // Do not output whitespace tokens.
-
- if (token != Scanner.TokenNameWHITESPACE) {
-
- /* Add pending space to the formatted source string.
- Do not output a space under the following circumstances:
- 1) this is the first pass
- 2) previous token is an open paren
- 3) previous token is a period
- 4) previous token is the logical compliment (eg: !)
- 5) previous token is the bitwise compliment (eg: ~)
- 6) previous token is the open bracket (eg: [)
- 7) in an assignment statement, if the previous token is an
- open brace or the current token is a close brace
- 8) previous token is a single line comment
- */
-
- boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
-
- // to be replaced by a nicer condition.
-
- if (pendingSpace
- && insertSpaceAfter(previousToken)
- && ! (inAssignment
- && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
- && previousToken != Scanner.TokenNameCOMMENT_LINE) {
- if ((! (options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace)
- space();
- }
-
- // Add the next token to the formatted source string.
-
- outputCurrentToken(token);
- if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1){
- pendingNewLines = 0;
- currentLineBuffer.append(options.lineSeparatorSequence);
- increaseLineDelta(options.lineSeparatorSequence.length);
- }
- pendingSpace = true;
- }
-
- // Whitespace tokens do not need to be remembered.
-
- if (token != Scanner.TokenNameWHITESPACE) {
- previousToken = token;
- if (token != Scanner.TokenNameCOMMENT_BLOCK
- && token != Scanner.TokenNameCOMMENT_LINE
- && token != Scanner.TokenNameCOMMENT_JAVADOC) {
- previousCompilableToken = token;
- }
- }
-
- }
- output(copyRemainingSource());
- flushBuffer(); // dump the last token of the source in the formatted output.
- } catch (InvalidInputException e) {
- output(copyRemainingSource());
- flushBuffer(); // dump the last token of the source in the formatted output.
- }
+ inArrayAssignment = true;
+ inAssignment = false;
+ }
+ if (inArrayAssignment) {
+ indentationLevel += pushBlock();
+ } else {
+ // Add new line and increase indentation level after open brace.
+ pendingNewLines = 1;
+ indentationLevel += pushBlock();
+ }
+ break;
+ case TokenNameRBRACE :
+ if (previousCompilableToken == TokenNameRPAREN) {
+ pendingSpace = false;
+ }
+ if (inArrayAssignment) {
+ inArrayAssignment = false;
+ pendingNewLines = 1;
+ indentationLevel += popInclusiveUntilBlock();
+ } else {
+ pendingNewLines = 1;
+ indentationLevel += popInclusiveUntilBlock();
+
+ if (previousCompilableToken == TokenNameRPAREN){
+ // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
+ currentLineBuffer.append(options.lineSeparatorSequence);
+ increaseLineDelta(options.lineSeparatorSequence.length);
+ }
+
+ if (constructionsCount > 0) {
+ switch (constructions[constructionsCount - 1]) {
+ case TokenNamefor :
+ //indentationLevel += popExclusiveUntilBlock();
+ //break;
+ case TokenNameswitch :
+ case TokenNameif :
+ case TokenNameelse :
+ case TokenNametry :
+ case TokenNamecatch :
+ case TokenNamefinally :
+ case TokenNamewhile :
+ case TokenNamedo :
+ clearNonBlockIndents = true;
+ default :
+ break;
+ }
+ }
+
+ }
+ break;
+ case TokenNameLBRACKET :
+ openBracketCount++;
+ pendingSpace = false;
+ break;
+ case TokenNameRBRACKET :
+ openBracketCount-=(openBracketCount>0)?1:0;
+ // if there is no left bracket to close, the right bracket is ignored.
+ pendingSpace = false;
+ break;
+ case TokenNameCOMMA :
+ case TokenNameDOT :
+ pendingSpace = false;
+ break;
+ case TokenNameSEMICOLON :
+
+ // Do not generate line terminators in the definition of
+ // the for statement.
+ // if not in this case, jump a line and reduce indentation after the brace
+ // if the block it closes belongs to a conditional statement (if, while, do...).
+
+ if (openParenthesisCount <= 1) {
+ pendingNewLines = 1;
+ if (expectingOpenBrace) {
+ clearNonBlockIndents = true;
+ expectingOpenBrace = false;
+ }
+ }
+ inAssignment = false;
+ pendingSpace = false;
+ break;
+ case TokenNamePLUS_PLUS :
+ case TokenNameMINUS_MINUS :
+
+ // Do not put a space between a post-increment/decrement
+ // and the identifier being modified.
+
+ if (previousToken == TokenNameIdentifier
+ || previousToken == TokenNameRBRACKET) {
+ pendingSpace = false;
+ }
+ break;
+ case TokenNamePLUS : // previously ADDITION
+ case TokenNameMINUS :
+
+ // Handle the unary operators plus and minus via a flag
+
+ if (!isLiteralToken(previousToken)
+ && previousToken != TokenNameIdentifier
+ && previousToken != TokenNameRPAREN
+ && previousToken != TokenNameRBRACKET) {
+ unarySignModifier = 1;
+ }
+ break;
+ case TokenNameCOLON :
+ // In a switch/case statement, add a newline & indent
+ // when a colon is encountered.
+ if (tokenBeforeColonCount > 0) {
+ if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
+ pendingNewLines = 1;
+ }
+ tokenBeforeColonCount--;
+ }
+ break;
+ case TokenNameEQUAL :
+ inAssignment = true;
+ break;
+ case Scanner.TokenNameCOMMENT_LINE :
+ pendingNewLines = 1;
+ if (inAssignment) {
+ currentLineIndentationLevel++;
+ }
+ break; // a line is always inserted after a one-line comment
+ case Scanner.TokenNameCOMMENT_JAVADOC :
+ case Scanner.TokenNameCOMMENT_BLOCK :
+ currentCommentOffset = getCurrentCommentOffset();
+ if (openParenthesis[0]==0 && openBracketCount < 1){
+ pendingNewLines = 1;
+ // a new line is inserted only if the comment is not between parenthesis.
+ }
+ break;
+ case Scanner.TokenNameWHITESPACE :
+
+ // Count the number of line terminators in the whitespace so
+ // line spacing can be preserved near comments.
+
+ char[] source = scanner.source;
+ newLinesInWhitespace = 0;
+ for (
+ int i = scanner.startPosition, max = scanner.currentPosition;
+ i < max;
+ i++) {
+ if (source[i] == '\n') {
+ newLinesInWhitespace++;
+ }
+ }
+ increaseLineDelta(scanner.startPosition - scanner.currentPosition);
+ break;
+ default :
+ if ((token == TokenNameIdentifier)
+ || isLiteralToken(token)
+ || token == TokenNamesuper
+ || token == TokenNamethis) {
+
+ // Do not put a space between a unary operator
+ // (eg: ++, --, +, -) and the identifier being modified.
+ if (previousToken == TokenNamePLUS_PLUS
+ || previousToken == TokenNameMINUS_MINUS
+ || (previousToken == TokenNamePLUS && unarySignModifier > 0)
+ || (previousToken == TokenNameMINUS && unarySignModifier > 0)) {
+ pendingSpace = false;
+ }
+ unarySignModifier = 0;
+ }
+ break;
+ }
+
+ // Do not output whitespace tokens.
+
+ if (token != Scanner.TokenNameWHITESPACE) {
+
+ /* Add pending space to the formatted source string.
+ Do not output a space under the following circumstances:
+ 1) this is the first pass
+ 2) previous token is an open paren
+ 3) previous token is a period
+ 4) previous token is the logical compliment (eg: !)
+ 5) previous token is the bitwise compliment (eg: ~)
+ 6) previous token is the open bracket (eg: [)
+ 7) in an assignment statement, if the previous token is an
+ open brace or the current token is a close brace
+ 8) previous token is a single line comment
+ */
+
+ boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
+
+ // to be replaced by a nicer condition.
+
+ if (pendingSpace
+ && insertSpaceAfter(previousToken)
+ && ! (inAssignment
+ && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
+ && previousToken != Scanner.TokenNameCOMMENT_LINE) {
+ if ((! (options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace)
+ space();
+ }
+
+ // Add the next token to the formatted source string.
+
+ outputCurrentToken(token);
+ if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1){
+ pendingNewLines = 0;
+ currentLineBuffer.append(options.lineSeparatorSequence);
+ increaseLineDelta(options.lineSeparatorSequence.length);
+ }
+ pendingSpace = true;
+ }
+
+ // Whitespace tokens do not need to be remembered.
+
+ if (token != Scanner.TokenNameWHITESPACE) {
+ previousToken = token;
+ if (token != Scanner.TokenNameCOMMENT_BLOCK
+ && token != Scanner.TokenNameCOMMENT_LINE
+ && token != Scanner.TokenNameCOMMENT_JAVADOC) {
+ previousCompilableToken = token;
+ }
+ }
+
+ }
+ output(copyRemainingSource());
+ flushBuffer(); // dump the last token of the source in the formatted output.
+ } catch (InvalidInputException e) {
+ output(copyRemainingSource());
+ flushBuffer(); // dump the last token of the source in the formatted output.
+ }
}
/**
* Formats a given source string, starting indenting it at depth 0
* using default options.
*/
public static String format(String sourceString) {
- return format(sourceString, 0, null);
+ return format(sourceString, 0, null);
}
/**
* Formats a given source string, starting indenting it at a particular
* depth and using the given options
*/
public static String format(String sourceString, int initialIndentationLevel, ConfigurableOption[] options) {
- CodeFormatter formatter = new CodeFormatter(options);
- formatter.setInitialIndentationLevel(initialIndentationLevel);
- return formatter.formatSourceString(sourceString);
+ CodeFormatter formatter = new CodeFormatter(options);
+ formatter.setInitialIndentationLevel(initialIndentationLevel);
+ return formatter.formatSourceString(sourceString);
}
/**
* Formats the char array <code>sourceString</code>,
@@ -902,58 +902,66 @@ public static String format(String sourceString, int initialIndentationLevel, Co
* @return the formatted ouput.
*/
public String formatSourceString(String sourceString) {
- char[] sourceChars = sourceString.toCharArray();
- formattedSource = new StringBuffer(sourceChars.length);
- scanner.setSourceBuffer(sourceChars);
- format();
- return formattedSource.toString();
+ char[] sourceChars = sourceString.toCharArray();
+ formattedSource = new StringBuffer(sourceChars.length);
+ scanner.setSourceBuffer(sourceChars);
+ format();
+ return formattedSource.toString();
}
/**
* Returns the number of characters and tab char between the beginning of the line
* and the beginning of the comment.
*/
private int getCurrentCommentOffset() {
- int linePtr = scanner.linePtr;
- // if there is no beginning of line, return 0.
- if (linePtr < 0)
- return 0;
- int offset = 0;
- int beginningOfLine = scanner.lineEnds[linePtr];
- int currentStartPosition = scanner.startPosition;
- char[] source = scanner.source;
-
- // find the position of the beginning of the line containing the comment
- while (beginningOfLine > currentStartPosition) {
- if (linePtr > 0) {
- beginningOfLine = scanner.lineEnds[--linePtr];
- } else {
- beginningOfLine = 0;
- break;
- }
- }
-
- for (int i = beginningOfLine ; i < currentStartPosition ; i++){
- char currentCharacter = source[i];
- switch(currentCharacter){
- case '\t':
- offset += options.tabSize;
- case '\n':
- case '\r':
- break;
- default:
- offset++;
- }
- }
-
- return offset;
+ int linePtr = scanner.linePtr;
+ // if there is no beginning of line, return 0.
+ if (linePtr < 0)
+ return 0;
+ int offset = 0;
+ int beginningOfLine = scanner.lineEnds[linePtr];
+ int currentStartPosition = scanner.startPosition;
+ char[] source = scanner.source;
+
+ // find the position of the beginning of the line containing the comment
+ while (beginningOfLine > currentStartPosition) {
+ if (linePtr > 0) {
+ beginningOfLine = scanner.lineEnds[--linePtr];
+ } else {
+ beginningOfLine = 0;
+ break;
+ }
+ }
+
+ for (int i = beginningOfLine ; i < currentStartPosition ; i++){
+ char currentCharacter = source[i];
+ switch(currentCharacter){
+ case '\t':
+ offset += options.tabSize;
+ case '\n':
+ case '\r':
+ break;
+ default:
+ offset++;
+ }
+ }
+
+ return offset;
}
/**
- * Returns an array of descriptions for the configurable options.
- * The descriptions may be changed and passed back to a different
- * compiler.
+ * Returns all the options of the Code Formatter to be shown by the UI
+ *
+ * @param locale java.util.Locale
+ * @return org.eclipse.jdt.internal.compiler.java.ConfigurableOption[]
*/
public static ConfigurableOption[] getDefaultOptions(Locale locale) {
- return new FormatterOptions().getConfigurableOptions(locale);
+ String[] ids = ConfigurableOption.getIDs(CodeFormatter.class.getName(),locale);
+
+ ConfigurableOption[] result = new ConfigurableOption[ids.length];
+ for(int i = 0 ; i < ids.length ; i++){
+ result[i] = new ConfigurableOption(ids[i],locale);
+ }
+
+ return result;
}
/**
* Returns the array of mapped positions.
@@ -961,7 +969,7 @@ public static ConfigurableOption[] getDefaultOptions(Locale locale) {
* @return int[]
*/
public int[] getMappedPositions() {
- return mappedPositions;
+ return mappedPositions;
}
/**
* Returns the priority of the token given as argument<br>
@@ -970,104 +978,104 @@ public int[] getMappedPositions() {
* @param token the token of which the priority is requested
*/
private static int getTokenPriority(int token) {
- switch (token) {
- case TokenNameextends:
- case TokenNameimplements:
- case TokenNamethrows:
- return 10;
- case TokenNameSEMICOLON : // ;
- return 20;
- case TokenNameCOMMA : // ,
- return 25;
- case TokenNameEQUAL : // =
- return 30;
- case TokenNameAND_AND : // &&
- case TokenNameOR_OR : // ||
- return 40;
- case TokenNameQUESTION : // ?
- case TokenNameCOLON : // :
- return 50; // it's better cutting on ?: than on ;
- case TokenNameEQUAL_EQUAL : // ==
- case TokenNameNOT_EQUAL : // !=
- return 60;
- case TokenNameLESS : // <
- case TokenNameLESS_EQUAL : // <=
- case TokenNameGREATER : // >
- case TokenNameGREATER_EQUAL : // >=
- case TokenNameinstanceof : // instanceof
- return 70;
- case TokenNamePLUS : // +
- case TokenNameMINUS : // -
- return 80;
- case TokenNameMULTIPLY : // *
- case TokenNameDIVIDE : // /
- case TokenNameREMAINDER : // %
- return 90;
- case TokenNameLEFT_SHIFT : // <<
- case TokenNameRIGHT_SHIFT : // >>
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
- return 100;
- case TokenNameAND : // &
- case TokenNameOR : // |
- case TokenNameXOR : // ^
- return 110;
- case TokenNameMULTIPLY_EQUAL : // *=
- case TokenNameDIVIDE_EQUAL : // /=
- case TokenNameREMAINDER_EQUAL : // %=
- case TokenNamePLUS_EQUAL : // +=
- case TokenNameMINUS_EQUAL : // -=
- case TokenNameLEFT_SHIFT_EQUAL : // <<=
- case TokenNameRIGHT_SHIFT_EQUAL : // >>=
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
- case TokenNameAND_EQUAL : // &=
- case TokenNameXOR_EQUAL : // ^=
- case TokenNameOR_EQUAL : // |=
- return 120;
- case TokenNameDOT : // .
- return 130;
- default :
- return Integer.MAX_VALUE;
- }
+ switch (token) {
+ case TokenNameextends:
+ case TokenNameimplements:
+ case TokenNamethrows:
+ return 10;
+ case TokenNameSEMICOLON : // ;
+ return 20;
+ case TokenNameCOMMA : // ,
+ return 25;
+ case TokenNameEQUAL : // =
+ return 30;
+ case TokenNameAND_AND : // &&
+ case TokenNameOR_OR : // ||
+ return 40;
+ case TokenNameQUESTION : // ?
+ case TokenNameCOLON : // :
+ return 50; // it's better cutting on ?: than on ;
+ case TokenNameEQUAL_EQUAL : // ==
+ case TokenNameNOT_EQUAL : // !=
+ return 60;
+ case TokenNameLESS : // <
+ case TokenNameLESS_EQUAL : // <=
+ case TokenNameGREATER : // >
+ case TokenNameGREATER_EQUAL : // >=
+ case TokenNameinstanceof : // instanceof
+ return 70;
+ case TokenNamePLUS : // +
+ case TokenNameMINUS : // -
+ return 80;
+ case TokenNameMULTIPLY : // *
+ case TokenNameDIVIDE : // /
+ case TokenNameREMAINDER : // %
+ return 90;
+ case TokenNameLEFT_SHIFT : // <<
+ case TokenNameRIGHT_SHIFT : // >>
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
+ return 100;
+ case TokenNameAND : // &
+ case TokenNameOR : // |
+ case TokenNameXOR : // ^
+ return 110;
+ case TokenNameMULTIPLY_EQUAL : // *=
+ case TokenNameDIVIDE_EQUAL : // /=
+ case TokenNameREMAINDER_EQUAL : // %=
+ case TokenNamePLUS_EQUAL : // +=
+ case TokenNameMINUS_EQUAL : // -=
+ case TokenNameLEFT_SHIFT_EQUAL : // <<=
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>=
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
+ case TokenNameAND_EQUAL : // &=
+ case TokenNameXOR_EQUAL : // ^=
+ case TokenNameOR_EQUAL : // |=
+ return 120;
+ case TokenNameDOT : // .
+ return 130;
+ default :
+ return Integer.MAX_VALUE;
+ }
}
/**
* Handles the exception raised when an invalid token is encountered.
* Returns true if the exception has been handled, false otherwise.
*/
private boolean handleInvalidToken(Exception e) {
- if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT)
- || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
- || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
- return true;
- }
- return false;
+ if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT)
+ || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
+ || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
+ return true;
+ }
+ return false;
}
private final void increaseGlobalDelta(int offset) {
- globalDelta += offset;
+ globalDelta += offset;
}
private final void increaseLineDelta(int offset) {
- lineDelta += offset;
+ lineDelta += offset;
}
private final void increaseSplitDelta(int offset) {
- splitDelta += offset;
+ splitDelta += offset;
}
/**
* Returns true if a space has to be inserted after <code>operator</code>
* false otherwise.
*/
private boolean insertSpaceAfter(int token) {
- switch (token){
- case TokenNameLPAREN:
- case TokenNameNOT:
- case TokenNameTWIDDLE:
- case TokenNameDOT :
- case 0: // no token
- case TokenNameLBRACKET:
- case Scanner.TokenNameCOMMENT_LINE:
- return false;
- default:
- return true;
- }
-
+ switch (token){
+ case TokenNameLPAREN:
+ case TokenNameNOT:
+ case TokenNameTWIDDLE:
+ case TokenNameDOT :
+ case 0: // no token
+ case TokenNameLBRACKET:
+ case Scanner.TokenNameCOMMENT_LINE:
+ return false;
+ default:
+ return true;
+ }
+
}
/**
* Returns true if a space has to be inserted before <code>operator</code>
@@ -1076,29 +1084,29 @@ private boolean insertSpaceAfter(int token) {
* (to know if the compact assignment mode is on).
*/
private boolean insertSpaceBefore(int token) {
- switch (token) {
- case TokenNameEQUAL:
- return (!options.compactAssignmentMode);
- default :
- return false;
- }
+ switch (token) {
+ case TokenNameEQUAL:
+ return (!options.compactAssignmentMode);
+ default :
+ return false;
+ }
}
private static boolean isComment(int token) {
- boolean result =
- token == Scanner.TokenNameCOMMENT_BLOCK ||
- token == Scanner.TokenNameCOMMENT_LINE ||
- token == Scanner.TokenNameCOMMENT_JAVADOC;
- return result;
+ boolean result =
+ token == Scanner.TokenNameCOMMENT_BLOCK ||
+ token == Scanner.TokenNameCOMMENT_LINE ||
+ token == Scanner.TokenNameCOMMENT_JAVADOC;
+ return result;
}
private static boolean isLiteralToken(int token) {
- boolean result =
- token == TokenNameIntegerLiteral ||
- token == TokenNameLongLiteral ||
- token == TokenNameFloatingPointLiteral ||
- token == TokenNameDoubleLiteral ||
- token == TokenNameCharacterLiteral ||
- token == TokenNameStringLiteral;
- return result;
+ boolean result =
+ token == TokenNameIntegerLiteral ||
+ token == TokenNameLongLiteral ||
+ token == TokenNameFloatingPointLiteral ||
+ token == TokenNameDoubleLiteral ||
+ token == TokenNameCharacterLiteral ||
+ token == TokenNameStringLiteral;
+ return result;
}
/**
* If the length of <code>oneLineBuffer</code> exceeds <code>maxLineLength</code>,
@@ -1107,241 +1115,241 @@ private static boolean isLiteralToken(int token) {
*/
private void newLine(int newLineCount) {
- // format current line
- splitDelta = 0;
- beginningOfLineIndex = formattedSource.length();
- String currentLine = currentLineBuffer.toString();
- if (containsOpenCloseBraces) {
- containsOpenCloseBraces = false;
- outputLine(currentLine,
- false,
- indentationLevelForOpenCloseBraces,
- 0,
- -1,
- null,
- 0);
- indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
- } else {
- outputLine(currentLine,
- false,
- currentLineIndentationLevel,
- 0,
- -1,
- null,
- 0);
- }
- // dump line break(s)
- for (int i = 0; i < newLineCount; i++) {
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
- }
- // reset formatter for next line
- int currentLength = currentLine.length();
- currentLineBuffer = new StringBuffer(
- currentLength > maxLineSize
- ? maxLineSize = currentLength
- : maxLineSize);
-
- increaseGlobalDelta(splitDelta);
- increaseGlobalDelta(lineDelta);
- lineDelta = 0;
- currentLineIndentationLevel = initialIndentationLevel;
+ // format current line
+ splitDelta = 0;
+ beginningOfLineIndex = formattedSource.length();
+ String currentLine = currentLineBuffer.toString();
+ if (containsOpenCloseBraces) {
+ containsOpenCloseBraces = false;
+ outputLine(currentLine,
+ false,
+ indentationLevelForOpenCloseBraces,
+ 0,
+ -1,
+ null,
+ 0);
+ indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
+ } else {
+ outputLine(currentLine,
+ false,
+ currentLineIndentationLevel,
+ 0,
+ -1,
+ null,
+ 0);
+ }
+ // dump line break(s)
+ for (int i = 0; i < newLineCount; i++) {
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+ }
+ // reset formatter for next line
+ int currentLength = currentLine.length();
+ currentLineBuffer = new StringBuffer(
+ currentLength > maxLineSize
+ ? maxLineSize = currentLength
+ : maxLineSize);
+
+ increaseGlobalDelta(splitDelta);
+ increaseGlobalDelta(lineDelta);
+ lineDelta = 0;
+ currentLineIndentationLevel = initialIndentationLevel;
}
private String operatorString(int operator) {
- switch (operator) {
- case TokenNameextends :
- return "extends"/*nonNLS*/;
+ switch (operator) {
+ case TokenNameextends :
+ return "extends"/*nonNLS*/;
- case TokenNameimplements :
- return "implements"/*nonNLS*/;
+ case TokenNameimplements :
+ return "implements"/*nonNLS*/;
- case TokenNamethrows :
- return "throws"/*nonNLS*/;
+ case TokenNamethrows :
+ return "throws"/*nonNLS*/;
- case TokenNameSEMICOLON : // ;
- return ";"/*nonNLS*/;
+ case TokenNameSEMICOLON : // ;
+ return ";"/*nonNLS*/;
- case TokenNameCOMMA : // ,
- return ","/*nonNLS*/;
+ case TokenNameCOMMA : // ,
+ return ","/*nonNLS*/;
- case TokenNameEQUAL : // =
- return "="/*nonNLS*/;
+ case TokenNameEQUAL : // =
+ return "="/*nonNLS*/;
- case TokenNameAND_AND : // && (15.22)
- return "&&"/*nonNLS*/;
+ case TokenNameAND_AND : // && (15.22)
+ return "&&"/*nonNLS*/;
- case TokenNameOR_OR : // || (15.23)
- return "||"/*nonNLS*/;
+ case TokenNameOR_OR : // || (15.23)
+ return "||"/*nonNLS*/;
- case TokenNameQUESTION : // ? (15.24)
- return "?"/*nonNLS*/;
+ case TokenNameQUESTION : // ? (15.24)
+ return "?"/*nonNLS*/;
- case TokenNameCOLON : // : (15.24)
- return ":"/*nonNLS*/;
+ case TokenNameCOLON : // : (15.24)
+ return ":"/*nonNLS*/;
- case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
- return "=="/*nonNLS*/;
+ case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
+ return "=="/*nonNLS*/;
- case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
- return "!="/*nonNLS*/;
+ case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
+ return "!="/*nonNLS*/;
- case TokenNameLESS : // < (15.19.1)
- return "<"/*nonNLS*/;
+ case TokenNameLESS : // < (15.19.1)
+ return "<"/*nonNLS*/;
- case TokenNameLESS_EQUAL : // <= (15.19.1)
- return "<="/*nonNLS*/;
+ case TokenNameLESS_EQUAL : // <= (15.19.1)
+ return "<="/*nonNLS*/;
- case TokenNameGREATER : // > (15.19.1)
- return ">"/*nonNLS*/;
+ case TokenNameGREATER : // > (15.19.1)
+ return ">"/*nonNLS*/;
- case TokenNameGREATER_EQUAL : // >= (15.19.1)
- return ">="/*nonNLS*/;
+ case TokenNameGREATER_EQUAL : // >= (15.19.1)
+ return ">="/*nonNLS*/;
- case TokenNameinstanceof : // instanceof
- return "instanceof"/*nonNLS*/;
+ case TokenNameinstanceof : // instanceof
+ return "instanceof"/*nonNLS*/;
- case TokenNamePLUS : // + (15.17, 15.17.2)
- return "+"/*nonNLS*/;
+ case TokenNamePLUS : // + (15.17, 15.17.2)
+ return "+"/*nonNLS*/;
- case TokenNameMINUS : // - (15.17.2)
- return "-"/*nonNLS*/;
+ case TokenNameMINUS : // - (15.17.2)
+ return "-"/*nonNLS*/;
- case TokenNameMULTIPLY : // * (15.16.1)
- return "*"/*nonNLS*/;
+ case TokenNameMULTIPLY : // * (15.16.1)
+ return "*"/*nonNLS*/;
- case TokenNameDIVIDE : // / (15.16.2)
- return "/"/*nonNLS*/;
+ case TokenNameDIVIDE : // / (15.16.2)
+ return "/"/*nonNLS*/;
- case TokenNameREMAINDER : // % (15.16.3)
- return "%"/*nonNLS*/;
+ case TokenNameREMAINDER : // % (15.16.3)
+ return "%"/*nonNLS*/;
- case TokenNameLEFT_SHIFT : // << (15.18)
- return "<<"/*nonNLS*/;
+ case TokenNameLEFT_SHIFT : // << (15.18)
+ return "<<"/*nonNLS*/;
- case TokenNameRIGHT_SHIFT : // >> (15.18)
- return ">>"/*nonNLS*/;
+ case TokenNameRIGHT_SHIFT : // >> (15.18)
+ return ">>"/*nonNLS*/;
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
- return ">>>"/*nonNLS*/;
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
+ return ">>>"/*nonNLS*/;
- case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
- return "&"/*nonNLS*/;
+ case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
+ return "&"/*nonNLS*/;
- case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
- return "|"/*nonNLS*/;
+ case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
+ return "|"/*nonNLS*/;
- case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
- return "^"/*nonNLS*/;
+ case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
+ return "^"/*nonNLS*/;
- case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
- return "*="/*nonNLS*/;
+ case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
+ return "*="/*nonNLS*/;
- case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
- return "/="/*nonNLS*/;
+ case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
+ return "/="/*nonNLS*/;
- case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
- return "%="/*nonNLS*/;
+ case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
+ return "%="/*nonNLS*/;
- case TokenNamePLUS_EQUAL : // += (15.25.2)
- return "+="/*nonNLS*/;
+ case TokenNamePLUS_EQUAL : // += (15.25.2)
+ return "+="/*nonNLS*/;
- case TokenNameMINUS_EQUAL : // -= (15.25.2)
- return "-="/*nonNLS*/;
+ case TokenNameMINUS_EQUAL : // -= (15.25.2)
+ return "-="/*nonNLS*/;
- case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
- return "<<="/*nonNLS*/;
+ case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
+ return "<<="/*nonNLS*/;
- case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
- return ">>="/*nonNLS*/;
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
+ return ">>="/*nonNLS*/;
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
- return ">>>="/*nonNLS*/;
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
+ return ">>>="/*nonNLS*/;
- case TokenNameAND_EQUAL : // &= (15.25.2)
- return "&="/*nonNLS*/;
+ case TokenNameAND_EQUAL : // &= (15.25.2)
+ return "&="/*nonNLS*/;
- case TokenNameXOR_EQUAL : // ^= (15.25.2)
- return "^="/*nonNLS*/;
+ case TokenNameXOR_EQUAL : // ^= (15.25.2)
+ return "^="/*nonNLS*/;
- case TokenNameOR_EQUAL : // |= (15.25.2)
- return "|="/*nonNLS*/;
+ case TokenNameOR_EQUAL : // |= (15.25.2)
+ return "|="/*nonNLS*/;
- case TokenNameDOT : // .
- return "."/*nonNLS*/;
+ case TokenNameDOT : // .
+ return "."/*nonNLS*/;
- default :
- return ""/*nonNLS*/;
- }
+ default :
+ return ""/*nonNLS*/;
+ }
}
/**
* Appends <code>stringToOutput</code> to the formatted output.<br>
* If it contains \n, append a LINE_SEPARATOR and indent after it.
*/
private void output(String stringToOutput) {
- char currentCharacter;
- for (int i = 0, max = stringToOutput.length(); i < max; i++) {
- currentCharacter = stringToOutput.charAt(i);
- if (currentCharacter != '\t') {
- currentLineBuffer.append(currentCharacter);
- }
- }
- updateMappedPositions(scanner.startPosition);
+ char currentCharacter;
+ for (int i = 0, max = stringToOutput.length(); i < max; i++) {
+ currentCharacter = stringToOutput.charAt(i);
+ if (currentCharacter != '\t') {
+ currentLineBuffer.append(currentCharacter);
+ }
+ }
+ updateMappedPositions(scanner.startPosition);
}
/**
* Appends <code>token</code> to the formatted output.<br>
* If it contains <code>\n</code>, append a LINE_SEPARATOR and indent after it.
*/
private void outputCurrentToken(int token) {
- char[] source = scanner.source;
- int startPosition = scanner.startPosition;
-
- switch(token) {
- case Scanner.TokenNameCOMMENT_JAVADOC :
- case Scanner.TokenNameCOMMENT_BLOCK :
- case Scanner.TokenNameCOMMENT_LINE :
- boolean endOfLine = false;
- int currentCommentOffset = getCurrentCommentOffset();
- int beginningOfLineSpaces = 0;
- for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
- char currentCharacter = source[i];
- switch(currentCharacter) {
- case '\r' :
- case '\n' :
- endOfLine = true;
- currentLineBuffer.append(currentCharacter);
- beginningOfLineSpaces = 0;
- break;
- case '\t' :
- if (endOfLine) {
- // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
- beginningOfLineSpaces+=options.tabSize;
- if (beginningOfLineSpaces > currentCommentOffset)
- currentLineBuffer.append(currentCharacter);
- } else {
- currentLineBuffer.append(currentCharacter);
- }
- break;
- case ' ' :
- if (endOfLine) {
- // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
- beginningOfLineSpaces++;
- if (beginningOfLineSpaces > currentCommentOffset)
- currentLineBuffer.append(currentCharacter);
- } else {
- currentLineBuffer.append(currentCharacter);
- }
- break;
- default:
- beginningOfLineSpaces = 0;
- currentLineBuffer.append(currentCharacter);
- endOfLine = false;
- }
- }
- break;
- default:
- currentLineBuffer.append(source, startPosition, scanner.currentPosition - startPosition);
- }
- updateMappedPositions(startPosition);
+ char[] source = scanner.source;
+ int startPosition = scanner.startPosition;
+
+ switch(token) {
+ case Scanner.TokenNameCOMMENT_JAVADOC :
+ case Scanner.TokenNameCOMMENT_BLOCK :
+ case Scanner.TokenNameCOMMENT_LINE :
+ boolean endOfLine = false;
+ int currentCommentOffset = getCurrentCommentOffset();
+ int beginningOfLineSpaces = 0;
+ for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
+ char currentCharacter = source[i];
+ switch(currentCharacter) {
+ case '\r' :
+ case '\n' :
+ endOfLine = true;
+ currentLineBuffer.append(currentCharacter);
+ beginningOfLineSpaces = 0;
+ break;
+ case '\t' :
+ if (endOfLine) {
+ // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
+ beginningOfLineSpaces+=options.tabSize;
+ if (beginningOfLineSpaces > currentCommentOffset)
+ currentLineBuffer.append(currentCharacter);
+ } else {
+ currentLineBuffer.append(currentCharacter);
+ }
+ break;
+ case ' ' :
+ if (endOfLine) {
+ // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
+ beginningOfLineSpaces++;
+ if (beginningOfLineSpaces > currentCommentOffset)
+ currentLineBuffer.append(currentCharacter);
+ } else {
+ currentLineBuffer.append(currentCharacter);
+ }
+ break;
+ default:
+ beginningOfLineSpaces = 0;
+ currentLineBuffer.append(currentCharacter);
+ endOfLine = false;
+ }
+ }
+ break;
+ default:
+ currentLineBuffer.append(source, startPosition, scanner.currentPosition - startPosition);
+ }
+ updateMappedPositions(startPosition);
}
/**
* Outputs <code>currentString</code>:<br>
@@ -1353,244 +1361,244 @@ private void outputCurrentToken(int token) {
* @param operator value of the operator belonging to <code>currentString</code>.
*/
private void outputLine(
- String currentString,
- boolean preIndented,
- int depth,
- int operator,
- int substringIndex,
- int[] startSubstringIndexes,
- int offsetInGlobalLine) {
-
- boolean emptyFirstSubString = false;
- String operatorString = operatorString(operator);
- boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
- boolean placeOperatorAhead = !placeOperatorBehind;
-
- // dump prefix operator?
- if (placeOperatorAhead) {
- if (!preIndented) {
- dumpTab(depth);
- preIndented = true;
- }
- if (operator != 0) {
- if (insertSpaceBefore(operator)) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- formattedSource.append(operatorString);
- increaseSplitDelta(operatorString.length());
-
- if (insertSpaceAfter(operator)
- && operator != TokenNameimplements
- && operator != TokenNameextends
- && operator != TokenNamethrows) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- }
- }
- SplitLine splitLine = null;
- if (options.maxLineLength == 0
- || currentString.length() < options.maxLineLength
- || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
- // depending on the type of operator, outputs new line before of after dumping it
- // indent before postfix operator
- // indent also when the line cannot be split
-
- if (operator == TokenNameextends
- || operator == TokenNameimplements
- || operator == TokenNamethrows) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
-
- if (placeOperatorBehind) {
- if (!preIndented) {
- dumpTab(depth);
- }
- }
-
- boolean containsMultiLineComment = currentString.lastIndexOf("/*"/*nonNLS*/) != -1;
- int numberOfSpaces = 0;
- int max = currentString.length();
- updateMappedPositionsWhileSplitting(
- beginningOfLineIndex,
- beginningOfLineIndex + max);
- for (int i = 0; i < max; i++) {
- char currentChar = currentString.charAt(i);
- switch (currentChar) {
- case '\r' :
- break;
- case '\n' :
- if (i != max - 1) {
- // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when split with a comment inside a condition
- // a substring cannot end with a lineSeparatorSequence,
- // except if it has been added by format() after a one-line comment
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
-
- if (containsMultiLineComment) {
- // fix for 1FGGQCN: LFCOM:ALL - Space management in comments for the formatter
- dumpTab(currentLineIndentationLevel);
- } else {
- // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
- dumpTab(depth - 1);
- }
- }
- break;
- default :
- formattedSource.append(currentChar);
- }
- }
-
- // update positions inside the mappedPositions table
- if (substringIndex != -1) {
- int startPosition =
- beginningOfLineIndex + startSubstringIndexes[substringIndex];
- updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
-
- // compute the splitDelta resulting with the operator and blank removal
- if (substringIndex + 1 != startSubstringIndexes.length) {
- increaseSplitDelta(
- startSubstringIndexes[substringIndex]
- + max
- - startSubstringIndexes[substringIndex
- + 1]);
- }
- }
- // dump postfix operator?
- if (placeOperatorBehind) {
- if (insertSpaceBefore(operator)) {
- formattedSource.append(' ');
- if (operator != 0) {
- increaseSplitDelta(1);
- }
- }
- formattedSource.append(operatorString);
- if (operator != 0) {
- increaseSplitDelta(operatorString.length());
- }
- }
- return;
- }
-
- // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
- // extends has to stand alone on a line when currentString has been split.
- if (options.maxLineLength != 0
- && splitLine != null
- && (operator == TokenNameextends
- || operator == TokenNameimplements
- || operator == TokenNamethrows)) {
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
-
- dumpTab(depth + 1);
- } else {
- if (operator == TokenNameextends
- || operator == TokenNameimplements
- || operator == TokenNamethrows) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- }
-
- // perform actual splitting
- String result[] = splitLine.substrings;
- int[] splitOperators = splitLine.operators;
- int[] splitLineStartIndexes = splitLine.startSubstringsIndexes;
-
- if (result[0].length() == 0) {
- // when the substring 0 is null, the substring 1 is correctly indented.
- depth--;
- emptyFirstSubString = true;
- }
- // the operator going in front of the result[0] string is the operator parameter
-
- for (int i = 0, max = result.length; i < max; i++) {
- // the new depth is the current one if this is the first substring,
- // the current one + 1 otherwise.
-
- // if the substring is a comment, use the current indentation Level instead of the depth
- // (-1 because the ouputline increases depth).
- // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line comments)
- String currentResult = result[i];
-
- if (currentResult.length() != 0 || splitOperators[i] != 0) {
- int newDepth =
- (currentResult.startsWith("/*"/*nonNLS*/) || currentResult.startsWith("//"/*nonNLS*/))
- ? indentationLevel - 1
- : depth;
- outputLine(
- currentResult,
- i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
- i == 0 ? newDepth : newDepth + 1,
- splitOperators[i],
- i,
- splitLine.startSubstringsIndexes,
- currentString.indexOf(currentResult));
- if (i != max - 1) {
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
- }
- }
- }
- if (result.length == splitOperators.length - 1) {
- int lastOperator = splitOperators[result.length];
- String lastOperatorString = operatorString(lastOperator);
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
-
- if (breakLineBeforeOperator(lastOperator)) {
- dumpTab(depth + 1);
- if (lastOperator != 0) {
- if (insertSpaceBefore(lastOperator)) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- formattedSource.append(lastOperatorString);
- increaseSplitDelta(lastOperatorString.length());
-
- if (insertSpaceAfter(lastOperator)
- && lastOperator != TokenNameimplements
- && lastOperator != TokenNameextends
- && lastOperator != TokenNamethrows) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- }
- }
- }
- if (placeOperatorBehind) {
- if (insertSpaceBefore(operator)) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- formattedSource.append(operatorString);
- //increaseSplitDelta(operatorString.length());
- }
+ String currentString,
+ boolean preIndented,
+ int depth,
+ int operator,
+ int substringIndex,
+ int[] startSubstringIndexes,
+ int offsetInGlobalLine) {
+
+ boolean emptyFirstSubString = false;
+ String operatorString = operatorString(operator);
+ boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
+ boolean placeOperatorAhead = !placeOperatorBehind;
+
+ // dump prefix operator?
+ if (placeOperatorAhead) {
+ if (!preIndented) {
+ dumpTab(depth);
+ preIndented = true;
+ }
+ if (operator != 0) {
+ if (insertSpaceBefore(operator)) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ formattedSource.append(operatorString);
+ increaseSplitDelta(operatorString.length());
+
+ if (insertSpaceAfter(operator)
+ && operator != TokenNameimplements
+ && operator != TokenNameextends
+ && operator != TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ }
+ }
+ SplitLine splitLine = null;
+ if (options.maxLineLength == 0
+ || currentString.length() < options.maxLineLength
+ || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
+ // depending on the type of operator, outputs new line before of after dumping it
+ // indent before postfix operator
+ // indent also when the line cannot be split
+
+ if (operator == TokenNameextends
+ || operator == TokenNameimplements
+ || operator == TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+
+ if (placeOperatorBehind) {
+ if (!preIndented) {
+ dumpTab(depth);
+ }
+ }
+
+ boolean containsMultiLineComment = currentString.lastIndexOf("/*"/*nonNLS*/) != -1;
+ int numberOfSpaces = 0;
+ int max = currentString.length();
+ updateMappedPositionsWhileSplitting(
+ beginningOfLineIndex,
+ beginningOfLineIndex + max);
+ for (int i = 0; i < max; i++) {
+ char currentChar = currentString.charAt(i);
+ switch (currentChar) {
+ case '\r' :
+ break;
+ case '\n' :
+ if (i != max - 1) {
+ // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when split with a comment inside a condition
+ // a substring cannot end with a lineSeparatorSequence,
+ // except if it has been added by format() after a one-line comment
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+
+ if (containsMultiLineComment) {
+ // fix for 1FGGQCN: LFCOM:ALL - Space management in comments for the formatter
+ dumpTab(currentLineIndentationLevel);
+ } else {
+ // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
+ dumpTab(depth - 1);
+ }
+ }
+ break;
+ default :
+ formattedSource.append(currentChar);
+ }
+ }
+
+ // update positions inside the mappedPositions table
+ if (substringIndex != -1) {
+ int startPosition =
+ beginningOfLineIndex + startSubstringIndexes[substringIndex];
+ updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
+
+ // compute the splitDelta resulting with the operator and blank removal
+ if (substringIndex + 1 != startSubstringIndexes.length) {
+ increaseSplitDelta(
+ startSubstringIndexes[substringIndex]
+ + max
+ - startSubstringIndexes[substringIndex
+ + 1]);
+ }
+ }
+ // dump postfix operator?
+ if (placeOperatorBehind) {
+ if (insertSpaceBefore(operator)) {
+ formattedSource.append(' ');
+ if (operator != 0) {
+ increaseSplitDelta(1);
+ }
+ }
+ formattedSource.append(operatorString);
+ if (operator != 0) {
+ increaseSplitDelta(operatorString.length());
+ }
+ }
+ return;
+ }
+
+ // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
+ // extends has to stand alone on a line when currentString has been split.
+ if (options.maxLineLength != 0
+ && splitLine != null
+ && (operator == TokenNameextends
+ || operator == TokenNameimplements
+ || operator == TokenNamethrows)) {
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+
+ dumpTab(depth + 1);
+ } else {
+ if (operator == TokenNameextends
+ || operator == TokenNameimplements
+ || operator == TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ }
+
+ // perform actual splitting
+ String result[] = splitLine.substrings;
+ int[] splitOperators = splitLine.operators;
+ int[] splitLineStartIndexes = splitLine.startSubstringsIndexes;
+
+ if (result[0].length() == 0) {
+ // when the substring 0 is null, the substring 1 is correctly indented.
+ depth--;
+ emptyFirstSubString = true;
+ }
+ // the operator going in front of the result[0] string is the operator parameter
+
+ for (int i = 0, max = result.length; i < max; i++) {
+ // the new depth is the current one if this is the first substring,
+ // the current one + 1 otherwise.
+
+ // if the substring is a comment, use the current indentation Level instead of the depth
+ // (-1 because the ouputline increases depth).
+ // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line comments)
+ String currentResult = result[i];
+
+ if (currentResult.length() != 0 || splitOperators[i] != 0) {
+ int newDepth =
+ (currentResult.startsWith("/*"/*nonNLS*/) || currentResult.startsWith("//"/*nonNLS*/))
+ ? indentationLevel - 1
+ : depth;
+ outputLine(
+ currentResult,
+ i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
+ i == 0 ? newDepth : newDepth + 1,
+ splitOperators[i],
+ i,
+ splitLine.startSubstringsIndexes,
+ currentString.indexOf(currentResult));
+ if (i != max - 1) {
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+ }
+ }
+ }
+ if (result.length == splitOperators.length - 1) {
+ int lastOperator = splitOperators[result.length];
+ String lastOperatorString = operatorString(lastOperator);
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+
+ if (breakLineBeforeOperator(lastOperator)) {
+ dumpTab(depth + 1);
+ if (lastOperator != 0) {
+ if (insertSpaceBefore(lastOperator)) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ formattedSource.append(lastOperatorString);
+ increaseSplitDelta(lastOperatorString.length());
+
+ if (insertSpaceAfter(lastOperator)
+ && lastOperator != TokenNameimplements
+ && lastOperator != TokenNameextends
+ && lastOperator != TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ }
+ }
+ }
+ if (placeOperatorBehind) {
+ if (insertSpaceBefore(operator)) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ formattedSource.append(operatorString);
+ //increaseSplitDelta(operatorString.length());
+ }
}
/**
* Pops the top statement of the stack if it is <code>token</code>
*/
private int pop(int token) {
- int delta=0;
- if ((constructionsCount>0) && (constructions[constructionsCount-1]==token)){
- delta--;
- constructionsCount--;
- }
- return delta;
+ int delta=0;
+ if ((constructionsCount>0) && (constructions[constructionsCount-1]==token)){
+ delta--;
+ constructionsCount--;
+ }
+ return delta;
}
/**
* Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
*/
private int popBlock() {
- int delta=0;
- if ((constructionsCount>0) && ((constructions[constructionsCount-1]==BLOCK) || (constructions[constructionsCount-1]==NONINDENT_BLOCK))){
- if (constructions[constructionsCount-1]==BLOCK)
- delta--;
- constructionsCount--;
- }
- return delta;
+ int delta=0;
+ if ((constructionsCount>0) && ((constructions[constructionsCount-1]==BLOCK) || (constructions[constructionsCount-1]==NONINDENT_BLOCK))){
+ if (constructions[constructionsCount-1]==BLOCK)
+ delta--;
+ constructionsCount--;
+ }
+ return delta;
}
/**
* Pops elements until the stack is empty or the top element is <code>token</code>.<br>
@@ -1598,14 +1606,14 @@ private int popBlock() {
* @param token the token to be left as the top of the stack
*/
private int popExclusiveUntil(int token) {
- int delta=0;
- int startCount=constructionsCount;
- for (int i = startCount-1; i >= 0 && constructions[i] != token; i--){
- if (constructions[i]!=NONINDENT_BLOCK)
- delta--;
- constructionsCount--;
- }
- return delta;
+ int delta=0;
+ int startCount=constructionsCount;
+ for (int i = startCount-1; i >= 0 && constructions[i] != token; i--){
+ if (constructions[i]!=NONINDENT_BLOCK)
+ delta--;
+ constructionsCount--;
+ }
+ return delta;
}
/**
* Pops elements until the stack is empty or the top element is
@@ -1613,13 +1621,13 @@ private int popExclusiveUntil(int token) {
* Does not remove it from the stack.
*/
private int popExclusiveUntilBlock(){
- int startCount=constructionsCount;
- int delta=0;
- for (int i = startCount-1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--){
- constructionsCount--;
- delta--;
- }
- return delta;
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--){
+ constructionsCount--;
+ delta--;
+ }
+ return delta;
}
/**
* Pops elements until the stack is empty or the top element is
@@ -1627,13 +1635,13 @@ private int popExclusiveUntilBlock(){
* Does not remove it from the stack.
*/
private int popExclusiveUntilBlockOrCase(){
- int startCount=constructionsCount;
- int delta=0;
- for (int i = startCount-1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK && constructions[i]!=TokenNamecase; i--){
- constructionsCount--;
- delta--;
- }
- return delta;
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK && constructions[i]!=TokenNamecase; i--){
+ constructionsCount--;
+ delta--;
+ }
+ return delta;
}
/**
* Pops elements until the stack is empty or the top element is <code>token</code>.<br>
@@ -1641,19 +1649,19 @@ private int popExclusiveUntilBlockOrCase(){
* @param token the token to remove from the stack
*/
private int popInclusiveUntil(int token) {
- int startCount=constructionsCount;
- int delta=0;
- for (int i = startCount-1; i >= 0 && constructions[i] != token; i--){
- if (constructions[i]!=NONINDENT_BLOCK)
- delta--;
- constructionsCount--;
- }
- if (constructionsCount>0){
- if (constructions[constructionsCount-1]!=NONINDENT_BLOCK)
- delta--;
- constructionsCount--;
- }
- return delta;
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && constructions[i] != token; i--){
+ if (constructions[i]!=NONINDENT_BLOCK)
+ delta--;
+ constructionsCount--;
+ }
+ if (constructionsCount>0){
+ if (constructions[constructionsCount-1]!=NONINDENT_BLOCK)
+ delta--;
+ constructionsCount--;
+ }
+ return delta;
}
/**
* Pops elements until the stack is empty or the top element is
@@ -1661,18 +1669,18 @@ private int popInclusiveUntil(int token) {
* Does not remove it from the stack.
*/
private int popInclusiveUntilBlock() {
- int startCount=constructionsCount;
- int delta=0;
- for (int i = startCount-1; i >= 0 && (constructions[i] != BLOCK && constructions[i]!=NONINDENT_BLOCK); i--){
- delta--;
- constructionsCount--;
- }
- if (constructionsCount>0){
- if (constructions[constructionsCount-1]==BLOCK)
- delta--;
- constructionsCount--;
- }
- return delta;
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && (constructions[i] != BLOCK && constructions[i]!=NONINDENT_BLOCK); i--){
+ delta--;
+ constructionsCount--;
+ }
+ if (constructionsCount>0){
+ if (constructions[constructionsCount-1]==BLOCK)
+ delta--;
+ constructionsCount--;
+ }
+ return delta;
}
/**
* Pushes a block in the stack.<br>
@@ -1681,45 +1689,45 @@ private int popInclusiveUntilBlock() {
* Creates a new bigger array if the current one is full.
*/
private int pushBlock() {
- int delta = 0;
- if (constructionsCount == constructions.length)
- System
- .arraycopy(constructions,
- 0,
- (constructions = new int[constructionsCount * 2]),
- 0,
- constructionsCount);
-
- if ((constructionsCount == 0)
- || (constructions[constructionsCount - 1] == BLOCK)
- || (constructions[constructionsCount - 1] == NONINDENT_BLOCK)
- || (constructions[constructionsCount - 1] == TokenNamecase)) {
- delta++;
- constructions[constructionsCount++] = BLOCK;
- }
- else {
- constructions[constructionsCount++] = NONINDENT_BLOCK;
- }
- return delta;
+ int delta = 0;
+ if (constructionsCount == constructions.length)
+ System
+ .arraycopy(constructions,
+ 0,
+ (constructions = new int[constructionsCount * 2]),
+ 0,
+ constructionsCount);
+
+ if ((constructionsCount == 0)
+ || (constructions[constructionsCount - 1] == BLOCK)
+ || (constructions[constructionsCount - 1] == NONINDENT_BLOCK)
+ || (constructions[constructionsCount - 1] == TokenNamecase)) {
+ delta++;
+ constructions[constructionsCount++] = BLOCK;
+ }
+ else {
+ constructions[constructionsCount++] = NONINDENT_BLOCK;
+ }
+ return delta;
}
/**
* Pushes <code>token</code>.<br>
* Creates a new bigger array if the current one is full.
*/
private int pushControlStatement(int token) {
- if (constructionsCount == constructions.length)
- System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
- constructions[constructionsCount++] = token;
- return 1;
+ if (constructionsCount == constructions.length)
+ System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
+ constructions[constructionsCount++] = token;
+ return 1;
}
private static boolean separateFirstArgumentOn(int currentToken) {
- //return (currentToken == TokenNameCOMMA || currentToken == TokenNameSEMICOLON);
- return currentToken != TokenNameif
- && currentToken != TokenNameLPAREN
- && currentToken != TokenNameNOT
- && currentToken != TokenNamewhile
- && currentToken != TokenNamefor
- && currentToken != TokenNameswitch;
+ //return (currentToken == TokenNameCOMMA || currentToken == TokenNameSEMICOLON);
+ return currentToken != TokenNameif
+ && currentToken != TokenNameLPAREN
+ && currentToken != TokenNameNOT
+ && currentToken != TokenNamewhile
+ && currentToken != TokenNamefor
+ && currentToken != TokenNameswitch;
}
/**
* Sets the behaviour of the formatter about the braces
@@ -1735,7 +1743,7 @@ private static boolean separateFirstArgumentOn(int currentToken) {
* @see addNewLineOnOpeningBrace(boolean)
*/
public void setBraceIndentationLevel(int newBraceIndentationLevel) {
- options.setNewLineBeforeOpeningBraceMode(newBraceIndentationLevel==0);
+ options.setNewLineBeforeOpeningBraceMode(newBraceIndentationLevel==0);
}
/**
* Sets the behaviour of the formatter regarding the whitespaces
@@ -1746,7 +1754,7 @@ public void setBraceIndentationLevel(int newBraceIndentationLevel) {
* @deprecated backward compatibility with VAJ
*/
public void setClearBlankLines(boolean newClearBlankLines) {
- options.setClearAllBlankLinesMode(newClearBlankLines);
+ options.setClearAllBlankLinesMode(newClearBlankLines);
}
/**
* Sets the number of consecutive spaces used to replace the tab char
@@ -1756,7 +1764,7 @@ public void setClearBlankLines(boolean newClearBlankLines) {
* @deprecated backward compatibility with VAJ
*/
public void setIndentationLength(int newIndentationLength) {
- options.setTabSize(newIndentationLength);
+ options.setTabSize(newIndentationLength);
}
/**
* Sets the initial indentation level
@@ -1765,7 +1773,7 @@ public void setIndentationLength(int newIndentationLength) {
* @deprecated
*/
public void setInitialIndentationLevel(int newIndentationLevel) {
- this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;
+ this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;
}
/**
* Sets the behaviour of the scanner.<br>
@@ -1778,7 +1786,7 @@ public void setInitialIndentationLevel(int newIndentationLevel) {
* @deprecated backward compatibility with VAJ
*/
public void setNewlineInCompoundStatement(boolean flag) {
- options.setNewlineInControlStatementMode(flag);
+ options.setNewlineInControlStatementMode(flag);
}
/**
* Set the positions to map. The mapped positions should be retrieved using the
@@ -1787,17 +1795,17 @@ public void setNewlineInCompoundStatement(boolean flag) {
* @param positions int[]
*/
public void setPositionsToMap(int[] positions) {
- positionsToMap = positions;
- lineDelta = 0;
- globalDelta = 0;
- mappedPositions = new int[positions.length];
+ positionsToMap = positions;
+ lineDelta = 0;
+ globalDelta = 0;
+ mappedPositions = new int[positions.length];
}
/**
* Appends a space character to the current line buffer.
*/
private void space() {
- currentLineBuffer.append(' ');
- increaseLineDelta(1);
+ currentLineBuffer.append(' ');
+ increaseLineDelta(1);
}
/**
* Splits <code>stringToSplit</code> on the top level token<br>
@@ -1807,7 +1815,7 @@ private void space() {
* or null if the string cannot be split
*/
public SplitLine split(String stringToSplit) {
- return split(stringToSplit, 0);
+ return split(stringToSplit, 0);
}
/**
* Splits <code>stringToSplit</code> on the top level token<br>
@@ -1817,476 +1825,476 @@ public SplitLine split(String stringToSplit) {
* or null if the string cannot be split
*/
public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
- // local variables
- int currentToken = 0;
- int splitTokenType = 0;
- int splitTokenDepth = Integer.MAX_VALUE;
- int splitTokenPriority = Integer.MAX_VALUE;
-
- int[] substringsStartPositions = new int[10];
- // contains the start position of substrings
- int[] substringsEndPositions = new int[10];
- // contains the start position of substrings
- int substringsCount = 1; // index in the substringsStartPosition array
- int[] splitOperators = new int[10];
- // contains the start position of substrings
- int splitOperatorsCount = 0; // index in the substringsStartPosition array
- int[] openParenthesisPosition = new int[10];
- int openParenthesisPositionCount = 0;
- int position = 0;
- int lastOpenParenthesisPosition = -1;
- // used to remember the position of the 1st open parenthesis
- // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
- // setup the scanner with a new source
- int lastCommentStartPosition = -1;
- // to remember the start position of the last comment
- int firstTokenOnLine = -1;
- // to remember the first token of the line
- int previousToken = -1;
- // to remember the previous token.
- splitScanner.setSourceBuffer(stringToSplit.toCharArray());
-
- try {
- // start the loop
- while (true) {
- // takes the next token
- try {
- if (currentToken != Scanner.TokenNameWHITESPACE)
- previousToken = currentToken;
- currentToken = splitScanner.getNextToken();
- } catch (InvalidInputException e) {
- if (!handleInvalidToken(e))
- throw e;
- currentToken = 0; // this value is not modify when an exception is raised.
- }
- if (currentToken == TokenNameEOF)
- break;
-
- if (firstTokenOnLine == -1){
- firstTokenOnLine = currentToken;
- }
-
-
- switch (currentToken) {
- case TokenNameRBRACE:
- case TokenNameRPAREN :
- if (openParenthesisPositionCount > 0) {
- if (openParenthesisPositionCount == 1 && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
- lastOpenParenthesisPosition = openParenthesisPosition[0];
- } else
- if ((splitTokenDepth == Integer.MAX_VALUE)
- || (splitTokenDepth > openParenthesisPositionCount
- && openParenthesisPositionCount == 1)) {
- splitTokenType = 0;
- splitTokenDepth = openParenthesisPositionCount;
- splitTokenPriority = Integer.MAX_VALUE;
- substringsStartPositions[0] = 0;
- // better token means the whole line until now is the first substring
- substringsCount = 1; // resets the count of substrings
-
- substringsEndPositions[0] = openParenthesisPosition[0];
- // substring ends on operator start
- position = openParenthesisPosition[0];
- // the string mustn't be cut before the closing parenthesis but after the opening one.
- splitOperatorsCount = 1; // resets the count of split operators
- splitOperators[0] = 0;
- }
- openParenthesisPositionCount--;
- }
- break;
- case TokenNameLBRACE:
- case TokenNameLPAREN :
- if (openParenthesisPositionCount == openParenthesisPosition.length) {
- System.arraycopy(
- openParenthesisPosition,
- 0,
- (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
- 0,
- openParenthesisPositionCount);
- }
- openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
- if (currentToken == TokenNameLPAREN && previousToken == TokenNameRPAREN){
- openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
- }
- break;
- case TokenNameSEMICOLON : // ;
- case TokenNameCOMMA : // ,
- case TokenNameEQUAL : // =
- if (openParenthesisPositionCount < splitTokenDepth
- || (openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority > getTokenPriority(currentToken))) {
- // the current token is better than the one we currently have
- // (in level or in priority if same level)
- // reset the substringsCount
- splitTokenDepth = openParenthesisPositionCount;
- splitTokenType = currentToken;
- splitTokenPriority = getTokenPriority(currentToken);
- substringsStartPositions[0] = 0;
- // better token means the whole line until now is the first substring
-
- if (separateFirstArgumentOn(firstTokenOnLine)
- && openParenthesisPositionCount > 0) {
- substringsCount = 2; // resets the count of substrings
-
- substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
- substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
- substringsEndPositions[1] = splitScanner.startPosition;
- splitOperatorsCount = 2; // resets the count of split operators
- splitOperators[0] = 0;
- splitOperators[1] = currentToken;
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- } else {
- substringsCount = 1; // resets the count of substrings
-
- substringsEndPositions[0] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperatorsCount = 1; // resets the count of split operators
- splitOperators[0] = currentToken;
- }
- } else {
- if ((openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority == getTokenPriority(currentToken))
- && splitTokenType!=TokenNameEQUAL && currentToken != TokenNameEQUAL) {
- // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after split
- // take only the 1st = into account.
- // if another token with the same priority is found,
- // push the start position of the substring and
- // push the token into the stack.
- // create a new array object if the current one is full.
- if (substringsCount == substringsStartPositions.length) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- }
- if (splitOperatorsCount == splitOperators.length) {
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount * 2]),
- 0,
- splitOperatorsCount);
- }
- substringsStartPositions[substringsCount] = position;
- substringsEndPositions[substringsCount++] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperators[splitOperatorsCount++] = currentToken;
- }
- }
- break;
-
- case TokenNameCOLON : // : (15.24)
- // see 1FK7C5R, we only split on a colon, when it is associated with a question-mark.
- // indeed it might appear also behind a case statement, and we do not to break at this point.
- if ((splitOperatorsCount == 0) || splitOperators[splitOperatorsCount-1] != TokenNameQUESTION){
- break;
- }
- case TokenNameextends :
- case TokenNameimplements :
- case TokenNamethrows :
-
- case TokenNameDOT : // .
- case TokenNameMULTIPLY : // * (15.16.1)
- case TokenNameDIVIDE : // / (15.16.2)
- case TokenNameREMAINDER : // % (15.16.3)
- case TokenNamePLUS : // + (15.17, 15.17.2)
- case TokenNameMINUS : // - (15.17.2)
- case TokenNameLEFT_SHIFT : // << (15.18)
- case TokenNameRIGHT_SHIFT : // >> (15.18)
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
- case TokenNameLESS : // < (15.19.1)
- case TokenNameLESS_EQUAL : // <= (15.19.1)
- case TokenNameGREATER : // > (15.19.1)
- case TokenNameGREATER_EQUAL : // >= (15.19.1)
- case TokenNameinstanceof : // instanceof
- case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
- case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
- case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
- case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
- case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
- case TokenNameAND_AND : // && (15.22)
- case TokenNameOR_OR : // || (15.23)
- case TokenNameQUESTION : // ? (15.24)
- case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
- case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
- case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
- case TokenNamePLUS_EQUAL : // += (15.25.2)
- case TokenNameMINUS_EQUAL : // -= (15.25.2)
- case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
- case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
- case TokenNameAND_EQUAL : // &= (15.25.2)
- case TokenNameXOR_EQUAL : // ^= (15.25.2)
- case TokenNameOR_EQUAL : // |= (15.25.2)
-
- if ((openParenthesisPositionCount < splitTokenDepth
- || (openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority > getTokenPriority(currentToken)))
- &&
- !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS)
- && (previousToken == TokenNameLBRACE || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))){
- // the current token is better than the one we currently have
- // (in level or in priority if same level)
- // reset the substringsCount
- splitTokenDepth = openParenthesisPositionCount;
- splitTokenType = currentToken;
- splitTokenPriority = getTokenPriority(currentToken);
- substringsStartPositions[0] = 0;
- // better token means the whole line until now is the first substring
-
- if (separateFirstArgumentOn(firstTokenOnLine)
- && openParenthesisPositionCount > 0) {
- substringsCount = 2; // resets the count of substrings
-
- substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
- substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
- substringsEndPositions[1] = splitScanner.startPosition;
- splitOperatorsCount = 3; // resets the count of split operators
- splitOperators[0] = 0;
- splitOperators[1] = 0;
- splitOperators[2] = currentToken;
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- } else {
- substringsCount = 1; // resets the count of substrings
-
- substringsEndPositions[0] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperatorsCount = 2; // resets the count of split operators
- splitOperators[0] = 0;
- // nothing for first operand since operator will be inserted in front of the second operand
- splitOperators[1] = currentToken;
-
- }
- } else {
- if (openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority == getTokenPriority(currentToken)) {
- // if another token with the same priority is found,
- // push the start position of the substring and
- // push the token into the stack.
- // create a new array object if the current one is full.
- if (substringsCount == substringsStartPositions.length) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- }
- if (splitOperatorsCount == splitOperators.length) {
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount * 2]),
- 0,
- splitOperatorsCount);
- }
- substringsStartPositions[substringsCount] = position;
- substringsEndPositions[substringsCount++] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperators[splitOperatorsCount++] = currentToken;
- }
- }
- default :
- break;
- }
- if (isComment(currentToken)) {
- lastCommentStartPosition = splitScanner.startPosition;
- } else {
- lastCommentStartPosition = -1;
- }
- }
- } catch (InvalidInputException e) {
- return null;
- }
- // if the string cannot be split, return null.
- if (splitOperatorsCount == 0)
- return null;
-
- // ## SPECIAL CASES BEGIN
- if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1)
- || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength)
- || (separateFirstArgumentOn(firstTokenOnLine) && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1))
- && (lastOpenParenthesisPosition<splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition]!=')')){
- // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should not be broken on two lines
- // only one split on a top level .
- // or more than one split on . and substring before open parenthesis fits one line.
- // or split inside parenthesis and first token is not a for/while/if
- SplitLine sl = split(stringToSplit.substring(lastOpenParenthesisPosition), lastOpenParenthesisPosition);
- if (sl == null || sl.operators[0] != TokenNameCOMMA) {
- // trim() is used to remove the extra blanks at the end of the substring. See PR 1FGYPI1
- return new SplitLine(
- new int[] {0, 0},
- new String[] {
- stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
- stringToSplit.substring(lastOpenParenthesisPosition)},
- new int[] {offsetInGlobalLine, lastOpenParenthesisPosition + offsetInGlobalLine});
- } else {
-
- // right substring can be split and is split on comma
- // copy substrings and operators
- // except if the 1st string is empty.
-
- int startIndex = (sl.substrings[0].length()==0)?1:0;
-
- int subStringsLength = sl.substrings.length + 1 - startIndex;
- String[] result = new String[subStringsLength];
- int[] startIndexes = new int[subStringsLength];
- int operatorsLength = sl.operators.length + 1 - startIndex;
- int[] operators = new int[operatorsLength];
-
- result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
- operators[0] = 0;
-
- System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes, 1, subStringsLength - 1);
- for (int i = subStringsLength - 1; i >= 0; i--) {
- startIndexes[i] += offsetInGlobalLine;
- }
- System.arraycopy(sl.substrings, startIndex, result, 1, subStringsLength - 1);
- System.arraycopy(sl.operators, startIndex, operators, 1, operatorsLength - 1);
-
- return new SplitLine(operators, result, startIndexes);
- }
- }
-
- // if the last token is a comment and the substring before the comment fits on a line,
- // split before the comment and return the result.
- if (lastCommentStartPosition > -1
- && lastCommentStartPosition < options.maxLineLength
- && splitTokenPriority > 50) {
- int end = lastCommentStartPosition;
- int start = lastCommentStartPosition;
- if (stringToSplit.charAt(end - 1) == ' ') {
- end--;
- }
- if (start != end && stringToSplit.charAt(start) == ' ') {
- start++;
- }
- return new SplitLine(
- new int[] {0, 0},
- new String[] {
- stringToSplit.substring(0, end),
- stringToSplit.substring(start)},
- new int[] {0, start});
- }
-
- if (position != stringToSplit.length()) {
-
- if (substringsCount == substringsStartPositions.length) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- }
- // avoid empty extra substring, e.g. line terminated with a semi-colon
- substringsStartPositions[substringsCount] = position;
- substringsEndPositions[substringsCount++] = stringToSplit.length();
- }
-
- if (splitOperatorsCount == splitOperators.length) {
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount * 2]),
- 0,
- splitOperatorsCount);
- }
-
- splitOperators[splitOperatorsCount] = 0;
-
- // the last element of the stack is the position of the end of StringToSPlit
- // +1 because the substring method excludes the last character
- String[] result = new String[substringsCount];
- for (int i = 0; i < substringsCount; i++) {
- int start = substringsStartPositions[i];
- int end = substringsEndPositions[i];
- if (stringToSplit.charAt(start) == ' ') {
- start++;
- substringsStartPositions[i]++;
- }
- if (end != start && stringToSplit.charAt(end - 1) == ' ') {
- end--;
- }
-
- result[i] = stringToSplit.substring(start, end);
- substringsStartPositions[i] += offsetInGlobalLine;
- }
- if (splitOperatorsCount > substringsCount) {
- System.arraycopy(substringsStartPositions, 0, (substringsStartPositions = new int[splitOperatorsCount]), 0, substringsCount);
- System.arraycopy(substringsEndPositions, 0, (substringsEndPositions = new int[splitOperatorsCount]), 0, substringsCount);
- for (int i = substringsCount; i < splitOperatorsCount; i++) {
- substringsStartPositions[i] = position;
- substringsEndPositions[i] = position;
- }
- System.arraycopy(splitOperators, 0, (splitOperators = new int[splitOperatorsCount]), 0, splitOperatorsCount);
- } else {
- System.arraycopy(substringsStartPositions, 0, (substringsStartPositions = new int[substringsCount]), 0, substringsCount);
- System.arraycopy(substringsEndPositions, 0, (substringsEndPositions = new int[substringsCount]), 0, substringsCount);
- System.arraycopy(splitOperators, 0, (splitOperators = new int[substringsCount]), 0, substringsCount);
- }
-
- SplitLine splitLine = new SplitLine(splitOperators, result, substringsStartPositions);
- return splitLine;
+ // local variables
+ int currentToken = 0;
+ int splitTokenType = 0;
+ int splitTokenDepth = Integer.MAX_VALUE;
+ int splitTokenPriority = Integer.MAX_VALUE;
+
+ int[] substringsStartPositions = new int[10];
+ // contains the start position of substrings
+ int[] substringsEndPositions = new int[10];
+ // contains the start position of substrings
+ int substringsCount = 1; // index in the substringsStartPosition array
+ int[] splitOperators = new int[10];
+ // contains the start position of substrings
+ int splitOperatorsCount = 0; // index in the substringsStartPosition array
+ int[] openParenthesisPosition = new int[10];
+ int openParenthesisPositionCount = 0;
+ int position = 0;
+ int lastOpenParenthesisPosition = -1;
+ // used to remember the position of the 1st open parenthesis
+ // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
+ // setup the scanner with a new source
+ int lastCommentStartPosition = -1;
+ // to remember the start position of the last comment
+ int firstTokenOnLine = -1;
+ // to remember the first token of the line
+ int previousToken = -1;
+ // to remember the previous token.
+ splitScanner.setSourceBuffer(stringToSplit.toCharArray());
+
+ try {
+ // start the loop
+ while (true) {
+ // takes the next token
+ try {
+ if (currentToken != Scanner.TokenNameWHITESPACE)
+ previousToken = currentToken;
+ currentToken = splitScanner.getNextToken();
+ } catch (InvalidInputException e) {
+ if (!handleInvalidToken(e))
+ throw e;
+ currentToken = 0; // this value is not modify when an exception is raised.
+ }
+ if (currentToken == TokenNameEOF)
+ break;
+
+ if (firstTokenOnLine == -1){
+ firstTokenOnLine = currentToken;
+ }
+
+
+ switch (currentToken) {
+ case TokenNameRBRACE:
+ case TokenNameRPAREN :
+ if (openParenthesisPositionCount > 0) {
+ if (openParenthesisPositionCount == 1 && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
+ lastOpenParenthesisPosition = openParenthesisPosition[0];
+ } else
+ if ((splitTokenDepth == Integer.MAX_VALUE)
+ || (splitTokenDepth > openParenthesisPositionCount
+ && openParenthesisPositionCount == 1)) {
+ splitTokenType = 0;
+ splitTokenDepth = openParenthesisPositionCount;
+ splitTokenPriority = Integer.MAX_VALUE;
+ substringsStartPositions[0] = 0;
+ // better token means the whole line until now is the first substring
+ substringsCount = 1; // resets the count of substrings
+
+ substringsEndPositions[0] = openParenthesisPosition[0];
+ // substring ends on operator start
+ position = openParenthesisPosition[0];
+ // the string mustn't be cut before the closing parenthesis but after the opening one.
+ splitOperatorsCount = 1; // resets the count of split operators
+ splitOperators[0] = 0;
+ }
+ openParenthesisPositionCount--;
+ }
+ break;
+ case TokenNameLBRACE:
+ case TokenNameLPAREN :
+ if (openParenthesisPositionCount == openParenthesisPosition.length) {
+ System.arraycopy(
+ openParenthesisPosition,
+ 0,
+ (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
+ 0,
+ openParenthesisPositionCount);
+ }
+ openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
+ if (currentToken == TokenNameLPAREN && previousToken == TokenNameRPAREN){
+ openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
+ }
+ break;
+ case TokenNameSEMICOLON : // ;
+ case TokenNameCOMMA : // ,
+ case TokenNameEQUAL : // =
+ if (openParenthesisPositionCount < splitTokenDepth
+ || (openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority > getTokenPriority(currentToken))) {
+ // the current token is better than the one we currently have
+ // (in level or in priority if same level)
+ // reset the substringsCount
+ splitTokenDepth = openParenthesisPositionCount;
+ splitTokenType = currentToken;
+ splitTokenPriority = getTokenPriority(currentToken);
+ substringsStartPositions[0] = 0;
+ // better token means the whole line until now is the first substring
+
+ if (separateFirstArgumentOn(firstTokenOnLine)
+ && openParenthesisPositionCount > 0) {
+ substringsCount = 2; // resets the count of substrings
+
+ substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsEndPositions[1] = splitScanner.startPosition;
+ splitOperatorsCount = 2; // resets the count of split operators
+ splitOperators[0] = 0;
+ splitOperators[1] = currentToken;
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ } else {
+ substringsCount = 1; // resets the count of substrings
+
+ substringsEndPositions[0] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperatorsCount = 1; // resets the count of split operators
+ splitOperators[0] = currentToken;
+ }
+ } else {
+ if ((openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority == getTokenPriority(currentToken))
+ && splitTokenType!=TokenNameEQUAL && currentToken != TokenNameEQUAL) {
+ // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after split
+ // take only the 1st = into account.
+ // if another token with the same priority is found,
+ // push the start position of the substring and
+ // push the token into the stack.
+ // create a new array object if the current one is full.
+ if (substringsCount == substringsStartPositions.length) {
+ System.arraycopy(
+ substringsStartPositions,
+ 0,
+ (substringsStartPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ System.arraycopy(
+ substringsEndPositions,
+ 0,
+ (substringsEndPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ }
+ if (splitOperatorsCount == splitOperators.length) {
+ System.arraycopy(
+ splitOperators,
+ 0,
+ (splitOperators = new int[splitOperatorsCount * 2]),
+ 0,
+ splitOperatorsCount);
+ }
+ substringsStartPositions[substringsCount] = position;
+ substringsEndPositions[substringsCount++] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperators[splitOperatorsCount++] = currentToken;
+ }
+ }
+ break;
+
+ case TokenNameCOLON : // : (15.24)
+ // see 1FK7C5R, we only split on a colon, when it is associated with a question-mark.
+ // indeed it might appear also behind a case statement, and we do not to break at this point.
+ if ((splitOperatorsCount == 0) || splitOperators[splitOperatorsCount-1] != TokenNameQUESTION){
+ break;
+ }
+ case TokenNameextends :
+ case TokenNameimplements :
+ case TokenNamethrows :
+
+ case TokenNameDOT : // .
+ case TokenNameMULTIPLY : // * (15.16.1)
+ case TokenNameDIVIDE : // / (15.16.2)
+ case TokenNameREMAINDER : // % (15.16.3)
+ case TokenNamePLUS : // + (15.17, 15.17.2)
+ case TokenNameMINUS : // - (15.17.2)
+ case TokenNameLEFT_SHIFT : // << (15.18)
+ case TokenNameRIGHT_SHIFT : // >> (15.18)
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
+ case TokenNameLESS : // < (15.19.1)
+ case TokenNameLESS_EQUAL : // <= (15.19.1)
+ case TokenNameGREATER : // > (15.19.1)
+ case TokenNameGREATER_EQUAL : // >= (15.19.1)
+ case TokenNameinstanceof : // instanceof
+ case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
+ case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
+ case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
+ case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
+ case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
+ case TokenNameAND_AND : // && (15.22)
+ case TokenNameOR_OR : // || (15.23)
+ case TokenNameQUESTION : // ? (15.24)
+ case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
+ case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
+ case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
+ case TokenNamePLUS_EQUAL : // += (15.25.2)
+ case TokenNameMINUS_EQUAL : // -= (15.25.2)
+ case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
+ case TokenNameAND_EQUAL : // &= (15.25.2)
+ case TokenNameXOR_EQUAL : // ^= (15.25.2)
+ case TokenNameOR_EQUAL : // |= (15.25.2)
+
+ if ((openParenthesisPositionCount < splitTokenDepth
+ || (openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority > getTokenPriority(currentToken)))
+ &&
+ !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS)
+ && (previousToken == TokenNameLBRACE || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))){
+ // the current token is better than the one we currently have
+ // (in level or in priority if same level)
+ // reset the substringsCount
+ splitTokenDepth = openParenthesisPositionCount;
+ splitTokenType = currentToken;
+ splitTokenPriority = getTokenPriority(currentToken);
+ substringsStartPositions[0] = 0;
+ // better token means the whole line until now is the first substring
+
+ if (separateFirstArgumentOn(firstTokenOnLine)
+ && openParenthesisPositionCount > 0) {
+ substringsCount = 2; // resets the count of substrings
+
+ substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsEndPositions[1] = splitScanner.startPosition;
+ splitOperatorsCount = 3; // resets the count of split operators
+ splitOperators[0] = 0;
+ splitOperators[1] = 0;
+ splitOperators[2] = currentToken;
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ } else {
+ substringsCount = 1; // resets the count of substrings
+
+ substringsEndPositions[0] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperatorsCount = 2; // resets the count of split operators
+ splitOperators[0] = 0;
+ // nothing for first operand since operator will be inserted in front of the second operand
+ splitOperators[1] = currentToken;
+
+ }
+ } else {
+ if (openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority == getTokenPriority(currentToken)) {
+ // if another token with the same priority is found,
+ // push the start position of the substring and
+ // push the token into the stack.
+ // create a new array object if the current one is full.
+ if (substringsCount == substringsStartPositions.length) {
+ System.arraycopy(
+ substringsStartPositions,
+ 0,
+ (substringsStartPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ System.arraycopy(
+ substringsEndPositions,
+ 0,
+ (substringsEndPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ }
+ if (splitOperatorsCount == splitOperators.length) {
+ System.arraycopy(
+ splitOperators,
+ 0,
+ (splitOperators = new int[splitOperatorsCount * 2]),
+ 0,
+ splitOperatorsCount);
+ }
+ substringsStartPositions[substringsCount] = position;
+ substringsEndPositions[substringsCount++] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperators[splitOperatorsCount++] = currentToken;
+ }
+ }
+ default :
+ break;
+ }
+ if (isComment(currentToken)) {
+ lastCommentStartPosition = splitScanner.startPosition;
+ } else {
+ lastCommentStartPosition = -1;
+ }
+ }
+ } catch (InvalidInputException e) {
+ return null;
+ }
+ // if the string cannot be split, return null.
+ if (splitOperatorsCount == 0)
+ return null;
+
+ // ## SPECIAL CASES BEGIN
+ if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1)
+ || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength)
+ || (separateFirstArgumentOn(firstTokenOnLine) && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1))
+ && (lastOpenParenthesisPosition<splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition]!=')')){
+ // fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should not be broken on two lines
+ // only one split on a top level .
+ // or more than one split on . and substring before open parenthesis fits one line.
+ // or split inside parenthesis and first token is not a for/while/if
+ SplitLine sl = split(stringToSplit.substring(lastOpenParenthesisPosition), lastOpenParenthesisPosition);
+ if (sl == null || sl.operators[0] != TokenNameCOMMA) {
+ // trim() is used to remove the extra blanks at the end of the substring. See PR 1FGYPI1
+ return new SplitLine(
+ new int[] {0, 0},
+ new String[] {
+ stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
+ stringToSplit.substring(lastOpenParenthesisPosition)},
+ new int[] {offsetInGlobalLine, lastOpenParenthesisPosition + offsetInGlobalLine});
+ } else {
+
+ // right substring can be split and is split on comma
+ // copy substrings and operators
+ // except if the 1st string is empty.
+
+ int startIndex = (sl.substrings[0].length()==0)?1:0;
+
+ int subStringsLength = sl.substrings.length + 1 - startIndex;
+ String[] result = new String[subStringsLength];
+ int[] startIndexes = new int[subStringsLength];
+ int operatorsLength = sl.operators.length + 1 - startIndex;
+ int[] operators = new int[operatorsLength];
+
+ result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
+ operators[0] = 0;
+
+ System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes, 1, subStringsLength - 1);
+ for (int i = subStringsLength - 1; i >= 0; i--) {
+ startIndexes[i] += offsetInGlobalLine;
+ }
+ System.arraycopy(sl.substrings, startIndex, result, 1, subStringsLength - 1);
+ System.arraycopy(sl.operators, startIndex, operators, 1, operatorsLength - 1);
+
+ return new SplitLine(operators, result, startIndexes);
+ }
+ }
+
+ // if the last token is a comment and the substring before the comment fits on a line,
+ // split before the comment and return the result.
+ if (lastCommentStartPosition > -1
+ && lastCommentStartPosition < options.maxLineLength
+ && splitTokenPriority > 50) {
+ int end = lastCommentStartPosition;
+ int start = lastCommentStartPosition;
+ if (stringToSplit.charAt(end - 1) == ' ') {
+ end--;
+ }
+ if (start != end && stringToSplit.charAt(start) == ' ') {
+ start++;
+ }
+ return new SplitLine(
+ new int[] {0, 0},
+ new String[] {
+ stringToSplit.substring(0, end),
+ stringToSplit.substring(start)},
+ new int[] {0, start});
+ }
+
+ if (position != stringToSplit.length()) {
+
+ if (substringsCount == substringsStartPositions.length) {
+ System.arraycopy(
+ substringsStartPositions,
+ 0,
+ (substringsStartPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ System.arraycopy(
+ substringsEndPositions,
+ 0,
+ (substringsEndPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ }
+ // avoid empty extra substring, e.g. line terminated with a semi-colon
+ substringsStartPositions[substringsCount] = position;
+ substringsEndPositions[substringsCount++] = stringToSplit.length();
+ }
+
+ if (splitOperatorsCount == splitOperators.length) {
+ System.arraycopy(
+ splitOperators,
+ 0,
+ (splitOperators = new int[splitOperatorsCount * 2]),
+ 0,
+ splitOperatorsCount);
+ }
+
+ splitOperators[splitOperatorsCount] = 0;
+
+ // the last element of the stack is the position of the end of StringToSPlit
+ // +1 because the substring method excludes the last character
+ String[] result = new String[substringsCount];
+ for (int i = 0; i < substringsCount; i++) {
+ int start = substringsStartPositions[i];
+ int end = substringsEndPositions[i];
+ if (stringToSplit.charAt(start) == ' ') {
+ start++;
+ substringsStartPositions[i]++;
+ }
+ if (end != start && stringToSplit.charAt(end - 1) == ' ') {
+ end--;
+ }
+
+ result[i] = stringToSplit.substring(start, end);
+ substringsStartPositions[i] += offsetInGlobalLine;
+ }
+ if (splitOperatorsCount > substringsCount) {
+ System.arraycopy(substringsStartPositions, 0, (substringsStartPositions = new int[splitOperatorsCount]), 0, substringsCount);
+ System.arraycopy(substringsEndPositions, 0, (substringsEndPositions = new int[splitOperatorsCount]), 0, substringsCount);
+ for (int i = substringsCount; i < splitOperatorsCount; i++) {
+ substringsStartPositions[i] = position;
+ substringsEndPositions[i] = position;
+ }
+ System.arraycopy(splitOperators, 0, (splitOperators = new int[splitOperatorsCount]), 0, splitOperatorsCount);
+ } else {
+ System.arraycopy(substringsStartPositions, 0, (substringsStartPositions = new int[substringsCount]), 0, substringsCount);
+ System.arraycopy(substringsEndPositions, 0, (substringsEndPositions = new int[substringsCount]), 0, substringsCount);
+ System.arraycopy(splitOperators, 0, (splitOperators = new int[substringsCount]), 0, substringsCount);
+ }
+
+ SplitLine splitLine = new SplitLine(splitOperators, result, substringsStartPositions);
+ return splitLine;
}
private void updateMappedPositions(int startPosition) {
- if (positionsToMap == null) return;
- char[] source = scanner.source;
- int sourceLength = source.length;
- while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) {
- int posToMap = positionsToMap[indexToMap];
- if (posToMap < 0 || posToMap >= sourceLength){ // protection against out of bounds position
- indexToMap = positionsToMap.length; // no more mapping
- return;
- }
- if (Character.isWhitespace(source[posToMap])) {
- mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
- } else {
- mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
- }
- indexToMap++;
- }
+ if (positionsToMap == null) return;
+ char[] source = scanner.source;
+ int sourceLength = source.length;
+ while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) {
+ int posToMap = positionsToMap[indexToMap];
+ if (posToMap < 0 || posToMap >= sourceLength){ // protection against out of bounds position
+ indexToMap = positionsToMap.length; // no more mapping
+ return;
+ }
+ if (Character.isWhitespace(source[posToMap])) {
+ mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
+ } else {
+ mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
+ }
+ indexToMap++;
+ }
}
private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) {
- if (mappedPositions == null || mappedPositions.length == indexInMap) return;
-
- while(indexInMap < mappedPositions.length
- && startPosition <= mappedPositions[indexInMap]
- && mappedPositions[indexInMap] < endPosition
- && indexInMap < indexToMap) {
- mappedPositions[indexInMap]+= splitDelta;
- indexInMap++;
- }
+ if (mappedPositions == null || mappedPositions.length == indexInMap) return;
+
+ while(indexInMap < mappedPositions.length
+ && startPosition <= mappedPositions[indexInMap]
+ && mappedPositions[indexInMap] < endPosition
+ && indexInMap < indexToMap) {
+ mappedPositions[indexInMap]+= splitDelta;
+ indexInMap++;
+ }
}
}
diff --git a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java
index fd6b7aeebf..4a295121e9 100644
--- a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java
+++ b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java
@@ -8,8 +8,21 @@ import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.formatter.*;
import java.util.*;
-public class FormatterOptions {
+public class FormatterOptions {
+ /**
+ * Option IDs
+ */
+ public static final String OPTION_InsertNewlineBeforeOpeningBrace = CodeFormatter.class.getName() + ".newlineOpeningBrace"/*nonNLS*/;
+ public static final String OPTION_InsertNewlineInControlStatement = CodeFormatter.class.getName() + ".newlineControlStatement"/*nonNLS*/;
+ public static final String OPTION_InsertNewLineBetweenElseAndIf = CodeFormatter.class.getName() + ".newlineElseIf"/*nonNLS*/;
+ public static final String OPTION_InsertNewLineInEmptyBlock = CodeFormatter.class.getName() + ".newlineEmptyBlock"/*nonNLS*/;
+ public static final String OPTION_ClearAllBlankLines = CodeFormatter.class.getName() + ".newlineClearAll"/*nonNLS*/;
+ public static final String OPTION_SplitLineExceedingLength = CodeFormatter.class.getName() + ".lineSplit"/*nonNLS*/;
+ public static final String OPTION_CompactAssignment = CodeFormatter.class.getName() + ".compactAssignment"/*nonNLS*/;
+ public static final String OPTION_TabulationChar = CodeFormatter.class.getName() + ".tabulationChar"/*nonNLS*/;
+ public static final String OPTION_TabulationSize = CodeFormatter.class.getName() + ".tabulationSize"/*nonNLS*/;
+
// by default, do not insert blank line before opening brace
public boolean newLineBeforeOpeningBraceMode = false;
@@ -42,7 +55,8 @@ public FormatterOptions(){
*/
public FormatterOptions(ConfigurableOption[] settings){
if (settings == null) return;
- // filter options which are related to the compiler component
+
+ // filter options which are related to the formatter component
String componentName = CodeFormatter.class.getName();
for (int i = 0, max = settings.length; i < max; i++){
if (settings[i].getComponentName().equals(componentName)){
@@ -50,26 +64,7 @@ public FormatterOptions(ConfigurableOption[] settings){
}
}
}
-/**
- * Returns all the options of the Code Formatter to be shown by the UI
- *
- * @param locale java.util.Locale
- * @return com.ibm.compiler.java.ConfigurableOption[]
- */
-public ConfigurableOption[] getConfigurableOptions(Locale locale) {
- String componentName = CodeFormatter.class.getName();
- return new ConfigurableOption[] {
- new ConfigurableOption(componentName, "newline.openingBrace"/*nonNLS*/, locale, newLineBeforeOpeningBraceMode ? 0 : 1),
- new ConfigurableOption(componentName, "newline.controlStatement"/*nonNLS*/, locale, newlineInControlStatementMode ? 0 : 1),
- new ConfigurableOption(componentName, "newline.clearAll"/*nonNLS*/, locale, clearAllBlankLinesMode ? 0 : 1),
- new ConfigurableOption(componentName, "newline.elseIf"/*nonNLS*/, locale, compactElseIfMode ? 0 : 1),
- new ConfigurableOption(componentName, "newline.emptyBlock"/*nonNLS*/, locale, newLineInEmptyBlockMode ? 0 : 1),
- new ConfigurableOption(componentName, "line.split"/*nonNLS*/, locale, maxLineLength),
- new ConfigurableOption(componentName, "style.compactAssignment"/*nonNLS*/, locale, compactAssignmentMode ? 0 : 1),
- new ConfigurableOption(componentName, "tabulation.char"/*nonNLS*/, locale, indentWithTab ? 0 : 1),
- new ConfigurableOption(componentName, "tabulation.size"/*nonNLS*/, locale, tabSize)
- };
-}
+
/**
*
* @return int
@@ -160,37 +155,36 @@ public void setNewLineInEmptyBlockMode(boolean flag) {
* @param newValue <CODE>int</CODE>
*/
public void setOption(ConfigurableOption setting) {
-
- switch (setting.getID()) {
- case 1 : // insert blank line before opening brace
- setNewLineBeforeOpeningBraceMode(setting.getCurrentValueIndex() == 0);
- break;
- case 2 : // insert blank line behind keywords (ELSE, CATCH, FINALLY,...) in control statements
- setNewlineInControlStatementMode(setting.getCurrentValueIndex() == 0);
- break;
- case 3 : // flush all blank lines
- setClearAllBlankLinesMode(setting.getCurrentValueIndex() == 0);
- break;
- case 4 : // puts else if on the same line
- setCompactElseIfMode(setting.getCurrentValueIndex() == 0);
- break;
- case 5 : // add a new line inside an empty block.
- setNewLineInEmptyBlockMode(setting.getCurrentValueIndex() == 0);
- break;
- case 6 : // line splitting will occur when line exceeds this length (0 -> no splitting)
- setMaxLineLength(setting.getCurrentValueIndex());
- break;
- case 7 : // if isTrue, assignments look like x= 12 (not like x = 12);
- setCompactAssignmentMode(setting.getCurrentValueIndex() == 0);
- break;
- case 9 : // should use tab or spaces to indent
- setIndentationUsesTab(setting.getCurrentValueIndex() == 0);
- break;
- case 10 : // amount of spaces for a tabulation
- setTabSize(setting.getCurrentValueIndex());
- break;
+
+ String optionID = setting.getID();
+
+ if(optionID.equals(OPTION_InsertNewlineBeforeOpeningBrace)){
+ setNewLineBeforeOpeningBraceMode(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_InsertNewlineInControlStatement)){
+ setNewlineInControlStatementMode(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_ClearAllBlankLines)){
+ setClearAllBlankLinesMode(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_InsertNewLineBetweenElseAndIf)){
+ setCompactElseIfMode(setting.getValueIndex() == 1);
+ }else if(optionID.equals(OPTION_InsertNewLineInEmptyBlock)){
+ setNewLineInEmptyBlockMode(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_SplitLineExceedingLength)){
+ try {
+ setMaxLineLength(Integer.parseInt(setting.getValue()));
+ } catch(NumberFormatException e){
+ }
+ }else if(optionID.equals(OPTION_CompactAssignment)){
+ setCompactAssignmentMode(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_TabulationChar)){
+ setIndentationUsesTab(setting.getValueIndex() == 0);
+ }else if(optionID.equals(OPTION_TabulationSize)){
+ try {
+ setTabSize(Integer.parseInt(setting.getValue()));
+ } catch(NumberFormatException e){
+ }
}
}
+
public void setReuseExistingLayoutMode(boolean flag) {
}
public void setTabSize(int size) {
diff --git a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java
index 72ab9b9949..912da60e27 100644
--- a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java
+++ b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java
@@ -40,8 +40,10 @@ public String toString() {
String currentString = substrings[i];
boolean placeOperatorAhead = currentOperator != TerminalSymbols.TokenNameCOMMA && currentOperator != TerminalSymbols.TokenNameSEMICOLON;
boolean placeOperatorBehind = currentOperator == TerminalSymbols.TokenNameCOMMA || currentOperator == TerminalSymbols.TokenNameSEMICOLON;
+
+
- switch (currentOperator){
+ switch (currentOperator){
case TokenNameextends:
operatorString="extends"/*nonNLS*/;
break;
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java
index 6297996c38..27dfaa148f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java
@@ -227,4 +227,13 @@ public interface IJavaModelStatusConstants {
* Status constant indicating that a classpath entry was invalid
*/
public static final int INVALID_CLASSPATH = 964;
+ /**
+ * Status constant indicating that a value is not a possible value
+ * for an option.
+ */
+ public static final int INVALID_OPTION_VALUE = 963;
+ /**
+ * Status constant indicating that an option is not an existing option.
+ */
+ public static final int INVALID_OPTION = 962;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java
index 202c33e4df..e43b5975d4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.runtime.*;
import org.eclipse.core.resources.*;
@@ -13,6 +13,8 @@ import java.net.URL;
import java.util.*;
import org.eclipse.jdt.internal.compiler.*;
+import org.eclipse.jdt.internal.compiler.Compiler;
+import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.core.builder.*;
@@ -20,6 +22,8 @@ import org.eclipse.jdt.internal.core.*;
import org.eclipse.jdt.internal.core.builder.impl.*;
import org.eclipse.jdt.internal.core.builder.impl.ProblemFactory;
import org.eclipse.jdt.internal.core.search.indexing.*;
+import org.eclipse.jdt.internal.formatter.CodeFormatter;
+import org.eclipse.jdt.internal.formatter.impl.FormatterOptions;
/**
* The plug-in runtime class for the Java model plug-in containing the core
@@ -39,25 +43,25 @@ import org.eclipse.jdt.internal.core.search.indexing.*;
*/
public final class JavaCore extends Plugin implements IExecutableExtension {
-
private static Plugin JAVA_CORE_PLUGIN = null;
/**
* The plug-in identifier of the Java core support
* (value <code>"org.eclipse.jdt.core"</code>).
*/
- public static final String PLUGIN_ID = "org.eclipse.jdt.core"/*nonNLS*/; // getPlugin().getDescriptor().getUniqueIdentifier();
+ public static final String PLUGIN_ID = "org.eclipse.jdt.core" /*nonNLS*/;
+ // getPlugin().getDescriptor().getUniqueIdentifier();
/**
* The identifier for the Java builder
* (value <code>"org.eclipse.jdt.core.javabuilder"</code>).
*/
- public static final String BUILDER_ID = PLUGIN_ID + ".javabuilder"/*nonNLS*/;
+ public static final String BUILDER_ID = PLUGIN_ID + ".javabuilder" /*nonNLS*/;
/**
* The identifier for the Java model
* (value <code>"org.eclipse.jdt.core.javamodel"</code>).
*/
- public static final String MODEL_ID = PLUGIN_ID + ".javamodel"/*nonNLS*/;
+ public static final String MODEL_ID = PLUGIN_ID + ".javamodel" /*nonNLS*/;
/**
* The identifier for the Java nature
@@ -67,358 +71,347 @@ public final class JavaCore extends Plugin implements IExecutableExtension {
*
* @see org.eclipse.core.resources.IProject#hasNature
*/
- public static final String NATURE_ID = PLUGIN_ID + ".javanature"/*nonNLS*/;
+ public static final String NATURE_ID = PLUGIN_ID + ".javanature" /*nonNLS*/;
/**
* Name of the handle id attribute in a Java marker
*/
- private static final String ATT_HANDLE_ID= "org.eclipse.jdt.internal.core.JavaModelManager.handleId"/*nonNLS*/;
+ private static final String ATT_HANDLE_ID =
+ "org.eclipse.jdt.internal.core.JavaModelManager.handleId" /*nonNLS*/;
+
+ private static Hashtable Variables = new Hashtable(5);
/**
- * Names of recognized configurable options
+ * Configurable option names. For further information, refer to the file named Java.ini
*/
- public static final String COMPILER_LOCAL_VARIABLE_ATTR = PLUGIN_ID + ".compiler.debug.localVariable"/*nonNLS*/;
- // possible values are GENERATE or DO_NOT_GENERATE (default is DO_NOT_GENERATE)
-
- public static final String COMPILER_LINE_NUMBER_ATTR = PLUGIN_ID + ".compiler.debug.lineNumber"/*nonNLS*/;
- // possible values are GENERATE or DO_NOT_GENERATE (default is GENERATE)
-
- public static final String COMPILER_SOURCE_FILE_ATTR = PLUGIN_ID + ".compiler.debug.sourceFile"/*nonNLS*/;
- // possible values are GENERATE or DO_NOT_GENERATE (default is GENERATE)
-
- public static final String COMPILER_CODEGEN_UNUSED_LOCAL = PLUGIN_ID + ".compiler.codegen.unusedLocal"/*nonNLS*/;
- // possible values are PRESERVE or OPTIMIZE_OUT (default is OPTIMIZE_OUT)
-
- public static final String COMPILER_CODEGEN_TARGET_PLATFORM = PLUGIN_ID + ".compiler.codegen.targetPlatform"/*nonNLS*/;
- // possible values are VERSION_1_1 or VERSION_1_2 (default is VERSION_1_1)
-
- public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + ".compiler.problem.unreachableCode"/*nonNLS*/;
- // possible values are ERROR or WARNING (default is ERROR)
-
- public static final String COMPILER_PB_INVALID_IMPORT = PLUGIN_ID + ".compiler.problem.invalidImport"/*nonNLS*/;
- // possible values are ERROR or WARNING (default is ERROR)
- public static final String COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD = PLUGIN_ID + ".compiler.problem.overridingPackageDefaultMethod"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = PLUGIN_ID + ".compiler.problem.methodWithConstructorName"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_DEPRECATION = PLUGIN_ID + ".compiler.problem.deprecation"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_HIDDEN_CATCH_BLOCK = PLUGIN_ID + ".compiler.problem.hiddenCatchBlock"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_UNUSED_LOCAL = PLUGIN_ID + ".compiler.problem.unusedLocal"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_UNUSED_PARAMETER = PLUGIN_ID + ".compiler.problem.unusedParameter"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is WARNING)
+ // File containing default settings for configurable options
+ private static final String JAVA_CORE_INIT = "JavaCore.ini"/*nonNLS*/;
+
+ /**
+ * Compiler options
+ */
+ public static final String OPTION_LocalVariableAttribute = CompilerOptions.OPTION_LocalVariableAttribute;
+ public static final String OPTION_LineNumberAttribute = CompilerOptions.OPTION_LineNumberAttribute;
+ public static final String OPTION_SourceFileAttribute = CompilerOptions.OPTION_SourceFileAttribute;
+ public static final String OPTION_PreserveUnusedLocal = CompilerOptions.OPTION_PreserveUnusedLocal;
+ public static final String OPTION_ReportUnreachableCode = CompilerOptions.OPTION_ReportUnreachableCode;
+ public static final String OPTION_ReportInvalidImport = CompilerOptions.OPTION_ReportInvalidImport;
+ public static final String OPTION_ReportMethodWithConstructorName = CompilerOptions.OPTION_ReportMethodWithConstructorName;
+ public static final String OPTION_ReportOverridingPackageDefaultMethod = CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod;
+ public static final String OPTION_ReportDeprecation = CompilerOptions.OPTION_ReportDeprecation;
+ public static final String OPTION_ReportHiddenCatchBlock = CompilerOptions.OPTION_ReportHiddenCatchBlock;
+ public static final String OPTION_ReportUnusedLocal = CompilerOptions.OPTION_ReportUnusedLocal;
+ public static final String OPTION_ReportUnusedParameter = CompilerOptions.OPTION_ReportUnusedParameter;
+ public static final String OPTION_TargetPlatform = CompilerOptions.OPTION_TargetPlatform;
+ public static final String OPTION_ReportSyntheticAccessEmulation = CompilerOptions.OPTION_ReportSyntheticAccessEmulation;
+ public static final String OPTION_ReportNonExternalizedStringLiteral = CompilerOptions.OPTION_ReportNonExternalizedStringLiteral;
+ public static final String OPTION_Source = CompilerOptions.OPTION_Source;
+ public static final String OPTION_ReportAssertIdentifier = CompilerOptions.OPTION_ReportAssertIdentifier;
- public static final String COMPILER_PB_SYNTHETIC_ACCESS_EMULATION = PLUGIN_ID + ".compiler.problem.syntheticAccessEmulation"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is IGNORE)
+ /**
+ * Code Formatter options
+ */
+ public static final String OPTION_InsertNewlineBeforeOpeningBrace = FormatterOptions.OPTION_InsertNewlineBeforeOpeningBrace;
+ public static final String OPTION_InsertNewlineInControlStatement = FormatterOptions.OPTION_InsertNewlineInControlStatement;
+ public static final String OPTION_InsertNewLineBetweenElseAndIf = FormatterOptions.OPTION_InsertNewLineBetweenElseAndIf;
+ public static final String OPTION_InsertNewLineInEmptyBlock = FormatterOptions.OPTION_InsertNewLineInEmptyBlock;
+ public static final String OPTION_ClearAllBlankLines = FormatterOptions.OPTION_ClearAllBlankLines;
+ public static final String OPTION_SplitLineExceedingLength = FormatterOptions.OPTION_SplitLineExceedingLength;
+ public static final String OPTION_CompactAssignment = FormatterOptions.OPTION_CompactAssignment;
+ public static final String OPTION_TabulationChar = FormatterOptions.OPTION_TabulationChar;
+ public static final String OPTION_TabulationSize = FormatterOptions.OPTION_TabulationSize;
- public static final String CORE_JAVA_BUILD_ORDER = PLUGIN_ID + ".computeJavaBuildOrder"/*nonNLS*/;
- // possible values are COMPUTE or IGNORE (default is COMPUTE)
-
- public static final String COMPILER_PB_NON_EXTERNALIZED_STRING_LITERAL = PLUGIN_ID + ".compiler.problem.nonExternalizedStringLiteral"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is IGNORE)
-
- public static final String COMPILER_COMPILATION_SOURCE = PLUGIN_ID + ".compiler.compilation.source"/*nonNLS*/;
- // possible values are VERSION_1_3 or VERSION_1_4 (default is VERSION_1_3)
-
- public static final String COMPILER_PB_ASSERT_IDENTIFIER = PLUGIN_ID + ".compiler.problem.assertIdentifier"/*nonNLS*/;
- // possible values are WARNING or IGNORE (default is IGNORE)
-
- /**
- * Possible values for configurable options
- */
- public static final String GENERATE = "generate"/*nonNLS*/;
- public static final String DO_NOT_GENERATE = "do not generate"/*nonNLS*/;
- public static final String PRESERVE = "preserve"/*nonNLS*/;
- public static final String OPTIMIZE_OUT = "optimize out"/*nonNLS*/;
- public static final String VERSION_1_1 = "1.1"/*nonNLS*/;
- public static final String VERSION_1_2 = "1.2"/*nonNLS*/;
- public static final String VERSION_1_3 = "1.3"/*nonNLS*/;
- public static final String VERSION_1_4 = "1.4"/*nonNLS*/;
- public static final String ERROR = "error"/*nonNLS*/;
- public static final String WARNING = "warning"/*nonNLS*/;
- public static final String IGNORE = "ignore"/*nonNLS*/;
- public static final String COMPUTE = "compute"/*nonNLS*/;
+ /**
+ * JavaCore options
+ */
+ public static final String OPTION_ComputeBuildOrder = "org.eclipse.jdt.core.JavaCore.computeJavaBuildOrder"/*nonNLS*/;
- private static Hashtable ConfigurableOptions;
- private static Hashtable Variables = new Hashtable(5);
-
- private static Hashtable DefaultOptions;
- private final static String PropertiesBundleName = "org.eclipse.jdt.core.JavaCore"/*nonNLS*/;
-/**
- * Creates the Java core plug-in.
- */
-public JavaCore(IPluginDescriptor pluginDescriptor) {
- super(pluginDescriptor);
- JAVA_CORE_PLUGIN = this;
-}
-/**
- * Adds the given listener for changes to Java elements.
- * Has no effect if an identical listener is already registered.
- *
- * @param listener the listener
- */
-public static void addElementChangedListener(IElementChangedListener listener) {
- JavaModelManager.getJavaModelManager().addElementChangedListener(listener);
-}
-/**
- * Configures the given marker attribute map for the given Java element.
- * Used for markers which denote a Java element rather than a resource.
- *
- * @param attributes the mutable marker attribute map (key type: <code>String</code>,
- * value type: <code>String</code>)
- * @param element the Java element for which the marker needs to be configured
- */
-public static void addJavaElementMarkerAttributes(Map attributes, IJavaElement element) {
- if (element instanceof IMember)
- element= ((IMember) element).getClassFile();
- if (attributes != null && element != null)
- attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
-}
-/**
- * Configures the given marker for the given Java element.
- * Used for markers which denote a Java element rather than a resource.
- *
- * @param marker the marker to be configured
- * @param element the Java element for which the marker needs to be configured
- * @exception CoreException if the <code>IMarker.setAttribute</code> on the marker fails
- */
-public void configureJavaElementMarker(IMarker marker, IJavaElement element) throws CoreException {
- if (element instanceof IMember)
- element= ((IMember)element).getClassFile();
- if (marker != null && element != null)
- marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
-}
-/**
- * Returns the Java model element corresponding to the given handle identifier
- * generated by <code>IJavaElement.getHandleIdentifier()</code>, or
- * <code>null</code> if unable to create the associated element.
- */
-public static IJavaElement create(String handleIdentifier) {
- if (handleIdentifier == null) {
- return null;
+ /**
+ * Code Assist options
+ */
+
+ /**
+ * Creates the Java core plug-in.
+ */
+ public JavaCore(IPluginDescriptor pluginDescriptor) {
+ super(pluginDescriptor);
+ JAVA_CORE_PLUGIN = this;
}
- try {
- return JavaModelManager.getJavaModelManager().getHandleFromMemento(handleIdentifier);
- } catch (JavaModelException e) {
- return null;
+
+ /**
+ * Adds the given listener for changes to Java elements.
+ * Has no effect if an identical listener is already registered.
+ *
+ * @param listener the listener
+ */
+ public static void addElementChangedListener(IElementChangedListener listener) {
+ JavaModelManager.getJavaModelManager().addElementChangedListener(listener);
}
-}
-/**
- * Returns the Java element corresponding to the given file, or
- * <code>null</code> if unable to associate the given file
- * with a Java element.
- *
- * <p>The file must be one of:<ul>
- * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * </ul>
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
-public static IJavaElement create(IFile file) {
- if (file == null) {
- return null;
+
+ /**
+ * Configures the given marker attribute map for the given Java element.
+ * Used for markers which denote a Java element rather than a resource.
+ *
+ * @param attributes the mutable marker attribute map (key type: <code>String</code>,
+ * value type: <code>String</code>)
+ * @param element the Java element for which the marker needs to be configured
+ */
+ public static void addJavaElementMarkerAttributes(
+ Map attributes,
+ IJavaElement element) {
+ if (element instanceof IMember)
+ element = ((IMember) element).getClassFile();
+ if (attributes != null && element != null)
+ attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
}
- String extension= file.getProjectRelativePath().getFileExtension();
- if (extension != null) {
- extension= extension.toLowerCase();
- if (extension.equals("java"/*nonNLS*/)) {
- return createCompilationUnitFrom(file);
- } else if (extension.equals("class"/*nonNLS*/)) {
- return createClassFileFrom(file);
- } else if (extension.equals("jar"/*nonNLS*/) || extension.equals("zip"/*nonNLS*/)) {
- return createJarPackageFragmentRootFrom(file);
- }
- }
- return null;
-}
-/**
- * Returns the package fragment or package fragment root corresponding to the given folder, or
- * <code>null</code> if unable to associate the given folder with a Java element.
- * <p>
- * Note that a package fragment root is returned rather than a default package.
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
-public static IJavaElement create(IFolder folder) {
- if (folder == null) {
- return null;
+ /**
+ * Configures the given marker for the given Java element.
+ * Used for markers which denote a Java element rather than a resource.
+ *
+ * @param marker the marker to be configured
+ * @param element the Java element for which the marker needs to be configured
+ * @exception CoreException if the <code>IMarker.setAttribute</code> on the marker fails
+ */
+ public void configureJavaElementMarker(IMarker marker, IJavaElement element)
+ throws CoreException {
+ if (element instanceof IMember)
+ element = ((IMember) element).getClassFile();
+ if (marker != null && element != null)
+ marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
}
- if (folder.getName().indexOf('.') < 0) {
- JavaProject project = (JavaProject) create(folder.getProject());
- if (project == null) return null;
- IJavaElement element = determineIfOnClasspath(folder, project);
+ /**
+ * Returns the Java model element corresponding to the given handle identifier
+ * generated by <code>IJavaElement.getHandleIdentifier()</code>, or
+ * <code>null</code> if unable to create the associated element.
+ */
+ public static IJavaElement create(String handleIdentifier) {
+ if (handleIdentifier == null) {
+ return null;
+ }
try {
- IPath outputLocation = project.getOutputLocation();
- if (outputLocation == null) return null;
- if (outputLocation.isPrefixOf(folder.getFullPath())) {
- if (project.getClasspathEntryFor(outputLocation) != null) {
- // if the output location is the same as an input location, return the element
- return element;
- } else {
- // otherwise, do not create elements for folders in the output location
- return null;
- }
- } else {
- return element;
- }
+ return JavaModelManager.getJavaModelManager().getHandleFromMemento(
+ handleIdentifier);
} catch (JavaModelException e) {
return null;
}
}
- return null;
-}
-/**
- * Returns the Java project corresponding to the given project, or
- * <code>null</code> if unable to associate the given project
- * with a Java project.
- * <p>
- * Creating a Java Project has the side effect of creating and opening all of the
- * project's parents if they are not yet open.
- */
-public static IJavaProject create(IProject project) {
- if (project == null) {
+ /**
+ * Returns the Java element corresponding to the given file, or
+ * <code>null</code> if unable to associate the given file
+ * with a Java element.
+ *
+ * <p>The file must be one of:<ul>
+ * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
+ * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
+ * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
+ * </ul>
+ * <p>
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ */
+ public static IJavaElement create(IFile file) {
+ if (file == null) {
+ return null;
+ }
+ String extension = file.getProjectRelativePath().getFileExtension();
+ if (extension != null) {
+ extension = extension.toLowerCase();
+ if (extension.equals("java" /*nonNLS*/
+ )) {
+ return createCompilationUnitFrom(file);
+ } else if (extension.equals("class" /*nonNLS*/
+ )) {
+ return createClassFileFrom(file);
+ } else if (extension.equals("jar" /*nonNLS*/
+ ) || extension.equals("zip" /*nonNLS*/
+ )) {
+ return createJarPackageFragmentRootFrom(file);
+ }
+ }
return null;
}
- JavaModel javaModel= JavaModelManager.getJavaModel(project.getWorkspace());
- return javaModel.getJavaProject(project);
-}
-/**
- * Returns the Java element corresponding to the given resource, or
- * <code>null</code> if unable to associate the given resource
- * with a Java element.
- * <p>
- * The resource must be one of:<ul>
- * <li>a project - the element returned is the corresponding <code>IJavaProject</code></li>
- * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
- * or <code>IPackageFragment</code></li>
- * <li>the workspace root resource - the element returned is the <code>IJavaModel</code></li>
- * </ul>
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
-public static IJavaElement create(IResource resource) {
- if (resource == null) {
+ /**
+ * Returns the package fragment or package fragment root corresponding to the given folder, or
+ * <code>null</code> if unable to associate the given folder with a Java element.
+ * <p>
+ * Note that a package fragment root is returned rather than a default package.
+ * <p>
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ */
+ public static IJavaElement create(IFolder folder) {
+ if (folder == null) {
+ return null;
+ }
+ if (folder.getName().indexOf('.') < 0) {
+ JavaProject project = (JavaProject) create(folder.getProject());
+ if (project == null)
+ return null;
+ IJavaElement element = determineIfOnClasspath(folder, project);
+ try {
+ IPath outputLocation = project.getOutputLocation();
+ if (outputLocation == null)
+ return null;
+ if (outputLocation.isPrefixOf(folder.getFullPath())) {
+ if (project.getClasspathEntryFor(outputLocation) != null) {
+ // if the output location is the same as an input location, return the element
+ return element;
+ } else {
+ // otherwise, do not create elements for folders in the output location
+ return null;
+ }
+ } else {
+ return element;
+ }
+ } catch (JavaModelException e) {
+ return null;
+ }
+ }
return null;
}
- int type= resource.getType();
- switch (type) {
- case IResource.PROJECT:
- return create((IProject)resource);
- case IResource.FILE:
- return create((IFile)resource);
- case IResource.FOLDER:
- return create((IFolder)resource);
- case IResource.ROOT:
- return create((IWorkspaceRoot)resource);
- default:
+ /**
+ * Returns the Java project corresponding to the given project, or
+ * <code>null</code> if unable to associate the given project
+ * with a Java project.
+ * <p>
+ * Creating a Java Project has the side effect of creating and opening all of the
+ * project's parents if they are not yet open.
+ */
+ public static IJavaProject create(IProject project) {
+ if (project == null) {
return null;
+ }
+ JavaModel javaModel = JavaModelManager.getJavaModel(project.getWorkspace());
+ return javaModel.getJavaProject(project);
}
-}
-/**
- * Returns the Java model.
- */
-public static IJavaModel create(IWorkspaceRoot root) {
- if (root == null) {
- return null;
+ /**
+ * Returns the Java element corresponding to the given resource, or
+ * <code>null</code> if unable to associate the given resource
+ * with a Java element.
+ * <p>
+ * The resource must be one of:<ul>
+ * <li>a project - the element returned is the corresponding <code>IJavaProject</code></li>
+ * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
+ * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
+ * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
+ * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
+ * or <code>IPackageFragment</code></li>
+ * <li>the workspace root resource - the element returned is the <code>IJavaModel</code></li>
+ * </ul>
+ * <p>
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ */
+ public static IJavaElement create(IResource resource) {
+ if (resource == null) {
+ return null;
+ }
+ int type = resource.getType();
+ switch (type) {
+ case IResource.PROJECT :
+ return create((IProject) resource);
+ case IResource.FILE :
+ return create((IFile) resource);
+ case IResource.FOLDER :
+ return create((IFolder) resource);
+ case IResource.ROOT :
+ return create((IWorkspaceRoot) resource);
+ default :
+ return null;
+ }
}
- return JavaModelManager.getJavaModel(root.getWorkspace());
-}
-/**
- * Creates and returns a class file element for
- * the given <code>.class</code> file. Returns <code>null</code> if unable
- * to recognize the class file.
- */
-public static IClassFile createClassFileFrom(IFile file) {
- IJavaProject project = (IJavaProject) create(file.getProject());
- IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
- if (pkg == null) {
- // fix for 1FVS7WE
- // not on classpath - make the root its folder, and a default package
- IPackageFragmentRoot root= project.getPackageFragmentRoot(file.getParent());
- pkg= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- }
- return pkg.getClassFile(file.getName());
-}
-/**
- * Creates and returns a compilation unit element for
- * the given <code>.java</code> file. Returns <code>null</code> if unable
- * to recognize the compilation unit.
- */
-public static ICompilationUnit createCompilationUnitFrom(IFile file) {
- IProject fileProject = file.getProject();
- IJavaProject project = (IJavaProject) create(fileProject);
- IPackageFragment pkg= (IPackageFragment)determineIfOnClasspath(file, project);
- if (pkg == null) {
- // fix for 1FVS7WE
- // not on classpath - make the root its folder, and a default package
- IPackageFragmentRoot root= project.getPackageFragmentRoot(file.getParent());
- pkg= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- }
- return pkg.getCompilationUnit(file.getName());
-}
-/**
- * Creates and returns a handle for the given JAR file.
- * The Java model associated with the JAR's project may be
- * created as a side effect.
- * Returns <code>null</code> if unable to create a JAR package fragment root.
- * (for example, if the JAR file represents a non-Java resource)
- */
-public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
- IJavaProject project= (IJavaProject)create(file.getProject());
-
- // Create a jar package fragment root only if on the classpath
- IPath resourcePath = file.getFullPath();
- try {
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- IPath rootPath = entry.getPath();
- if (rootPath.equals(resourcePath)) {
- return project.getPackageFragmentRoot(file);
+ /**
+ * Returns the Java model.
+ */
+ public static IJavaModel create(IWorkspaceRoot root) {
+ if (root == null) {
+ return null;
+ }
+ return JavaModelManager.getJavaModel(root.getWorkspace());
+ }
+ /**
+ * Creates and returns a class file element for
+ * the given <code>.class</code> file. Returns <code>null</code> if unable
+ * to recognize the class file.
+ */
+ public static IClassFile createClassFileFrom(IFile file) {
+ IJavaProject project = (IJavaProject) create(file.getProject());
+ IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
+ if (pkg == null) {
+ // fix for 1FVS7WE
+ // not on classpath - make the root its folder, and a default package
+ IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
+ pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ }
+ return pkg.getClassFile(file.getName());
+ }
+ /**
+ * Creates and returns a compilation unit element for
+ * the given <code>.java</code> file. Returns <code>null</code> if unable
+ * to recognize the compilation unit.
+ */
+ public static ICompilationUnit createCompilationUnitFrom(IFile file) {
+ IProject fileProject = file.getProject();
+ IJavaProject project = (IJavaProject) create(fileProject);
+ IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
+ if (pkg == null) {
+ // fix for 1FVS7WE
+ // not on classpath - make the root its folder, and a default package
+ IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
+ pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ }
+ return pkg.getCompilationUnit(file.getName());
+ }
+ /**
+ * Creates and returns a handle for the given JAR file.
+ * The Java model associated with the JAR's project may be
+ * created as a side effect.
+ * Returns <code>null</code> if unable to create a JAR package fragment root.
+ * (for example, if the JAR file represents a non-Java resource)
+ */
+ public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
+ IJavaProject project = (IJavaProject) create(file.getProject());
+
+ // Create a jar package fragment root only if on the classpath
+ IPath resourcePath = file.getFullPath();
+ try {
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ IPath rootPath = entry.getPath();
+ if (rootPath.equals(resourcePath)) {
+ return project.getPackageFragmentRoot(file);
+ }
}
+ } catch (JavaModelException e) {
}
- } catch (JavaModelException e) {
+ return null;
}
- return null;
-}
-/**
- * Returns the package fragment root represented by the resource, or
- * the package fragment the given resource is located in, or <code>null</code>
- * if the given resource is not on the classpath of the given project.
- */
-private static IJavaElement determineIfOnClasspath(IResource resource, IJavaProject project) {
- IPath resourcePath = resource.getFullPath();
- try {
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- IPath rootPath = entry.getPath();
- if (rootPath.equals(resourcePath)) {
- return project.getPackageFragmentRoot(resource);
- } else
- if (rootPath.isPrefixOf(resourcePath)) {
- IPackageFragmentRoot root = ((JavaProject)project).getPackageFragmentRoot(rootPath);
+ /**
+ * Returns the package fragment root represented by the resource, or
+ * the package fragment the given resource is located in, or <code>null</code>
+ * if the given resource is not on the classpath of the given project.
+ */
+ private static IJavaElement determineIfOnClasspath(
+ IResource resource,
+ IJavaProject project) {
+ IPath resourcePath = resource.getFullPath();
+ try {
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ for (int i = 0; i < entries.length; i++) {
+ IClasspathEntry entry = entries[i];
+ IPath rootPath = entry.getPath();
+ if (rootPath.equals(resourcePath)) {
+ return project.getPackageFragmentRoot(resource);
+ } else if (rootPath.isPrefixOf(resourcePath)) {
+ IPackageFragmentRoot root =
+ ((JavaProject) project).getPackageFragmentRoot(rootPath);
IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
if (resource.getType() == IResource.FILE) {
// if the resource is a file, then remove the last segment which
// is the file name in the package
- pkgPath= pkgPath.removeLastSegments(1);
+ pkgPath = pkgPath.removeLastSegments(1);
}
StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) {
@@ -428,589 +421,932 @@ private static IJavaElement determineIfOnClasspath(IResource resource, IJavaProj
}
pkgName.append(segment);
if (j < pkgPath.segmentCount() - 1) {
- pkgName.append("."/*nonNLS*/);
+ pkgName.append("." /*nonNLS*/);
}
}
return root.getPackageFragment(pkgName.toString());
}
+ }
+ } catch (JavaModelException npe) {
+ return null;
}
- } catch (JavaModelException npe) {
return null;
}
- return null;
-}
-/**
- * Returns the path held in the given classpath variable.
- * Returns <node>null</code> if unable to bind.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @return the path, or <code>null</code> if none
- * @see #setClasspathVariable
- */
-public static IPath getClasspathVariable(String variableName) {
- return (IPath)Variables.get(variableName);
-}
-/**
- * Returns the names of all known classpath variables.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @return the list of classpath variable names
- * @see #setClasspathVariable
- */
-public static String[] getClasspathVariableNames() {
- int length = Variables.size();
- String[] result = new String[length];
- Enumeration vars = Variables.keys();
- int index = 0;
- while (vars.hasMoreElements()){
- result[index++] = (String)vars.nextElement();
- }
- return result;
-}
-/**
- * Answers a set of configurable options with their default values.
- * These options allow to configure the behavior of the underlying components.
- */
-public static Hashtable getDefaultOptions(){
- if (DefaultOptions == null) {
- DefaultOptions = new Hashtable(10);
-
- try{
- ResourceBundle bundle =
- ResourceBundle.getBundle(PropertiesBundleName,Locale.getDefault());
-
- Enumeration enum = bundle.getKeys();
- while(enum.hasMoreElements()){
- String id = (String)enum.nextElement();
- DefaultOptions.put(id,bundle.getString(id));
- }
- } catch(Exception ex){}
+ /**
+ * Returns the path held in the given classpath variable.
+ * Returns <node>null</code> if unable to bind.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @return the path, or <code>null</code> if none
+ * @see #setClasspathVariable
+ */
+ public static IPath getClasspathVariable(String variableName) {
+ return (IPath) Variables.get(variableName);
+ }
+ /**
+ * Returns the names of all known classpath variables.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @return the list of classpath variable names
+ * @see #setClasspathVariable
+ */
+ public static String[] getClasspathVariableNames() {
+ int length = Variables.size();
+ String[] result = new String[length];
+ Enumeration vars = Variables.keys();
+ int index = 0;
+ while (vars.hasMoreElements()) {
+ result[index++] = (String) vars.nextElement();
+ }
+ return result;
}
- return (Hashtable)DefaultOptions.clone();
-
-
-}
-
-private static IPath getInstallLocation() {
- return new Path(getPlugin().getDescriptor().getInstallURL().getFile());
-}
+ private static IPath getInstallLocation() {
+ return new Path(getPlugin().getDescriptor().getInstallURL().getFile());
+ }
-/**
- * Returns the single instance of the Java core plug-in runtime class.
- * Equivalent to <code>(JavaCore) getPlugin()</code>.
- */
-public static JavaCore getJavaCore() {
- return (JavaCore) getPlugin();
-}
-/**
- * Returns the <code>IJavaProject</code> associated with the
- * given <code>IProject</code>, or <code>null</code> if the
- * project does not have a Java nature.
- */
-private IJavaProject getJavaProject(IProject project) {
- try {
- if (project.hasNature(NATURE_ID)) {
- JavaModel model= JavaModelManager.getJavaModel(project.getWorkspace());
- if (model != null) {
- return model.getJavaProject(project);
+ /**
+ * Returns the single instance of the Java core plug-in runtime class.
+ * Equivalent to <code>(JavaCore) getPlugin()</code>.
+ */
+ public static JavaCore getJavaCore() {
+ return (JavaCore) getPlugin();
+ }
+ /**
+ * Returns the <code>IJavaProject</code> associated with the
+ * given <code>IProject</code>, or <code>null</code> if the
+ * project does not have a Java nature.
+ */
+ private IJavaProject getJavaProject(IProject project) {
+ try {
+ if (project.hasNature(NATURE_ID)) {
+ JavaModel model = JavaModelManager.getJavaModel(project.getWorkspace());
+ if (model != null) {
+ return model.getJavaProject(project);
+ }
}
+ } catch (CoreException e) {
}
- } catch (CoreException e) {
+ return null;
+ }
+
+ /**
+ * Returns the single instance of the Java core plug-in runtime class.
+ */
+ public static Plugin getPlugin() {
+ return JAVA_CORE_PLUGIN;
}
- return null;
-}
-/**
- * Answers a copy of the current set of configurable options supported by the Java core.
- * These options allow to configure the behavior of the underlying components.
- *
- * Changes on the set of options are not committed until invoking <code>JavaCore.setOptions</code>
- *
- * For a list of recognized options, refer to <code>JavaCore.getDefaultOptions</code>
- */
-public static Hashtable getOptions(){
- if (ConfigurableOptions == null) return ConfigurableOptions = getDefaultOptions();
- return (Hashtable)ConfigurableOptions.clone();
-}
-/**
- * Returns the single instance of the Java core plug-in runtime class.
- */
-public static Plugin getPlugin() {
- return JAVA_CORE_PLUGIN;
-}
-/**
- * This is a helper method which returns the resolved classpath entry denoted
- * by a given entry (if it is a variable entry). It is obtained by resolving the variable
- * reference in the first segment. Returns <node>null</code> if unable to resolve using
- * the following algorithm:
- * <ul>
- * <li> if variable segment cannot be resolved, returns <code>null</code></li>
- * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
- * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
- * <li> if none returns <code>null</code></li>
- * </ul>
- * <p>
- * Variable source attachment path and root path are also resolved and recorded in the resulting classpath entry.
- * <p>
- * @return the resolved library or project classpath entry, or <code>null</code>
- * if the given variable entry could not be resolved to a valid classpath entry
- */
-public static IClasspathEntry getResolvedClasspathEntry(IClasspathEntry entry) {
-
- if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE) return entry;
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath resolvedPath = JavaCore.getResolvedVariablePath(entry.getPath());
- if (resolvedPath == null) return null;
-
- Object target = JavaModel.getTarget(workspaceRoot, resolvedPath, false);
- if (target == null) return null;
-
- // inside the workspace
- if (target instanceof IResource){
- IResource resolvedResource = (IResource) target;
- if (resolvedResource != null){
- switch(resolvedResource.getType()){
- case IResource.PROJECT :
- return JavaCore.newProjectEntry(resolvedPath); // internal project
- case IResource.FILE :
- String extension = resolvedResource.getFileExtension();
- if ("jar"/*nonNLS*/.equalsIgnoreCase(extension) || "zip"/*nonNLS*/.equalsIgnoreCase(extension)){ // internal binary archive
- return JavaCore.newLibraryEntry(
+ /**
+ * This is a helper method which returns the resolved classpath entry denoted
+ * by a given entry (if it is a variable entry). It is obtained by resolving the variable
+ * reference in the first segment. Returns <node>null</code> if unable to resolve using
+ * the following algorithm:
+ * <ul>
+ * <li> if variable segment cannot be resolved, returns <code>null</code></li>
+ * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
+ * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
+ * <li> if none returns <code>null</code></li>
+ * </ul>
+ * <p>
+ * Variable source attachment path and root path are also resolved and recorded in the resulting classpath entry.
+ * <p>
+ * @return the resolved library or project classpath entry, or <code>null</code>
+ * if the given variable entry could not be resolved to a valid classpath entry
+ */
+ public static IClasspathEntry getResolvedClasspathEntry(IClasspathEntry entry) {
+
+ if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE)
+ return entry;
+
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IPath resolvedPath = JavaCore.getResolvedVariablePath(entry.getPath());
+ if (resolvedPath == null)
+ return null;
+
+ Object target = JavaModel.getTarget(workspaceRoot, resolvedPath, false);
+ if (target == null)
+ return null;
+
+ // inside the workspace
+ if (target instanceof IResource) {
+ IResource resolvedResource = (IResource) target;
+ if (resolvedResource != null) {
+ switch (resolvedResource.getType()) {
+ case IResource.PROJECT :
+ return JavaCore.newProjectEntry(resolvedPath); // internal project
+ case IResource.FILE :
+ String extension = resolvedResource.getFileExtension();
+ if ("jar" /*nonNLS*/
+ .equalsIgnoreCase(extension) || "zip" /*nonNLS*/
+ .equalsIgnoreCase(extension)) { // internal binary archive
+ return JavaCore.newLibraryEntry(
resolvedPath,
getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
- }
- break;
- case IResource.FOLDER : // internal binary folder
- return JavaCore.newLibraryEntry(
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ }
+ break;
+ case IResource.FOLDER : // internal binary folder
+ return JavaCore.newLibraryEntry(
resolvedPath,
getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ }
}
}
- }
- // outside the workspace
- if (target instanceof File){
- File externalFile = (File) target;
- if (externalFile.isFile()){
- String fileName = externalFile.getName().toLowerCase();
- if (fileName.endsWith(".jar"/*nonNLS*/) || fileName.endsWith(".zip"/*nonNLS*/)){ // external binary archive
- return JavaCore.newLibraryEntry(
+ // outside the workspace
+ if (target instanceof File) {
+ File externalFile = (File) target;
+ if (externalFile.isFile()) {
+ String fileName = externalFile.getName().toLowerCase();
+ if (fileName.endsWith(".jar" /*nonNLS*/
+ ) || fileName.endsWith(".zip" /*nonNLS*/
+ )) { // external binary archive
+ return JavaCore.newLibraryEntry(
resolvedPath,
getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ }
+ } else { // external binary folder
+ return JavaCore.newLibraryEntry(
+ resolvedPath,
+ getResolvedVariablePath(entry.getSourceAttachmentPath()),
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
}
- } else { // external binary folder
- return JavaCore.newLibraryEntry(
- resolvedPath,
- getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
}
+ return null;
}
- return null;
-}
-/**
- * Resolve a variable path (helper method)
- */
-public static IPath getResolvedVariablePath(IPath variablePath) {
- if (variablePath == null) return null;
- int count = variablePath.segmentCount();
- if (count == 0) return null;
+ /**
+ * Resolve a variable path (helper method)
+ */
+ public static IPath getResolvedVariablePath(IPath variablePath) {
- // lookup variable
- String variableName = variablePath.segment(0);
- IPath resolvedPath = JavaCore.getClasspathVariable(variableName);
- if (resolvedPath == null || resolvedPath.isEmpty()) return null;
+ if (variablePath == null)
+ return null;
+ int count = variablePath.segmentCount();
+ if (count == 0)
+ return null;
- // append path suffix
- if (count > 1){
- resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
+ // lookup variable
+ String variableName = variablePath.segment(0);
+ IPath resolvedPath = JavaCore.getClasspathVariable(variableName);
+ if (resolvedPath == null || resolvedPath.isEmpty())
+ return null;
+
+ // append path suffix
+ if (count > 1) {
+ resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
+ }
+ return resolvedPath;
}
- return resolvedPath;
-}
-/**
- * Returns whether the given marker references the given Java element.
- * Used for markers which denote a Java element rather than a resource.
- *
- * @param element the element
- * @param marker the marker
- * @return <code>true</code> if the marker references the element
- * @exception CoreException if the <code>IMarker.getAttribute</code> on the marker fails
- */
- public static boolean isReferencedBy(IJavaElement element, IMarker marker) throws CoreException {
- if (element instanceof IMember)
- element= ((IMember)element).getClassFile();
- return (element != null
- && marker != null
- && element.getHandleIdentifier().equals(marker.getAttribute(ATT_HANDLE_ID)));
-}
-/**
- * Returns whether the given marker delta references the given Java element.
- * Used for markers deltas which denote a Java element rather than a resource.
- *
- * @param element the element
- * @param markerDelta the marker delta
- * @return <code>true</code> if the marker delta references the element
- * @exception CoreException if the <code>IMarkerDelta.getAttribute</code> on the marker delta fails
- */
-public static boolean isReferencedBy(IJavaElement element, IMarkerDelta markerDelta) throws CoreException {
- if (element instanceof IMember) element= ((IMember) element).getClassFile();
- return element != null
- && markerDelta != null
+
+ /**
+ * Returns whether the given marker references the given Java element.
+ * Used for markers which denote a Java element rather than a resource.
+ *
+ * @param element the element
+ * @param marker the marker
+ * @return <code>true</code> if the marker references the element
+ * @exception CoreException if the <code>IMarker.getAttribute</code> on the marker fails
+ */
+ public static boolean isReferencedBy(IJavaElement element, IMarker marker)
+ throws CoreException {
+ if (element instanceof IMember)
+ element = ((IMember) element).getClassFile();
+ return (
+ element != null
+ && marker != null
+ && element.getHandleIdentifier().equals(marker.getAttribute(ATT_HANDLE_ID)));
+ }
+
+ /**
+ * Returns whether the given marker delta references the given Java element.
+ * Used for markers deltas which denote a Java element rather than a resource.
+ *
+ * @param element the element
+ * @param markerDelta the marker delta
+ * @return <code>true</code> if the marker delta references the element
+ * @exception CoreException if the <code>IMarkerDelta.getAttribute</code> on the marker delta fails
+ */
+ public static boolean isReferencedBy(
+ IJavaElement element,
+ IMarkerDelta markerDelta)
+ throws CoreException {
+ if (element instanceof IMember)
+ element = ((IMember) element).getClassFile();
+ return element != null
+ && markerDelta != null
&& element.getHandleIdentifier().equals(markerDelta.getAttribute(ATT_HANDLE_ID));
-}
-/**
- * Creates and returns a new classpath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
- * identified by the given absolute path. This specifies that all package fragments within the root
- * will have children of type <code>IClassFile</code>.
- * <p>
- * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
- * The target JAR or folder can either be defined internally to the workspace (absolute path relative
- * to the workspace root) or externally to the workspace (absolute path in the file system).
- *
- * e.g. Here are some examples of binary path usage<ul>
- * <li><code> "c:/jdk1.2.2/jre/lib/rt.jar" </code> - reference to an external JAR</li>
- * <li><code> "/Project/someLib.jar" </code> - reference to an internal JAR </li>
- * <li><code> "c:/classes/" </code> - reference to an external binary folder</li>
- * </ul>
- * Note that this operation does not attempt to validate or access the
- * resources at the given paths.
- * <p>
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive,
- * or <code>null</code> if none
- * @param sourceAttachmentRootPath the location of the root within the source archive
- * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
- */
-
-public static IClasspathEntry newLibraryEntry(IPath path, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath) {
- Assert.isTrue(path.isAbsolute(), Util.bind("classpath.needAbsolutePath"/*nonNLS*/));
- return new ClasspathEntry(
- IPackageFragmentRoot.K_BINARY,
- IClasspathEntry.CPE_LIBRARY,
+ }
+
+ /**
+ * Creates and returns a new classpath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
+ * identified by the given absolute path. This specifies that all package fragments within the root
+ * will have children of type <code>IClassFile</code>.
+ * <p>
+ * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
+ * The target JAR or folder can either be defined internally to the workspace (absolute path relative
+ * to the workspace root) or externally to the workspace (absolute path in the file system).
+ *
+ * e.g. Here are some examples of binary path usage<ul>
+ * <li><code> "c:/jdk1.2.2/jre/lib/rt.jar" </code> - reference to an external JAR</li>
+ * <li><code> "/Project/someLib.jar" </code> - reference to an internal JAR </li>
+ * <li><code> "c:/classes/" </code> - reference to an external binary folder</li>
+ * </ul>
+ * Note that this operation does not attempt to validate or access the
+ * resources at the given paths.
+ * <p>
+ * @param path the absolute path of the binary archive
+ * @param sourceAttachmentPath the absolute path of the corresponding source archive,
+ * or <code>null</code> if none
+ * @param sourceAttachmentRootPath the location of the root within the source archive
+ * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
+ */
+ public static IClasspathEntry newLibraryEntry(
+ IPath path,
+ IPath sourceAttachmentPath,
+ IPath sourceAttachmentRootPath) {
+ Assert.isTrue(
+ path.isAbsolute(),
+ Util.bind("classpath.needAbsolutePath" /*nonNLS*/));
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_BINARY,
+ IClasspathEntry.CPE_LIBRARY,
JavaProject.canonicalizedPath(path),
sourceAttachmentPath,
sourceAttachmentRootPath);
-}
-/**
- * Creates and returns a new classpath entry of kind <code>CPE_PROJECT</code>
- * for the project identified by the given absolute path.
- * <p>
- * A project entry is used to denote a prerequisite project on a classpath.
- * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
- * contributes all its package fragment roots) or as binaries (when building, it contributes its
- * whole output location).
- * <p>
- * A project reference allows to indirect through another project, independently from its internal layout.
- * <p>
- * The prerequisite project is referred to using an absolute path relative to the workspace root.
- */
-public static IClasspathEntry newProjectEntry(IPath path){
- Assert.isTrue(path.isAbsolute(), Util.bind("classpath.needAbsolutePath"/*nonNLS*/));
- return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, null, null);
-}
-/**
- * Returns a new empty region.
- */
-public static IRegion newRegion() {
- return new Region();
-}
-/**
- * Creates and returns a new classpath entry of kind <code>CPE_SOURCE</code> for the project's source folder
- * identified by the given absolute path. This specifies that all package fragments within the root will
- * have children of type <code>ICompilationUnit</code>.
- * <p>
- * The source folder is referred to using an absolute path relative to the workspace root, e.g. <code>"/Project/src"</code>.
- * <p>
- * A source entry is used to setup the internal source layout of a project, and cannot be used out of the
- * context of the containing project (a source entry "Proj1/src" cannot be used on the classpath of Proj2).
- */
-public static IClasspathEntry newSourceEntry(IPath path){
- Assert.isTrue(path.isAbsolute(), Util.bind("classpath.needAbsolutePath"/*nonNLS*/));
- return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_SOURCE, path, null, null);
-}
-/**
- * Creates and returns a new classpath entry of kind <code>CPE_VARIABLE</code>
- * for the given path. The first segment of the the path is the name of a classpath variable.
- * The trailing segments of the path will be appended to resolved variable path.
- * <p>
- * A variable entry allows to express indirect references on a classpath to other projects or libraries,
- * depending on what the classpath variable is referring.
- * <p>
- * e.g. Here are some examples of variable path usage<ul>
- * <li><"JDTCORE" where variable <code>JDTCORE</code> is
- * bound to "c:/jars/jdtcore.jar". The resoved classpath entry is denoting the library "c:\jars\jdtcore.jar"</li>
- * <li> "JDTCORE" where variable <code>JDTCORE</code> is
- * bound to "/Project_JDTCORE". The resoved classpath entry is denoting the project "/Project_JDTCORE"</li>
- * <li> "PLUGINS/com.example/example.jar" where variable <code>PLUGINS</code>
- * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"</li>
- * </ul>
- * <p>
- * Note that this operation does not attempt to validate classpath variables
- * or access the resources at the given paths.
- * <p>
- * @param variablePath the path of the binary archive; first segment is the
- * name of a classpath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or <code>null</code> if none; if present, the first segment is the
- * name of a classpath variable (not necessarily the same variable
- * as the one that begins <code>variablePath</code>)
- * @param sourceAttachmentRootPath the location of the root within the source archive
- * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
- */
-public static IClasspathEntry newVariableEntry(IPath variablePath, IPath variableSourceAttachmentPath, IPath sourceAttachmentRootPath){
- Assert.isTrue(variablePath != null && variablePath.segmentCount() >= 1, Util.bind("classpath.illegalVariablePath"/*nonNLS*/));
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IClasspathEntry.CPE_VARIABLE,
- variablePath,
- variableSourceAttachmentPath,
- sourceAttachmentRootPath);
-}
-/**
- * Removed the given classpath variable. Does nothing if no value was
- * set for this classpath variable.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @see #setClasspathVariable
- *
- * @deprecated - use version with extra IProgressMonitor
- */
-public static void removeClasspathVariable(String variableName) {
+ }
- removeClasspathVariable(variableName, null);
-}
-/**
- * Removed the given classpath variable. Does nothing if no value was
- * set for this classpath variable.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @param monitor the progress monitor to report progress
- * @see #setClasspathVariable
- */
-public static void removeClasspathVariable(String variableName, IProgressMonitor monitor) {
+ /**
+ * Creates and returns a new classpath entry of kind <code>CPE_PROJECT</code>
+ * for the project identified by the given absolute path.
+ * <p>
+ * A project entry is used to denote a prerequisite project on a classpath.
+ * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
+ * contributes all its package fragment roots) or as binaries (when building, it contributes its
+ * whole output location).
+ * <p>
+ * A project reference allows to indirect through another project, independently from its internal layout.
+ * <p>
+ * The prerequisite project is referred to using an absolute path relative to the workspace root.
+ */
+ public static IClasspathEntry newProjectEntry(IPath path) {
+ Assert.isTrue(
+ path.isAbsolute(),
+ Util.bind("classpath.needAbsolutePath" /*nonNLS*/));
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_PROJECT,
+ path,
+ null,
+ null);
+ }
- try {
- updateVariableValue(variableName, null, monitor);
- } catch(JavaModelException e){
+ /**
+ * Returns a new empty region.
+ */
+ public static IRegion newRegion() {
+ return new Region();
}
-}
-/**
- * Removes the given element changed listener.
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
-public static void removeElementChangedListener(IElementChangedListener listener) {
- JavaModelManager.getJavaModelManager().removeElementChangedListener(listener);
-}
-/**
- * Sets the value of the given classpath variable.
- * The path must have at least one segment.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @param path the path
- * @see #getClasspathVariable
- *
- * @deprecated - use API with IProgressMonitor
- */
-public static void setClasspathVariable(String variableName, IPath path) throws JavaModelException {
- setClasspathVariable(variableName, path, null);
-}
-/**
- * Sets the value of the given classpath variable.
- * The path must have at least one segment.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @param path the path
- * @param monitor a monitor to report progress
- * @see #getClasspathVariable
- */
-public static void setClasspathVariable(String variableName, IPath path, IProgressMonitor monitor) throws JavaModelException {
-
- Assert.isTrue(path != null, Util.bind("classpath.nullVariablePath"/*nonNLS*/));
- updateVariableValue(variableName, path, monitor);
-}
-/* (non-Javadoc)
- * Method declared on IExecutableExtension.
- * Record any necessary initialization data from the plugin.
- */
-public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) throws CoreException {}
-/**
- * Set current set of configurable options supported by the Java core.
- * These options allow to configure the behavior of the underlying components.
- *
- * For a list of recognized options, refer to <code>JavaCore.getDefaultOptions</code>
- */
-public static void setOptions(Hashtable configurableOptions){
- ConfigurableOptions = (Hashtable) configurableOptions.clone();
-}
-/**
- * Shutdown the JavaCore plugin
- * <p>
- * De-registers the JavaModelManager as a resource changed listener and save participant.
- * <p>
- * @see Plugin#shutdown
- */
-public void shutdown() {
+ /**
+ * Creates and returns a new classpath entry of kind <code>CPE_SOURCE</code> for the project's source folder
+ * identified by the given absolute path. This specifies that all package fragments within the root will
+ * have children of type <code>ICompilationUnit</code>.
+ * <p>
+ * The source folder is referred to using an absolute path relative to the workspace root, e.g. <code>"/Project/src"</code>.
+ * <p>
+ * A source entry is used to setup the internal source layout of a project, and cannot be used out of the
+ * context of the containing project (a source entry "Proj1/src" cannot be used on the classpath of Proj2).
+ */
+ public static IClasspathEntry newSourceEntry(IPath path) {
+ Assert.isTrue(
+ path.isAbsolute(),
+ Util.bind("classpath.needAbsolutePath" /*nonNLS*/));
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_SOURCE,
+ path,
+ null,
+ null);
+ }
+
+ /**
+ * Creates and returns a new classpath entry of kind <code>CPE_VARIABLE</code>
+ * for the given path. The first segment of the the path is the name of a classpath variable.
+ * The trailing segments of the path will be appended to resolved variable path.
+ * <p>
+ * A variable entry allows to express indirect references on a classpath to other projects or libraries,
+ * depending on what the classpath variable is referring.
+ * <p>
+ * e.g. Here are some examples of variable path usage<ul>
+ * <li><"JDTCORE" where variable <code>JDTCORE</code> is
+ * bound to "c:/jars/jdtcore.jar". The resoved classpath entry is denoting the library "c:\jars\jdtcore.jar"</li>
+ * <li> "JDTCORE" where variable <code>JDTCORE</code> is
+ * bound to "/Project_JDTCORE". The resoved classpath entry is denoting the project "/Project_JDTCORE"</li>
+ * <li> "PLUGINS/com.example/example.jar" where variable <code>PLUGINS</code>
+ * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"</li>
+ * </ul>
+ * <p>
+ * Note that this operation does not attempt to validate classpath variables
+ * or access the resources at the given paths.
+ * <p>
+ * @param variablePath the path of the binary archive; first segment is the
+ * name of a classpath variable
+ * @param variableSourceAttachmentPath the path of the corresponding source archive,
+ * or <code>null</code> if none; if present, the first segment is the
+ * name of a classpath variable (not necessarily the same variable
+ * as the one that begins <code>variablePath</code>)
+ * @param sourceAttachmentRootPath the location of the root within the source archive
+ * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
+ */
+ public static IClasspathEntry newVariableEntry(
+ IPath variablePath,
+ IPath variableSourceAttachmentPath,
+ IPath sourceAttachmentRootPath) {
+ Assert.isTrue(
+ variablePath != null && variablePath.segmentCount() >= 1,
+ Util.bind("classpath.illegalVariablePath" /*nonNLS*/));
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_VARIABLE,
+ variablePath,
+ variableSourceAttachmentPath,
+ sourceAttachmentRootPath);
+ }
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager());
- workspace.removeSaveParticipant(this);
+ /**
+ * Removed the given classpath variable. Does nothing if no value was
+ * set for this classpath variable.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @see #setClasspathVariable
+ *
+ * @deprecated - use version with extra IProgressMonitor
+ */
+ public static void removeClasspathVariable(String variableName) {
+ removeClasspathVariable(variableName, null);
+ }
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
-}
-/**
- * Initiate the background indexing process.
- * This should be deferred after the plugin activation.
- */
-private void startIndexing() {
-
- JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
- IndexManager indexManager = manager.getIndexManager();
- if (indexManager != null) indexManager.reset();
- /*
- // if there is a desktop defer the start of the indexing by posting a runnable
- if (getDesktopPlugin() != null) {
- IDesktop desktop= getDesktop();
- ApplicationWindow window= (ApplicationWindow) desktop.getActiveDesktopWindow();
- Display display= null;
- if (window != null)
- display= window.getDisplay();
- if (display != null) {
- display.asyncExec(start);
- return;
- }
+ /**
+ * Removed the given classpath variable. Does nothing if no value was
+ * set for this classpath variable.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @param monitor the progress monitor to report progress
+ * @see #setClasspathVariable
+ */
+ public static void removeClasspathVariable(
+ String variableName,
+ IProgressMonitor monitor) {
+
+ try {
+ updateVariableValue(variableName, null, monitor);
+ } catch (JavaModelException e) {
}
- */
-}
-/**
- * Startup of the JavaCore plugin
- * <p>
- * Registers the JavaModelManager as a resource changed listener and save participant.
- * Starts the background indexing, and restore saved classpath variable values.
- * <p>
- * @see Plugin#startup
- */
-public void startup() {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
+ }
+
+ /**
+ * Removes the given element changed listener.
+ * Has no affect if an identical listener is not registered.
+ *
+ * @param listener the listener
+ */
+ public static void removeElementChangedListener(IElementChangedListener listener) {
+ JavaModelManager.getJavaModelManager().removeElementChangedListener(listener);
+ }
+
+ /**
+ * Sets the value of the given classpath variable.
+ * The path must have at least one segment.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @param path the path
+ * @see #getClasspathVariable
+ *
+ * @deprecated - use API with IProgressMonitor
+ */
+ public static void setClasspathVariable(String variableName, IPath path)
+ throws JavaModelException {
+
+ setClasspathVariable(variableName, path, null);
+ }
+
+ /**
+ * Sets the value of the given classpath variable.
+ * The path must have at least one segment.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @param path the path
+ * @param monitor a monitor to report progress
+ * @see #getClasspathVariable
+ */
+ public static void setClasspathVariable(
+ String variableName,
+ IPath path,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ Assert.isTrue(path != null, Util.bind("classpath.nullVariablePath" /*nonNLS*/));
+ updateVariableValue(variableName, path, monitor);
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IExecutableExtension.
+ * Record any necessary initialization data from the plugin.
+ */
+ public void setInitializationData(
+ IConfigurationElement cfig,
+ String propertyName,
+ Object data)
+ throws CoreException {
+ }
+
+ /**
+ * Shutdown the JavaCore plugin
+ * <p>
+ * De-registers the JavaModelManager as a resource changed listener and save participant.
+ * <p>
+ * @see Plugin#shutdown
+ */
+ public void shutdown() {
+
IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager());
+ workspace.removeSaveParticipant(this);
+
+ ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
+ }
+
+ /**
+ * Initiate the background indexing process.
+ * This should be deferred after the plugin activation.
+ */
+ private void startIndexing() {
+
+ JavaModelManager manager =
+ (JavaModelManager) JavaModelManager.getJavaModelManager();
IndexManager indexManager = manager.getIndexManager();
- if (indexManager != null) {
- // need to initialize workbench now since a query may be done before indexing starts
- indexManager.workspace = workspace;
- }
- workspace.addResourceChangeListener(
- manager,
- IResourceChangeEvent.PRE_AUTO_BUILD | IResourceChangeEvent.POST_CHANGE
- | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE);
-
- startIndexing();
-
- workspace.addSaveParticipant(this, manager);
- manager.loadVariables();
- } catch(CoreException e) {
- } catch(RuntimeException e){
- manager.shutdown();
- throw e;
- }
-}
-/**
- * Internal updating of a variable value (null path meaning removal).
- */
-private static void updateVariableValue(String variableName, IPath path, IProgressMonitor monitor) throws JavaModelException {
-
- // gather classpath information for updating
- Hashtable affectedProjects = new Hashtable(5);
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- IJavaModel model = manager.getJavaModel();
- if (model != null){
- IJavaProject[] projects = model.getJavaProjects();
- nextProject: for (int i = 0, max = projects.length; i < max; i++){
- IClasspathEntry[] entries = projects[i].getRawClasspath();
- for (int j = 0, cplength = entries.length; j < cplength; j++){
- IClasspathEntry oldEntry = entries[j];
- if (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
- IPath sourcePath, sourceRootPath;
- if (oldEntry.getPath().segment(0).equals(variableName)
- || ((sourcePath = oldEntry.getSourceAttachmentPath()) != null && sourcePath.segment(0).equals(variableName))
- || ((sourceRootPath = oldEntry.getSourceAttachmentRootPath()) != null && sourceRootPath.segment(0).equals(variableName))) {
- affectedProjects.put(projects[i], projects[i].getResolvedClasspath(true));
- continue nextProject;
+ if (indexManager != null)
+ indexManager.reset();
+ }
+
+ /**
+ * Startup of the JavaCore plugin
+ * <p>
+ * Registers the JavaModelManager as a resource changed listener and save participant.
+ * Starts the background indexing, and restore saved classpath variable values.
+ * <p>
+ * @see Plugin#startup
+ */
+ public void startup() {
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ try {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IndexManager indexManager = manager.getIndexManager();
+ if (indexManager != null) {
+ // need to initialize workbench now since a query may be done before indexing starts
+ indexManager.workspace = workspace;
+ }
+ workspace.addResourceChangeListener(
+ manager,
+ IResourceChangeEvent.PRE_AUTO_BUILD
+ | IResourceChangeEvent.POST_CHANGE
+ | IResourceChangeEvent.PRE_DELETE
+ | IResourceChangeEvent.PRE_CLOSE);
+
+ startIndexing();
+
+ workspace.addSaveParticipant(this, manager);
+ manager.loadVariables();
+ manager.loadOptions();
+ } catch (CoreException e) {
+ } catch (RuntimeException e) {
+ manager.shutdown();
+ throw e;
+ }
+ }
+
+ /**
+ * Internal updating of a variable value (null path meaning removal).
+ */
+ private static void updateVariableValue(
+ String variableName,
+ IPath path,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ // gather classpath information for updating
+ Hashtable affectedProjects = new Hashtable(5);
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ try {
+ IJavaModel model = manager.getJavaModel();
+ if (model != null) {
+ IJavaProject[] projects = model.getJavaProjects();
+ nextProject : for (int i = 0, max = projects.length; i < max; i++) {
+ IClasspathEntry[] entries = projects[i].getRawClasspath();
+ for (int j = 0, cplength = entries.length; j < cplength; j++) {
+ IClasspathEntry oldEntry = entries[j];
+ if (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
+ IPath sourcePath, sourceRootPath;
+ if (oldEntry.getPath().segment(0).equals(variableName)
+ || ((sourcePath = oldEntry.getSourceAttachmentPath()) != null
+ && sourcePath.segment(0).equals(variableName))
+ || ((sourceRootPath = oldEntry.getSourceAttachmentRootPath()) != null
+ && sourceRootPath.segment(0).equals(variableName))) {
+ affectedProjects.put(projects[i], projects[i].getResolvedClasspath(true));
+ continue nextProject;
+ }
}
}
}
}
+ } catch (JavaModelException e) {
+ }
+ if (path == null) {
+ Variables.remove(variableName);
+ } else {
+ // new variable value is assigned
+ Variables.put(variableName, path);
+ }
+ if (!affectedProjects.isEmpty()) {
+ boolean wasFiring = manager.isFiring();
+ try {
+ if (wasFiring)
+ manager.stopDeltas();
+ // propagate classpath change
+ Enumeration projectsToUpdate = affectedProjects.keys();
+ while (projectsToUpdate.hasMoreElements()) {
+ JavaProject project = (JavaProject) projectsToUpdate.nextElement();
+ project
+ .setRawClasspath(
+ project.getRawClasspath(),
+ monitor,
+ project.getWorkspace().isAutoBuilding(),
+ // force build if in auto build mode
+ (IClasspathEntry[]) affectedProjects.get(project));
+ }
+ } finally {
+ manager.mergeDeltas();
+ if (wasFiring) {
+ manager.startDeltas();
+ manager.fire();
+ }
+ }
+ }
+ }
+
+ /**
+ * Set the value of the current setting for an option.
+ *
+ * @return IJavaModelStatusConstants.INVALID_OPTION_VALUE if option value
+ * are not correct and IJavaModelStatusConstants.INVALID_OPTION if option
+ * doesn't exist.
+ */
+ public static IJavaModelStatus setOptionValue(String id, String value) {
+ IJavaModelStatus status = validateOptionValue(id, value);
+ if (status.getCode() == IJavaModelStatus.OK) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+ if (option != null)
+ option.setValue(value);
+ }
+ return status;
+ }
+
+ /**
+ * Answer the value of the current setting for an option.
+ *
+ * @return String
+ */
+ public static String getOptionValue(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getValue();
+
+ return null;
+ }
+
+ /**
+ * Set the value of the default setting for an option.
+ *
+ * @return IJavaModelStatusConstants.INVALID_OPTION_VALUE if option value
+ * are not correct and IJavaModelStatusConstants.INVALID_OPTION if option
+ * doesn't exist.
+ */
+ private static IJavaModelStatus setOptionDefaultValue(
+ String id,
+ String value) {
+ IJavaModelStatus status = validateOptionValue(id, value);
+ if (status.getCode() == IJavaModelStatus.OK) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+ if (option != null)
+ option.setDefaultValue(value);
+ }
+ return status;
+ }
+
+ /**
+ * Answer the value of the default setting for an option.
+ *
+ * @return String
+ */
+ public static String getOptionDefaultValue(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getDefaultValue();
+
+ return null;
+ }
+
+ /**
+ * Return an String that represents the localized description of an option.
+ *
+ * @return java.lang.String
+ */
+ public static String getOptionDescription(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getDescription();
+
+ return null;
+ }
+ /**
+ * Return a String that represents the localized name of an option.
+ * @return java.lang.String
+ */
+ public static String getOptionName(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getName();
+
+ return null;
+ }
+
+ /**
+ * Return a String that identifies the component owner of an option
+ * (typically the qualified type name of the class which it corresponds to).
+ *
+ * e.g. "org.eclipse.jdt.internal.compiler.api.Compiler"
+ *
+ * @return java.lang.String
+ */
+ public static String getOptionComponentName(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getComponentName();
+
+ return null;
+ }
+
+ /**
+ * Return a String that represents the localized category of an option.
+ * @return java.lang.String
+ */
+ public static String getOptionCategory(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getCategory();
+
+ return null;
+ }
+
+ /**
+ * Return an array of String that represents the localized possible values of an option.
+ *
+ * @return java.lang.String[]
+ */
+ public static String[] getOptionPossibleValues(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getPossibleValues();
+
+ return null;
+ }
+
+ /**
+ * Return the type of option. Type is a String with possible value :
+ * <code>discrete</code>,<code>string</code>,<code>int</code> and
+ * <code>float</code>.
+ */
+ public static String getOptionType(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getType();
+
+ return null;
+ }
+
+ /**
+ * Return the maximum value of option if option's type is <code>int</code>
+ * or <code>float</code>.Otherwise return null.
+ */
+ public static Number getOptionMax(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null) {
+ return option.getMax();
+ }
+
+ return null;
+ }
+
+ /**
+ * Return the minimum value of option if option's type is <code>int</code>
+ * or <code>float</code>.Otherwise return null.
+ */
+ public static Number getOptionMin(String id) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null)
+ return option.getMin();
+
+ return null;
+ }
+
+ /**
+ * Answers a set of option'IDs which are in option set of JavaCore
+ */
+ public static String[] getOptionIDs() {
+ return JavaModelManager.getOptionIDs();
+ }
+
+ /**
+ * Answers a set of option'IDs which are in option set of JavaCore
+ * and associated with a component.
+ */
+ public static String[] getOptionIDs(String componentName) {
+ String[] ids = getOptionIDs();
+
+ String[] result = new String[ids.length];
+ int resultCount = 0;
+ for (int i = 0; i < ids.length; i++) {
+ if (ids[i].startsWith(componentName))
+ result[resultCount++] = ids[i];
+ }
+
+ System.arraycopy(result, 0, result = new String[resultCount], 0, resultCount);
+
+ return result;
+ }
+
+ /**
+ * Answers if a value is valide for an option
+ *
+ * @return IJavaModelStatusConstants.INVALID_OPTION_VALUE if option value
+ * are not correct and IJavaModelStatusConstants.INVALID_OPTION if option
+ * doesn't exist.
+ */
+ public static IJavaModelStatus validateOptionValue(String id, String value) {
+ ConfigurableOption option = (ConfigurableOption) getOptions().get(id);
+
+ if (option != null) {
+ String[] values = option.getPossibleValues();
+ if (values == ConfigurableOption.NoDiscreteValue) {
+ try {
+ if (option.getType().equals(ConfigurableOption.INT)) {
+ int max = option.getMax().intValue();
+ int min = option.getMin().intValue();
+ int val = Integer.parseInt(value);
+ if (val > max || val < min)
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_OPTION_VALUE);
+ } else if (option.getType().equals(ConfigurableOption.FLOAT)) {
+ float max = option.getMax().floatValue();
+ float min = option.getMin().floatValue();
+ float val = Float.parseFloat(value);
+ if (val > max || val < min)
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_OPTION_VALUE);
+ }
+ } catch (NumberFormatException e) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_OPTION_VALUE);
+ }
+ return JavaModelStatus.VERIFIED_OK;
+ } else {
+ for (int i = 0; i < values.length; i++) {
+ if (values[i].equals(value))
+ return JavaModelStatus.VERIFIED_OK;
+ }
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_OPTION_VALUE);
+ }
}
- } catch(JavaModelException e){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_OPTION);
}
- if (path == null){
- Variables.remove(variableName);
- } else {
- // new variable value is assigned
- Variables.put(variableName, path);
+ /**
+ * Reset JavaCore option values to defaults.
+ */
+ public static void resetOptions() {
+ Locale locale = Locale.getDefault();
+
+ if (JavaModelManager.fOptions == null) {
+ JavaModelManager.initializeOptions();
+ // Set options to JavaCore default value
+ setJavaCoreDefaultOptionsValue(locale);
+
+ } else {
+ ConfigurableOption[] options =
+ (ConfigurableOption[]) JavaModelManager.fOptions.values().toArray(
+ new ConfigurableOption[0]);
+ for (int i = 0; i < options.length; i++)
+ options[i].setToDefault();
+ }
}
- if (!affectedProjects.isEmpty()){
- boolean wasFiring = manager.isFiring();
+ private static void setJavaCoreDefaultOptionsValue(Locale locale) {
+ BufferedReader reader;
try {
- if (wasFiring) manager.stopDeltas();
- // propagate classpath change
- Enumeration projectsToUpdate = affectedProjects.keys();
- while (projectsToUpdate.hasMoreElements()){
- JavaProject project = (JavaProject)projectsToUpdate.nextElement();
- project.setRawClasspath(
- project.getRawClasspath(),
- monitor,
- project.getWorkspace().isAutoBuilding(), // force build if in auto build mode
- (IClasspathEntry[])affectedProjects.get(project));
+ reader =
+ new BufferedReader(
+ new InputStreamReader(JavaCore.class.getResourceAsStream(JAVA_CORE_INIT)));
+ String line = reader.readLine();
+ while (line != null) {
+ int equalIndex = line.indexOf("=" /*nonNLS*/);
+ if (!line.startsWith("#" /*nonNLS*/
+ ) && equalIndex != -1) {
+ String id = line.substring(0, equalIndex).trim();
+
+ ConfigurableOption option = new ConfigurableOption(id, locale);
+ if (option.getPossibleValues() != ConfigurableOption.NoDiscreteValue) {
+ try {
+ int index = Integer.parseInt(line.substring(equalIndex + 1).trim());
+ option.setDefaultValueIndex(index);
+ } catch (NumberFormatException e) {
+ // value is default default value
+ }
+ } else {
+ String value = line.substring(equalIndex + 1).trim();
+ option.setDefaultValue(value);
+ }
+ JavaModelManager.addOption(option);
+ }
+ line = reader.readLine();
}
+ reader.close();
+ } catch (FileNotFoundException e) {
+ } catch (IOException e) {
} finally {
- manager.mergeDeltas();
- if (wasFiring){
- manager.startDeltas();
- manager.fire();
- }
}
}
-}
-}
+ private static Hashtable getOptions() {
+ if (JavaModelManager.fOptions == null)
+ resetOptions();
+
+ return JavaModelManager.fOptions;
+ }
+
+ /**
+ * Returns all the options of Java Core to be shown by the UI
+ *
+ * @param locale java.util.Locale
+ * @return org.eclipse.jdt.internal.compiler.ConfigurableOption[]
+ */
+ private static ConfigurableOption[] getDefaultOptions(Locale locale) {
+ String[] ids = ConfigurableOption.getIDs(JavaCore.class.getName(), locale);
+
+ ConfigurableOption[] result = new ConfigurableOption[ids.length];
+ for (int i = 0; i < ids.length; i++) {
+ result[i] = new ConfigurableOption(ids[i], locale);
+ }
+ return result;
+ }
+} \ No newline at end of file
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java
index 78301d3f3c..27c55071fd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java
@@ -110,8 +110,7 @@ public class CompilationUnitVisitor extends Compiler {
* Low-level API performing the actual compilation
*/
protected static ConfigurableOption[] getOptions() {
- CompilerOptions options = new CompilerOptions();
- return options.getConfigurableOptions(Locale.getDefault());
+ return JavaModelManager.getOptions();
}
/*
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java
index d7f627709f..50fcf2c74b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java
@@ -39,6 +39,15 @@ import org.eclipse.jdt.internal.core.builder.NotPresentException;
* the static method <code>JavaModelManager.getJavaModelManager()</code>.
*/
public class JavaModelManager implements IResourceChangeListener, ISaveParticipant {
+ /**
+ * JavaCore options (don't use this field to add an new option,
+ * use JavaModelManager#addOption method.
+ */
+ public static Hashtable fOptions;
+ /**
+ * JavaCore options IDs
+ */
+ private static ArrayList fOptionIDs;
/**
* The singleton manager
@@ -168,237 +177,7 @@ public void checkProjectBeingAdded(IResourceDelta delta) {
public void closeAffectedElements(IResourceDelta delta) {
fDeltaProcessor.closeAffectedElements(delta);
}
-/**
- * Convert options Map into ConfigurableOption understood by the infrastructure
- *
- * Should be revisited
- */
-public static ConfigurableOption[] convertConfigurableOptions(Hashtable optionMap) {
-
- Enumeration optionNames = optionMap.keys();
- CompilerOptions compilerOptions = new CompilerOptions();
- int index = 0;
-
- while (optionNames.hasMoreElements()){
-
- String optionName = (String)optionNames.nextElement();
- String optionValue = (String)optionMap.get(optionName);
-
- if (optionName.equals(JavaCore.COMPILER_LOCAL_VARIABLE_ATTR)){
-
- if (optionValue.equals(JavaCore.GENERATE)){
- compilerOptions.produceDebugAttributes(
- compilerOptions.getDebugAttributesMask() | CompilerOptions.Vars);
- continue;
- }
- if (optionValue.equals(JavaCore.DO_NOT_GENERATE)){
- compilerOptions.produceDebugAttributes(
- compilerOptions.getDebugAttributesMask() & ~CompilerOptions.Vars);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_LINE_NUMBER_ATTR)){
-
- if (optionValue.equals(JavaCore.GENERATE)){
- compilerOptions.produceDebugAttributes(
- compilerOptions.getDebugAttributesMask() | CompilerOptions.Lines);
- continue;
- }
- if (optionValue.equals(JavaCore.DO_NOT_GENERATE)){
- compilerOptions.produceDebugAttributes(
- compilerOptions.getDebugAttributesMask() & ~CompilerOptions.Lines);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_SOURCE_FILE_ATTR)){
-
- if (optionValue.equals(JavaCore.GENERATE)){
- compilerOptions.produceDebugAttributes(
- compilerOptions.getDebugAttributesMask() | CompilerOptions.Source);
- continue;
- }
- if (optionValue.equals(JavaCore.DO_NOT_GENERATE)){
- compilerOptions.produceDebugAttributes(
- compilerOptions.getDebugAttributesMask() & ~CompilerOptions.Source);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL)){
-
- if (optionValue.equals(JavaCore.PRESERVE)){
- compilerOptions.preserveAllLocalVariables(true);
- continue;
- }
- if (optionValue.equals(JavaCore.OPTIMIZE_OUT)){
- compilerOptions.preserveAllLocalVariables(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM)){
-
- if (optionValue.equals(JavaCore.VERSION_1_1)){
- compilerOptions.setTargetJDK(CompilerOptions.JDK1_1);
- continue;
- }
- if (optionValue.equals(JavaCore.VERSION_1_2)){
- compilerOptions.setTargetJDK(CompilerOptions.JDK1_2);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_UNREACHABLE_CODE)){
-
- if (optionValue.equals(JavaCore.ERROR)){
- compilerOptions.handleUnreachableCodeAsError(true);
- continue;
- }
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleUnreachableCodeAsError(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_INVALID_IMPORT)){
-
- if (optionValue.equals(JavaCore.ERROR)){
- compilerOptions.handleImportProblemAsError(true);
- continue;
- }
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleImportProblemAsError(false);
- continue;
- }
- continue;
- }
-
- if (optionName.equals(JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleOverriddenPackageDefaultMethodAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleOverriddenPackageDefaultMethodAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleMethodWithConstructorNameAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleMethodWithConstructorNameAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_DEPRECATION)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleDeprecationUseAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleDeprecationUseAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK)){
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleMaskedCatchBlockAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleMaskedCatchBlockAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_UNUSED_LOCAL)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleUnusedLocalVariableAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleUnusedLocalVariableAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_UNUSED_PARAMETER)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleUnusedArgumentAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleUnusedArgumentAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleAccessEmulationAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleAccessEmulationAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_NON_EXTERNALIZED_STRING_LITERAL)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleNonExternalizedStringLiteralAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleNonExternalizedStringLiteralAsWarning(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_COMPILATION_SOURCE)){
-
- if (optionValue.equals(JavaCore.VERSION_1_4)){
- compilerOptions.setAssertMode(true);
- continue;
- }
- if (optionValue.equals(JavaCore.VERSION_1_3)){
- compilerOptions.setAssertMode(false);
- continue;
- }
- continue;
- }
- if (optionName.equals(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER)){
-
- if (optionValue.equals(JavaCore.WARNING)){
- compilerOptions.handleAssertIdentifierAsWarning(true);
- continue;
- }
- if (optionValue.equals(JavaCore.IGNORE)){
- compilerOptions.handleAssertIdentifierAsWarning(false);
- continue;
- }
- continue;
- }
- }
-
- return compilerOptions.getConfigurableOptions(Locale.getDefault());
-}
/**
* Note that the project is now deleted.
*
@@ -720,6 +499,42 @@ public void doneSaving(ISaveContext context){
return writer.toString();
}
+
+ public String getOptionsAsXMLString() throws CoreException {
+
+ Document document = new DocumentImpl();
+ Element rootElement = document.createElement("options"/*nonNLS*/);
+ document.appendChild(rootElement);
+
+ String[] ids = JavaCore.getOptionIDs();
+
+ for (int i= 0; i < ids.length; ++i) {
+ ConfigurableOption option = (ConfigurableOption)fOptions.get(ids[i]);
+
+ Element optionElement= document.createElement("option"/*nonNLS*/);
+ optionElement.setAttribute("id"/*nonNLS*/, ids[i]);
+ if(option.getPossibleValues() == ConfigurableOption.NoDiscreteValue){
+ optionElement.setAttribute("value"/*nonNLS*/, option.getValue());
+ }
+ else{
+ optionElement.setAttribute("index"/*nonNLS*/, String.valueOf(option.getValueIndex()));
+ }
+ rootElement.appendChild(optionElement);
+ }
+
+ // produce a String output
+ StringWriter writer = new StringWriter();
+ try {
+ OutputFormat format = new OutputFormat();
+ format.setIndenting(true);
+ Serializer serializer = SerializerFactory.getSerializerFactory(Method.XML).makeSerializer(writer, format);
+ serializer.asDOMSerializer().serialize(document);
+ } catch (IOException e) {
+ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
+ }
+ return writer.toString();
+
+ }
/**
* Returns the open ZipFile at the given location. If the ZipFile
* does not yet exist, it is created, opened, and added to the cache
@@ -783,6 +598,16 @@ public void doneSaving(ISaveContext context){
return;
}
}
+
+ public void loadOptions() throws CoreException {
+ String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(
+ new QualifiedName(JavaCore.PLUGIN_ID, "options"/*nonNLS*/));
+ try {
+ if (xmlString != null) readOptions(xmlString);
+ } catch(IOException e){
+ return;
+ }
+ }
/**
* Merged all awaiting deltas.
*/
@@ -931,7 +756,54 @@ public void prepareToSave(ISaveContext context) throws CoreException {
}
}
- }
+ }
+
+ public void readOptions(String xmlString) throws IOException {
+ if(fOptions == null)
+ JavaCore.resetOptions();
+
+ StringReader reader = new StringReader(xmlString);
+ Element cpElement;
+ try {
+ DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
+ } catch(SAXException e) {
+ throw new IOException(Util.bind("option.badFormat"/*nonNLS*/));
+ } catch(ParserConfigurationException e){
+ reader.close();
+ throw new IOException(Util.bind("option.badFormat"/*nonNLS*/));
+ } finally {
+ reader.close();
+ }
+ if (!cpElement.getNodeName().equalsIgnoreCase("options"/*nonNLS*/)) {
+ throw new IOException(Util.bind("option.badFormat"/*nonNLS*/));
+ }
+ NodeList list= cpElement.getChildNodes();
+ int length= list.getLength();
+ for (int i= 0; i < length; ++i) {
+ Node node= list.item(i);
+ short type= node.getNodeType();
+ if (type == Node.ELEMENT_NODE) {
+ Element element= (Element) node;
+ if (element.getNodeName().equalsIgnoreCase("option"/*nonNLS*/)) {
+ String id = element.getAttribute("id"/*nonNLS*/);
+ ConfigurableOption option = (ConfigurableOption) fOptions.get(id);
+
+ String[] possible = option.getPossibleValues();
+ if(possible == ConfigurableOption.NoDiscreteValue){
+ String value = element.getAttribute("value"/*nonNLS*/);
+ option.setValue(value);
+ }
+ else {
+ int valueIndex = Integer.parseInt(element.getAttribute("index"/*nonNLS*/));
+ option.setValueIndex(valueIndex);
+ }
+
+ }
+
+ }
+ }
+ }
/**
* Registers the given delta with this manager. This API is to be
* used to registerd deltas that are created explicitly by the Java
@@ -1147,12 +1019,19 @@ public void rollback(ISaveContext context){
new QualifiedName(JavaCore.PLUGIN_ID, "variables"/*nonNLS*/),
getVariablesAsXMLString());
}
+
+ public void saveOptions() throws CoreException {
+ ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(
+ new QualifiedName(JavaCore.PLUGIN_ID, "options"/*nonNLS*/),
+ getOptionsAsXMLString());
+ }
/**
* @see ISaveParticipant
*/
public void saving(ISaveContext context) throws CoreException {
this.saveVariables();
+ this.saveOptions();
if (context.getKind() == ISaveContext.FULL_SAVE){
this.saveBuildState(); // build state
@@ -1165,8 +1044,9 @@ public void saving(ISaveContext context) throws CoreException {
protected void setBuildOrder(String[] javaBuildOrder) throws JavaModelException {
// optional behaviour
- if (!JavaCore.COMPUTE.equals(JavaCore.getOptions().get(JavaCore.CORE_JAVA_BUILD_ORDER))) return;
-
+ // possible value of index 0 is Compute
+ if (!JavaCore.getOptionPossibleValues(JavaCore.OPTION_ComputeBuildOrder)[0].equals(JavaCore.getOptionValue(JavaCore.OPTION_ComputeBuildOrder))) return;
+
if (javaBuildOrder == null || javaBuildOrder.length <= 1) return;
IWorkspace workspace = ResourcesPlugin.getWorkspace();
@@ -1246,4 +1126,37 @@ public void saving(ISaveContext context) throws CoreException {
public void stopDeltas() {
fFire= false;
}
+
+ /**
+ * Answers a copy of the current set of options supported by the Java core.
+ * These options allow to configure the behavior of the underlying components.
+ *
+ * Changes on the set of options are not committed until invoking <code>JavaCore.setOptionValue</code>
+ */
+ public static ConfigurableOption[] getOptions(){
+ if(fOptions == null)
+ JavaCore.resetOptions();
+
+ return (ConfigurableOption[])fOptions.values().toArray(new ConfigurableOption[0]);
+ }
+
+ /**
+ * Answers a set of option'IDs which are in option set of JavaCore
+ */
+ public static String[] getOptionIDs(){
+ if(fOptionIDs == null)
+ return new String[0];
+ return (String [])fOptionIDs.toArray(new String[0]);
+ }
+
+ public static void initializeOptions(){
+ fOptions = new Hashtable(10);
+ fOptionIDs = new ArrayList(10);
+ }
+
+ public static void addOption(ConfigurableOption option){
+ String id = option.getID();
+ fOptions.put(id,option);
+ fOptionIDs.add(id);
+ }
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties
index fa56ab2beb..a3c90e4f40 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties
@@ -149,6 +149,7 @@ classpath.needAbsolutePath = Path for IClasspathEntry must be absolute.
file.notFound = File not found.
file.badFormat = Bad format.
variable.badFormat = Bad format for variables.
+option.badFormat = Bad format for options.
path.nullPath = Path cannot be null.
path.mustBeAbsolute = Path must be absolute.
cache.invalidLoadFactor = Incorrect load factor
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java
index cc6944b475..2dc4c805fd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java
@@ -21,6 +21,7 @@ import org.eclipse.jdt.internal.core.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
+import java.util.Map;
/**
@@ -103,7 +104,7 @@ protected void codeComplete(org.eclipse.jdt.internal.compiler.env.ICompilationUn
SearchableEnvironment environment = (SearchableEnvironment) ((JavaProject) getJavaProject()).getSearchableNameEnvironment();
environment.unitToSkip = unitToSkip;
- CompletionEngine engine = new CompletionEngine(environment, new CompletionRequestorWrapper(requestor), JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+ CompletionEngine engine = new CompletionEngine(environment, new CompletionRequestorWrapper(requestor), JavaModelManager.getOptions());
engine.complete(cu, position);
environment.unitToSkip = null;
}
@@ -134,7 +135,7 @@ protected void codeSelect(org.eclipse.jdt.internal.compiler.env.ICompilationUnit
ISearchableNameEnvironment environment = ((JavaProject)getJavaProject()).getSearchableNameEnvironment();
// fix for 1FVXGDK
- SelectionEngine engine = new SelectionEngine(environment, requestor, JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+ SelectionEngine engine = new SelectionEngine(environment, requestor, JavaModelManager.getOptions());
engine.select(cu, offset, offset + length - 1);
}
/**
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java
index 91a76939e7..f31cfdb128 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java
@@ -31,7 +31,9 @@ import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
* @see AttachSourceOperation
* @see JarPackageFragment
*/
-public class SourceMapper extends ReferenceInfoAdapter implements ISourceElementRequestor {
+public class SourceMapper
+ extends ReferenceInfoAdapter
+ implements ISourceElementRequestor {
/**
* The binary type source is being mapped for
@@ -70,7 +72,7 @@ public class SourceMapper extends ReferenceInfoAdapter implements ISourceElement
/**
* The unknown source range {-1, 0}
*/
- protected static SourceRange fgUnknownRange= new SourceRange(-1, 0);
+ protected static SourceRange fgUnknownRange = new SourceRange(-1, 0);
/**
* The position within the source of the start of the
@@ -100,447 +102,598 @@ public class SourceMapper extends ReferenceInfoAdapter implements ISourceElement
*/
private Hashtable importsTable;
private Hashtable importsCounterTable;
-
+
/**
* Enclosing type information
*/
- IType[] types;
- int[] typeDeclarationStarts;
- SourceRange[] typeNameRanges;
- int typeDepth;
-/**
- * Creates a <code>SourceMapper</code> that locates source in the zip file
- * at the given location in the specified package fragment root.
- */
-public SourceMapper(IPath zipPath, String rootPath, JavaModel model) {
- fZipPath= zipPath;
- fRootPath= rootPath.replace('\\', '/');
- if (fRootPath.endsWith("/"/*nonNLS*/)) {
- fRootPath = fRootPath.substring(0, fRootPath.lastIndexOf('/'));
- }
- fJavaModel= model;
- fSourceRanges= new Hashtable();
- importsTable = new Hashtable();
- importsCounterTable = new Hashtable();
-}
-/**
- * @see ISourceElementRequestor
- */
-public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
- char[][] imports = (char[][]) this.importsTable.get(fType);
- int importsCounter;
- if (imports == null) {
- imports = new char[5][];
- importsCounter = 0;
- } else {
- importsCounter = ((Integer) this.importsCounterTable.get(fType)).intValue();
- }
- if (imports.length == importsCounter) {
- System.arraycopy(imports, 0, (imports = new char[importsCounter * 2][]), 0, importsCounter);
- }
- imports[importsCounter++] = name;
- this.importsTable.put(fType, imports);
- this.importsCounterTable.put(fType, new Integer(importsCounter));
-}
-/**
- * @see ISourceElementRequestor
- */
-public void acceptInitializer(int modifiers, int declarationSourceStart, int declarationSourceEnd) {
- //do nothing
-}
-/**
- * @see ISourceElementRequestor
- */
-public void acceptLineSeparatorPositions(int[] positions) {
- //do nothing
-}
-/**
- * @see ISourceElementRequestor
- */
-public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
- //do nothing
-}
-/**
- * @see ISourceElementRequestor
- */
-public void acceptProblem(IProblem problem) {
- //do nothing
-}
-/**
- * Closes this <code>SourceMapper</code>'s zip file. Once this is done, this
- * <code>SourceMapper</code> cannot be used again.
- */
-public void close() throws JavaModelException {
- fSourceRanges= null;
-}
-/**
- * Converts these type names to signatures.
- * @see Signature.
- */
-public String[] convertTypeNamesToSigs(char[][] typeNames) {
- if (typeNames == null)
- return fgEmptyStringArray;
- int n = typeNames.length;
- if (n == 0)
- return fgEmptyStringArray;
- String[] typeSigs = new String[n];
- for (int i = 0; i < n; ++i) {
- typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
- }
- return typeSigs;
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterClass(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[] superclass, char[][] superinterfaces) {
-
- this.typeDepth++;
- if (this.typeDepth == this.types.length){ // need to grow
- System.arraycopy(this.types, 0, this.types = new IType[this.typeDepth*2], 0, this.typeDepth);
- System.arraycopy(this.typeNameRanges, 0, this.typeNameRanges = new SourceRange[this.typeDepth*2], 0, this.typeDepth);
- System.arraycopy(this.typeDeclarationStarts, 0, this.typeDeclarationStarts = new int[this.typeDepth*2], 0, this.typeDepth);
- }
- this.types[typeDepth] = this.getType(new String(name));
- this.typeNameRanges[typeDepth] = new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
- this.typeDeclarationStarts[typeDepth] = declarationStart;
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterCompilationUnit() {
- // do nothing
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterConstructor(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
- enterMethod(declarationStart, modifiers, null, name, nameSourceStart, nameSourceEnd, parameterTypes, parameterNames, exceptionTypes);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameSourceStart, int nameSourceEnd) {
- if (typeDepth >= 0 && fMemberDeclarationStart == -1) { // don't allow nested member (can only happen with anonymous inner classes)
- fMemberDeclarationStart= declarationStart;
- fMemberNameRange= new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
- fMemberName= new String(name);
- }
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterInterface(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[][] superinterfaces) {
- enterClass(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, null, superinterfaces);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void enterMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
- if (typeDepth >= 0 && fMemberDeclarationStart == -1) { // don't allow nested member (can only happen with anonymous inner classes)
- fMemberName= new String(name);
- fMemberNameRange= new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
- fMemberDeclarationStart= declarationStart;
- fMethodParameterTypes= parameterTypes;
- }
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitClass(int declarationEnd) {
- if (typeDepth >= 0) {
- IType currentType = this.types[typeDepth];
- setSourceRange(
- currentType,
- new SourceRange(
- this.typeDeclarationStarts[typeDepth] ,
- declarationEnd - this.typeDeclarationStarts[typeDepth] + 1),
- this.typeNameRanges[typeDepth]);
- this.typeDepth--;
- }
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitCompilationUnit(int declarationEnd) {
- //do nothing
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitConstructor(int declarationEnd) {
- exitMethod(declarationEnd);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitField(int declarationEnd) {
- if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
- IType currentType = this.types[typeDepth];
- setSourceRange(currentType.getField(fMemberName), new SourceRange(fMemberDeclarationStart, declarationEnd - fMemberDeclarationStart + 1), fMemberNameRange);
- fMemberDeclarationStart = -1;
+ IType[] types;
+ int[] typeDeclarationStarts;
+ SourceRange[] typeNameRanges;
+ int typeDepth;
+ /**
+ * Creates a <code>SourceMapper</code> that locates source in the zip file
+ * at the given location in the specified package fragment root.
+ */
+ public SourceMapper(IPath zipPath, String rootPath, JavaModel model) {
+ fZipPath = zipPath;
+ fRootPath = rootPath.replace('\\', '/');
+ if (fRootPath.endsWith("/" /*nonNLS*/)) {
+ fRootPath = fRootPath.substring(0, fRootPath.lastIndexOf('/'));
+ }
+ fJavaModel = model;
+ fSourceRanges = new Hashtable();
+ importsTable = new Hashtable();
+ importsCounterTable = new Hashtable();
}
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitInterface(int declarationEnd) {
- exitClass(declarationEnd);
-}
-/**
- * @see ISourceElementRequestor
- */
-public void exitMethod(int declarationEnd) {
- if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
- IType currentType = this.types[typeDepth];
- SourceRange sourceRange= new SourceRange(fMemberDeclarationStart, declarationEnd - fMemberDeclarationStart + 1);
- setSourceRange(currentType.getMethod(fMemberName, convertTypeNamesToSigs(fMethodParameterTypes)), sourceRange, fMemberNameRange);
- fMemberDeclarationStart = -1;
- }
-}
-/**
- * Locates and returns source code for the given (binary) type, in this
- * SourceMapper's ZIP file, or returns <code>null</code> if source
- * code cannot be found.
- */
-public char[] findSource(IType type) {
- if (!type.isBinary()) {
- return null;
- }
- BinaryType parent= (BinaryType)type.getDeclaringType();
- BinaryType declType= (BinaryType)type;
- while (parent != null) {
- declType= parent;
- parent= (BinaryType)declType.getDeclaringType();
- }
- IBinaryType info= null;
- try {
- info= (IBinaryType)declType.getRawInfo();
- } catch (JavaModelException e) {
- return null;
- }
- return this.findSource(type, info);
-}
-/**
- * Locates and returns source code for the given (binary) type, in this
- * SourceMapper's ZIP file, or returns <code>null</code> if source
- * code cannot be found.
- */
-public char[] findSource(IType type, IBinaryType info) {
- char[] sourceFileName = info.sourceFileName();
- if (sourceFileName == null) return null; // no source file attribute
- String name = new String(sourceFileName);
-
- IPackageFragment pkgFrag = type.getPackageFragment();
- if (!pkgFrag.isDefaultPackage()) {
- String pkg= type.getPackageFragment().getElementName().replace('.', '/');
- name= pkg + '/' + name;
- }
- // try to get the entry
- ZipEntry entry= null;
- ZipFile zip = null;
- char[] source= null;
- try {
- String fullName;
- //add the root path if specified
- if (!fRootPath.equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)) {
- fullName= fRootPath + '/' + name;
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void acceptImport(
+ int declarationStart,
+ int declarationEnd,
+ char[] name,
+ boolean onDemand) {
+ char[][] imports = (char[][]) this.importsTable.get(fType);
+ int importsCounter;
+ if (imports == null) {
+ imports = new char[5][];
+ importsCounter = 0;
} else {
- fullName= name;
+ importsCounter = ((Integer) this.importsCounterTable.get(fType)).intValue();
}
- zip = getZip();
- entry= zip.getEntry(fullName);
- if (entry != null) {
- // now read the source code
- byte[] bytes= readEntry(zip, entry);
- if (bytes != null) {
- try {
- source= BufferManager.bytesToChar(bytes);
- } catch (JavaModelException e) {
- source= null;
- }
- }
+ if (imports.length == importsCounter) {
+ System.arraycopy(
+ imports,
+ 0,
+ (imports = new char[importsCounter * 2][]),
+ 0,
+ importsCounter);
}
- } catch (CoreException e) {
- return null;
- } finally {
- if (zip != null) {
- try {
- zip.close();
- } catch(IOException e) {}
+ imports[importsCounter++] = name;
+ this.importsTable.put(fType, imports);
+ this.importsCounterTable.put(fType, new Integer(importsCounter));
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void acceptInitializer(
+ int modifiers,
+ int declarationSourceStart,
+ int declarationSourceEnd) {
+ //do nothing
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void acceptLineSeparatorPositions(int[] positions) {
+ //do nothing
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void acceptPackage(
+ int declarationStart,
+ int declarationEnd,
+ char[] name) {
+ //do nothing
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void acceptProblem(IProblem problem) {
+ //do nothing
+ }
+
+ /**
+ * Closes this <code>SourceMapper</code>'s zip file. Once this is done, this
+ * <code>SourceMapper</code> cannot be used again.
+ */
+ public void close() throws JavaModelException {
+ fSourceRanges = null;
+ }
+
+ /**
+ * Converts these type names to signatures.
+ * @see Signature.
+ */
+ public String[] convertTypeNamesToSigs(char[][] typeNames) {
+ if (typeNames == null)
+ return fgEmptyStringArray;
+ int n = typeNames.length;
+ if (n == 0)
+ return fgEmptyStringArray;
+ String[] typeSigs = new String[n];
+ for (int i = 0; i < n; ++i) {
+ typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
}
+ return typeSigs;
}
- return source;
-}
-/**
- * Returns the SourceRange for the name of the given element, or
- * {-1, -1} if no source range is known for the name of the element.
- */
-public SourceRange getNameRange(IJavaElement element) {
- if (element.getElementType() == IJavaElement.METHOD && ((IMember)element).isBinary()) {
- element= getUnqualifiedMethodHandle((IMethod)element);
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterClass(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[] superclass,
+ char[][] superinterfaces) {
+
+ this.typeDepth++;
+ if (this.typeDepth == this.types.length) { // need to grow
+ System.arraycopy(
+ this.types,
+ 0,
+ this.types = new IType[this.typeDepth * 2],
+ 0,
+ this.typeDepth);
+ System.arraycopy(
+ this.typeNameRanges,
+ 0,
+ this.typeNameRanges = new SourceRange[this.typeDepth * 2],
+ 0,
+ this.typeDepth);
+ System.arraycopy(
+ this.typeDeclarationStarts,
+ 0,
+ this.typeDeclarationStarts = new int[this.typeDepth * 2],
+ 0,
+ this.typeDepth);
+ }
+ this.types[typeDepth] = this.getType(new String(name));
+ this.typeNameRanges[typeDepth] =
+ new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
+ this.typeDeclarationStarts[typeDepth] = declarationStart;
}
- SourceRange[] ranges= (SourceRange[])fSourceRanges.get(element);
- if (ranges == null) {
- return fgUnknownRange;
- } else {
- return ranges[1];
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterCompilationUnit() {
+ // do nothing
}
-}
-/**
- * Returns the <code>SourceRange</code> for the given element, or
- * {-1, -1} if no source range is known for the element.
- */
-public SourceRange getSourceRange(IJavaElement element) {
- if (element.getElementType() == IJavaElement.METHOD && ((IMember)element).isBinary()) {
- element= getUnqualifiedMethodHandle((IMethod)element);
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterConstructor(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes) {
+ enterMethod(
+ declarationStart,
+ modifiers,
+ null,
+ name,
+ nameSourceStart,
+ nameSourceEnd,
+ parameterTypes,
+ parameterNames,
+ exceptionTypes);
}
- SourceRange[] ranges= (SourceRange[])fSourceRanges.get(element);
- if (ranges == null) {
- return fgUnknownRange;
- } else {
- return ranges[0];
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterField(
+ int declarationStart,
+ int modifiers,
+ char[] type,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd) {
+ if (typeDepth >= 0
+ && fMemberDeclarationStart == -1) {
+ // don't allow nested member (can only happen with anonymous inner classes)
+ fMemberDeclarationStart = declarationStart;
+ fMemberNameRange =
+ new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
+ fMemberName = new String(name);
+ }
}
-}
-/**
- * Returns the type with the given <code>typeName</code>. Returns inner classes
- * as well.
- */
-protected IType getType(String typeName) {
- if (fType.getElementName().equals(typeName))
- return fType;
- else
- return fType.getType(typeName);
-}
-/**
- * Creates a handle that has parameter types that are not
- * fully qualified so that the correct source is found.
- */
-protected IJavaElement getUnqualifiedMethodHandle(IMethod method) {
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterInterface(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] superinterfaces) {
+ enterClass(
+ declarationStart,
+ modifiers,
+ name,
+ nameSourceStart,
+ nameSourceEnd,
+ null,
+ superinterfaces);
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterMethod(
+ int declarationStart,
+ int modifiers,
+ char[] returnType,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes) {
+ if (typeDepth >= 0
+ && fMemberDeclarationStart == -1) {
+ // don't allow nested member (can only happen with anonymous inner classes)
+ fMemberName = new String(name);
+ fMemberNameRange =
+ new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
+ fMemberDeclarationStart = declarationStart;
+ fMethodParameterTypes = parameterTypes;
+ }
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitClass(int declarationEnd) {
+ if (typeDepth >= 0) {
+ IType currentType = this.types[typeDepth];
+ setSourceRange(
+ currentType,
+ new SourceRange(
+ this.typeDeclarationStarts[typeDepth],
+ declarationEnd - this.typeDeclarationStarts[typeDepth] + 1),
+ this.typeNameRanges[typeDepth]);
+ this.typeDepth--;
+ }
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitCompilationUnit(int declarationEnd) {
+ //do nothing
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitConstructor(int declarationEnd) {
+ exitMethod(declarationEnd);
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitField(int declarationEnd) {
+ if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
+ IType currentType = this.types[typeDepth];
+ setSourceRange(
+ currentType.getField(fMemberName),
+ new SourceRange(
+ fMemberDeclarationStart,
+ declarationEnd - fMemberDeclarationStart + 1),
+ fMemberNameRange);
+ fMemberDeclarationStart = -1;
+ }
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitInterface(int declarationEnd) {
+ exitClass(declarationEnd);
+ }
+
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitMethod(int declarationEnd) {
+ if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
+ IType currentType = this.types[typeDepth];
+ SourceRange sourceRange =
+ new SourceRange(
+ fMemberDeclarationStart,
+ declarationEnd - fMemberDeclarationStart + 1);
+ setSourceRange(
+ currentType.getMethod(
+ fMemberName,
+ convertTypeNamesToSigs(fMethodParameterTypes)),
+ sourceRange,
+ fMemberNameRange);
+ fMemberDeclarationStart = -1;
+ }
+ }
+
+ /**
+ * Locates and returns source code for the given (binary) type, in this
+ * SourceMapper's ZIP file, or returns <code>null</code> if source
+ * code cannot be found.
+ */
+ public char[] findSource(IType type) {
+ if (!type.isBinary()) {
+ return null;
+ }
+ BinaryType parent = (BinaryType) type.getDeclaringType();
+ BinaryType declType = (BinaryType) type;
+ while (parent != null) {
+ declType = parent;
+ parent = (BinaryType) declType.getDeclaringType();
+ }
+ IBinaryType info = null;
+ try {
+ info = (IBinaryType) declType.getRawInfo();
+ } catch (JavaModelException e) {
+ return null;
+ }
+ return this.findSource(type, info);
+ }
+
+ /**
+ * Locates and returns source code for the given (binary) type, in this
+ * SourceMapper's ZIP file, or returns <code>null</code> if source
+ * code cannot be found.
+ */
+ public char[] findSource(IType type, IBinaryType info) {
+ char[] sourceFileName = info.sourceFileName();
+ if (sourceFileName == null)
+ return null; // no source file attribute
+ String name = new String(sourceFileName);
- String[] qualifiedParameterTypes = method.getParameterTypes();
- String[] unqualifiedParameterTypes = new String[qualifiedParameterTypes.length];
- for (int i = 0; i < qualifiedParameterTypes.length; i++) {
- StringBuffer unqualifiedName= new StringBuffer();
- String qualifiedName= qualifiedParameterTypes[i];
- int count = 0;
- while (qualifiedName.charAt(count) == Signature.C_ARRAY) {
- unqualifiedName.append(Signature.C_ARRAY);
- ++count;
+ IPackageFragment pkgFrag = type.getPackageFragment();
+ if (!pkgFrag.isDefaultPackage()) {
+ String pkg = type.getPackageFragment().getElementName().replace('.', '/');
+ name = pkg + '/' + name;
+ }
+ // try to get the entry
+ ZipEntry entry = null;
+ ZipFile zip = null;
+ char[] source = null;
+ try {
+ String fullName;
+ //add the root path if specified
+ if (!fRootPath.equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)) {
+ fullName = fRootPath + '/' + name;
+ } else {
+ fullName = name;
+ }
+ zip = getZip();
+ entry = zip.getEntry(fullName);
+ if (entry != null) {
+ // now read the source code
+ byte[] bytes = readEntry(zip, entry);
+ if (bytes != null) {
+ try {
+ source = BufferManager.bytesToChar(bytes);
+ } catch (JavaModelException e) {
+ source = null;
+ }
+ }
+ }
+ } catch (CoreException e) {
+ return null;
+ } finally {
+ if (zip != null) {
+ try {
+ zip.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ return source;
+ }
+
+ /**
+ * Returns the SourceRange for the name of the given element, or
+ * {-1, -1} if no source range is known for the name of the element.
+ */
+ public SourceRange getNameRange(IJavaElement element) {
+ if (element.getElementType() == IJavaElement.METHOD
+ && ((IMember) element).isBinary()) {
+ element = getUnqualifiedMethodHandle((IMethod) element);
}
- if (qualifiedName.charAt(count) == Signature.C_RESOLVED) {
- unqualifiedName.append(Signature.C_UNRESOLVED);
- unqualifiedName.append(Signature.getSimpleName(qualifiedName));
+ SourceRange[] ranges = (SourceRange[]) fSourceRanges.get(element);
+ if (ranges == null) {
+ return fgUnknownRange;
} else {
- unqualifiedName.append(qualifiedName.substring(count, qualifiedName.length()));
+ return ranges[1];
}
- unqualifiedParameterTypes[i]= unqualifiedName.toString();
}
- return ((IType) method.getParent()).getMethod(method.getElementName(), unqualifiedParameterTypes);
-}
-/**
- * Returns the <code>ZipFile</code> that source is located in.
- */
-public ZipFile getZip() throws CoreException {
- return fJavaModel.fgJavaModelManager.getZipFile(fZipPath);
-}
-/**
- * Maps the given source code to the given binary type and its children.
- */
-public void mapSource(IType type, char[] contents) {
- this.mapSource(type, contents, null);
-}
-/**
- * Maps the given source code to the given binary type and its children.
- * If a non-null java element is passed, finds the name range for the
- * given java element without storing it.
- */
-public ISourceRange mapSource(IType type, char[] contents, IJavaElement searchedElement) {
- fType= (BinaryType)type;
-
- this.importsTable.remove(fType);
- this.importsCounterTable.remove(fType);
- this.searchedElement = searchedElement;
- this.types = new IType[1];
- this.typeDeclarationStarts = new int[1];
- this.typeNameRanges = new SourceRange[1];
- this.typeDepth = -1;
-
- Hashtable oldSourceRanges = (Hashtable)fSourceRanges.clone();
- try {
- IProblemFactory factory= new DefaultProblemFactory();
- SourceElementParser parser = new SourceElementParser(this, factory);
- parser.parseCompilationUnit(new BasicCompilationUnit(contents, type.getElementName() + ".java"/*nonNLS*/), false);
- if (searchedElement != null) {
- ISourceRange range = this.getNameRange(searchedElement);
- return range;
+
+ /**
+ * Returns the <code>SourceRange</code> for the given element, or
+ * {-1, -1} if no source range is known for the element.
+ */
+ public SourceRange getSourceRange(IJavaElement element) {
+ if (element.getElementType() == IJavaElement.METHOD
+ && ((IMember) element).isBinary()) {
+ element = getUnqualifiedMethodHandle((IMethod) element);
+ }
+ SourceRange[] ranges = (SourceRange[]) fSourceRanges.get(element);
+ if (ranges == null) {
+ return fgUnknownRange;
} else {
- return null;
+ return ranges[0];
}
- } finally {
- if (searchedElement != null) {
- fSourceRanges = oldSourceRanges;
+ }
+
+ /**
+ * Returns the type with the given <code>typeName</code>. Returns inner classes
+ * as well.
+ */
+ protected IType getType(String typeName) {
+ if (fType.getElementName().equals(typeName))
+ return fType;
+ else
+ return fType.getType(typeName);
+ }
+
+ /**
+ * Creates a handle that has parameter types that are not
+ * fully qualified so that the correct source is found.
+ */
+ protected IJavaElement getUnqualifiedMethodHandle(IMethod method) {
+
+ String[] qualifiedParameterTypes = method.getParameterTypes();
+ String[] unqualifiedParameterTypes = new String[qualifiedParameterTypes.length];
+ for (int i = 0; i < qualifiedParameterTypes.length; i++) {
+ StringBuffer unqualifiedName = new StringBuffer();
+ String qualifiedName = qualifiedParameterTypes[i];
+ int count = 0;
+ while (qualifiedName.charAt(count) == Signature.C_ARRAY) {
+ unqualifiedName.append(Signature.C_ARRAY);
+ ++count;
+ }
+ if (qualifiedName.charAt(count) == Signature.C_RESOLVED) {
+ unqualifiedName.append(Signature.C_UNRESOLVED);
+ unqualifiedName.append(Signature.getSimpleName(qualifiedName));
+ } else {
+ unqualifiedName.append(qualifiedName.substring(count, qualifiedName.length()));
+ }
+ unqualifiedParameterTypes[i] = unqualifiedName.toString();
}
- fType= null;
- this.searchedElement = null;
- this.types = null;
- this.typeDeclarationStarts = null;
- this.typeNameRanges = null;
- this.typeDepth = -1;
+ return ((IType) method.getParent()).getMethod(
+ method.getElementName(),
+ unqualifiedParameterTypes);
}
-}
-/**
- * Returns the contents of the specified zip entry
- */
-protected byte[] readEntry(ZipFile zip, ZipEntry entry) {
- InputStream stream = null;
- try {
- stream = zip.getInputStream(entry);
- int remaining = (int) entry.getSize();
- byte[] bytes = new byte[remaining];
- int offset = 0;
- while (remaining > 0) {
- int read = stream.read(bytes, offset, remaining);
- if (read == -1)
- break;
- remaining -= read;
- offset += read;
+
+ /**
+ * Returns the <code>ZipFile</code> that source is located in.
+ */
+ public ZipFile getZip() throws CoreException {
+ return fJavaModel.fgJavaModelManager.getZipFile(fZipPath);
+ }
+
+ /**
+ * Maps the given source code to the given binary type and its children.
+ */
+ public void mapSource(IType type, char[] contents) {
+ this.mapSource(type, contents, null);
+ }
+
+ /**
+ * Maps the given source code to the given binary type and its children.
+ * If a non-null java element is passed, finds the name range for the
+ * given java element without storing it.
+ */
+ public ISourceRange mapSource(
+ IType type,
+ char[] contents,
+ IJavaElement searchedElement) {
+ fType = (BinaryType) type;
+
+ this.importsTable.remove(fType);
+ this.importsCounterTable.remove(fType);
+ this.searchedElement = searchedElement;
+ this.types = new IType[1];
+ this.typeDeclarationStarts = new int[1];
+ this.typeNameRanges = new SourceRange[1];
+ this.typeDepth = -1;
+
+ Hashtable oldSourceRanges = (Hashtable) fSourceRanges.clone();
+ try {
+ IProblemFactory factory = new DefaultProblemFactory();
+ SourceElementParser parser = new SourceElementParser(this, factory);
+ parser.parseCompilationUnit(
+ new BasicCompilationUnit(contents, type.getElementName() + ".java" /*nonNLS*/),
+ false);
+ if (searchedElement != null) {
+ ISourceRange range = this.getNameRange(searchedElement);
+ return range;
+ } else {
+ return null;
+ }
+ } finally {
+ if (searchedElement != null) {
+ fSourceRanges = oldSourceRanges;
+ }
+ fType = null;
+ this.searchedElement = null;
+ this.types = null;
+ this.typeDeclarationStarts = null;
+ this.typeNameRanges = null;
+ this.typeDepth = -1;
}
- return bytes;
- } catch (IOException e) {
- return null;
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException ioe) {
+ }
+
+ /**
+ * Returns the contents of the specified zip entry
+ */
+ protected byte[] readEntry(ZipFile zip, ZipEntry entry) {
+ InputStream stream = null;
+ try {
+ stream = zip.getInputStream(entry);
+ int remaining = (int) entry.getSize();
+ byte[] bytes = new byte[remaining];
+ int offset = 0;
+ while (remaining > 0) {
+ int read = stream.read(bytes, offset, remaining);
+ if (read == -1)
+ break;
+ remaining -= read;
+ offset += read;
+ }
+ return bytes;
+ } catch (IOException e) {
+ return null;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ return null;
+ } finally {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException ioe) {
+ }
}
}
}
-}
-/**
- * Sets the mapping for this element to its source ranges for its source range
- * and name range.
- *
- * @see fSourceRanges
- */
-protected void setSourceRange(IJavaElement element, SourceRange sourceRange, SourceRange nameRange) {
- fSourceRanges.put(element, new SourceRange[] {sourceRange, nameRange});
-}
+
+ /**
+ * Sets the mapping for this element to its source ranges for its source range
+ * and name range.
+ *
+ * @see fSourceRanges
+ */
+ protected void setSourceRange(
+ IJavaElement element,
+ SourceRange sourceRange,
+ SourceRange nameRange) {
+ fSourceRanges.put(element, new SourceRange[] { sourceRange, nameRange });
+ }
-/**
- * Return a char[][] array containing the imports of the attached source for the fType binary
- */
-public char[][] getImports(BinaryType type) {
- char[][] imports = (char[][]) this.importsTable.get(type);
- if (imports != null) {
- int importsCounter = ((Integer) this.importsCounterTable.get(type)).intValue();
- if (imports.length != importsCounter) {
- System.arraycopy(imports, 0, (imports = new char[importsCounter][]), 0, importsCounter);
- }
- }
- this.importsTable.put(type, imports);
- return imports;
-}
+ /**
+ * Return a char[][] array containing the imports of the attached source for the fType binary
+ */
+ public char[][] getImports(BinaryType type) {
+ char[][] imports = (char[][]) this.importsTable.get(type);
+ if (imports != null) {
+ int importsCounter = ((Integer) this.importsCounterTable.get(type)).intValue();
+ if (imports.length != importsCounter) {
+ System.arraycopy(
+ imports,
+ 0,
+ (imports = new char[importsCounter][]),
+ 0,
+ importsCounter);
+ }
+ }
+ this.importsTable.put(type, imports);
+ return imports;
+ }
} \ No newline at end of file
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java
index 3fffc3fa6f..3f4489070a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java
@@ -306,7 +306,7 @@ public ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor mo
}
TypeResolveRequestor requestor = new TypeResolveRequestor();
SelectionEngine engine =
- new SelectionEngine(environment, requestor, JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+ new SelectionEngine(environment, requestor, JavaModelManager.getOptions());
engine.selectType(info, typeName.toCharArray());
return requestor.answers;
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java
index 453d8b1799..5b5415adf1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java
@@ -39,7 +39,6 @@ public BatchImageBuilder(StateImpl state) {
*/
protected BatchImageBuilder(StateImpl state, ConfigurableOption[] options) {
fDC = (JavaDevelopmentContextImpl) state.getDevelopmentContext();
- state.setCompilerOptions(options);
fCompilerOptions = options;
fNewState = state;
fWorkQueue = new WorkQueue();
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java
index 30a9a8db76..bfe0c977aa 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java
@@ -203,8 +203,7 @@ public void applySourceDelta(Hashtable deltas) {
fNewState = fOldState.copy(fNewProject, fImageContext);
// options might have changed since last builder run, thus refresh them
- fCompilerOptions = JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
- fNewState.setCompilerOptions(fCompilerOptions);
+ fCompilerOptions = JavaModelManager.getOptions();
try {
/* find out what has changed at the package level */
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java
index 43dd321781..4243f759c5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java
@@ -143,7 +143,7 @@ protected boolean classpathChanged(IState lastBuiltState) throws CoreException {
/* create and invoke the batch builder */
// Pass the compiler options, needed for 1FVXS80: ITPJCORE:ALL - .class files are missing their LocalVariableTable
- ConfigurableOption[] options = JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
+ ConfigurableOption[] options = JavaModelManager.getOptions();
setLastBuiltState(null); // free possible existing state
IImageBuilder builder = dc.createState(project, null, problemReporter, options);
setLastBuiltState(builder.getNewState());
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java
index 3b894eac78..720f1c48d6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java
@@ -18,8 +18,10 @@ import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.ConfigurableOption;
+import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.core.Util;
+import org.eclipse.jdt.internal.core.JavaModelManager;
import org.eclipse.jdt.internal.core.builder.IBinaryBroker;
import org.eclipse.jdt.internal.core.builder.IBuildListener;
import org.eclipse.jdt.internal.core.builder.IBuildMonitor;
@@ -203,15 +205,7 @@ public IState getCurrentState() throws NotPresentException {
* Reads the default compiler options.
*/
protected static ConfigurableOption[] getDefaultCompilerOptions() {
- ConfigurableOption[] options = Compiler.getDefaultOptions(Locale.getDefault());
-
- /**
- * Ugly because this requires knowledge of the compiler's
- * internal problem representation.
- */
- setCompilerOption(options, 11, 1);
- setCompilerOption(options, 12, 1);
- return options;
+ return JavaModelManager.getOptions();
}
/**
* Returns the default package handle (java.lang).
@@ -405,17 +399,7 @@ public void setBinaryBroker(IBinaryBroker broker) {
*/
public void setBuildProgressListener(IProgressListener listener) {
}
-/**
- * Sets a compiler option. This seems awkward.
- */
-protected static void setCompilerOption(ConfigurableOption[] options, int optionID, int valueIndex) {
- for (int i = 0; i < options.length; i++) {
- if (options[i].getID() == optionID) {
- options[i].setValueIndex(valueIndex);
- return;
- }
- }
-}
+
/**
* setCurrentState method comment.
*/
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java
index 0dce2cd329..6d9623f525 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java
@@ -1,5 +1,5 @@
package org.eclipse.jdt.internal.core.builder.impl;
-
+
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
@@ -16,7 +16,7 @@ import java.util.Random;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
-
+
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
@@ -63,52 +63,52 @@ import org.eclipse.jdt.internal.core.builder.NotPresentException;
import org.eclipse.jdt.internal.core.builder.StateSpecificException;
import org.eclipse.jdt.internal.core.lookup.ReferenceInfo;
import org.eclipse.jdt.internal.core.util.LookupTable;
-
+
/**
* The concrete representation of a built state.
*
* @see IState
*/
public class StateImpl implements IState {
-
+
/**
* The development context corresponding to this state
*/
private JavaDevelopmentContextImpl fDevelopmentContext;
-
+
/**
* The build context. Only packages in the build context
* are actually built
*/
private IImageContext fBuildContext;
-
+
/**
* The project built by this state.
*/
private IProject fProject;
-
+
/**
* The name of the project built by this state.
*/
private String fProjectName;
-
+
/**
* The paths of the package fragment roots in the class path.
*/
private IPackageFragmentRoot[] fPackageFragmentRootsInClassPath;
-
+
/**
* The binary output.
*/
private BinaryOutput fBinaryOutput;
-
+
/**
* The package map. A hashtable of package handles to PackageMapEntry objects.
* The package map entries store the collection of package fragments that
* make up the given builder package.
*/
private PackageMap fPackageMap;
-
+
/**
* The path map. A table that maps from paths to package handles. This
* is essentially a reverse index of the package map. Note that this
@@ -116,63 +116,58 @@ public class StateImpl implements IState {
* not need to be serialized or incrementally updated.
*/
private PathMap fPathMap;
-
+
/**
* The source element table. This table holds a source fragment for
* all workspace elements.
*/
private SourceElementTable fSourceElementTable;
-
+
/**
* The principal structure table. A table of type handles to TypeStructureEntry objects.
* This is where build results are stored. This table only contains types that
* have been compiled.
*/
private Hashtable fPrincipalStructureTable;
-
+
/**
* Table of IPackage to TypeStructureEntry[] for all types in package (lazy).
*/
private Hashtable fPrincipalStructureByPackageTable;
-
+
/**
* The problem reporter. All problems for this state are stored in this problem
* reporter.
*/
private IProblemReporter fProblemReporter;
-
+
/**
* The graph of source element dependencies, used for
* incremental compilation
*/
private DependencyGraph fGraph= null;
-
+
/**
* The table of subtypes. Maps from IType to TypeStructureEntry[]. Absence in table implies no subtypes.
*/
private Hashtable fSubtypesTable;
private IImageContext fSubtypesTableImageContext;
-
+
/**
* The image corresponding to this state
*/
private IImage fImage;
-
- /**
- * The compiler options that were used to build this state.
- */
- private ConfigurableOption[] fCompilerOptions;
-
+
/**
* Unique state number
*/
private int fStateNumber;
-
+
/**
* Fingerprint bytes
*/
private byte[] fFingerprint;
-
+
/* primitive type handles */
final IType fVoidType;
final IType fIntType;
@@ -183,28 +178,28 @@ public class StateImpl implements IState {
final IType fLongType;
final IType fShortType;
final IType fBooleanType;
-
+
/**
* Counter for unique state numbers (not the fingerprint).
*/
private static int fgStateCounter= 0;
-
+
/**
* Namespace flag indicating CU has parse error.
* Must not conflict with modifiers or other flags in IConstants.
*/
private static final int F_HAS_PARSE_ERROR= 0x10000000;
-
+
/**
* Name for namespace node representing unknown dependencies.
*/
private static final String UNKNOWN_DEPENDENCIES= "$UNKNOWN_DEPENDENCIES$"/*nonNLS*/;
-
+
/**
* Random number generator, used for generating fingerprints.
*/
private static final Random fgRandom= new Random();
-
+
/**
* State constructor comment. The build context, fingerprint, and internal tables
* are not instantiated and must be filled in before use.
@@ -231,7 +226,7 @@ public class StateImpl implements IState {
protected StateImpl(JavaDevelopmentContextImpl dc, IProject project, IImageContext buildContext) {
this(dc, project);
fBuildContext= buildContext;
-
+
/* state tables */
fPackageMap= new PackageMap();
fSourceElementTable= new SourceElementTable();
@@ -255,7 +250,7 @@ public class StateImpl implements IState {
*/
protected void buildInitialPackageMap() {
fPackageMap= new PackageMap();
-
+
/* do for each package fragment root in (classpath INTERSECT workspace) */
try {
IPackageFragmentRoot[] roots= getPackageFragmentRootsInClassPath();
@@ -279,7 +274,7 @@ public class StateImpl implements IState {
} catch (JavaModelException e) {
throw internalException(e);
}
-
+
/* build the reverse index -- the path map */
fPathMap= new PathMap(fPackageMap);
}
@@ -357,12 +352,12 @@ public class StateImpl implements IState {
IPackage[] oldPackages= oldContext.getPackages();
int pkgCount= oldPackages.length;
IPackage[] newPackages= new IPackage[pkgCount];
-
+
/* canonicalize packages through package map */
for (int i= 0; i < pkgCount; i++) {
newPackages[i]= canonicalize(oldPackages[i]);
}
-
+
return new ImageContextImpl(fDevelopmentContext, newPackages);
}
/**
@@ -406,7 +401,7 @@ public class StateImpl implements IState {
String fileName= new String(result.getFileName());
SourceEntry sEntry= SourceEntry.fromPathWithZipEntryName(fileName);
PackageElement resultUnit= packageElementFromSourceEntry(sEntry);
-
+
/**
* Make sure the CU exists. May be null if unit is unavailable
* (e.g. package is not included in package map due to class path omission).
@@ -415,7 +410,7 @@ public class StateImpl implements IState {
IPackage resultPkg= resultUnit.getPackage();
IProblem[] compilerProblems= result.getProblems();
Vector vProblems= new Vector(compilerProblems == null ? 0 : compilerProblems.length);
-
+
/* convert type names to type handles for the produced types */
ClassFile[] classFiles= result.getClassFiles();
Vector vTSEntries= new Vector(classFiles.length);
@@ -454,7 +449,7 @@ public class StateImpl implements IState {
continue;
}
TypeStructureEntry tsEntry= new TypeStructureEntry(sEntry, typeHandle);
-
+
/* squirrel the binary away */
byte[] binary= classFile.getBytes();
// as a side effect, the following sets the crc32 for the type structure entry
@@ -463,10 +458,10 @@ public class StateImpl implements IState {
}
TypeStructureEntry[] tsEntries= new TypeStructureEntry[vTSEntries.size()];
vTSEntries.copyInto(tsEntries);
-
+
/* convert dependencies */
Vector dependencies= resolveDependencies(resultUnit, result);
-
+
/* convert problems */
if (compilerProblems != null) {
for (int i= 0; i < compilerProblems.length; i++) {
@@ -493,7 +488,6 @@ public class StateImpl implements IState {
newState.fProblemReporter= this.fProblemReporter.copy();
newState.fGraph= this.fGraph.copy();
newState.fBuildContext= context;
- newState.fCompilerOptions= this.fCompilerOptions;
return newState;
}
/**
@@ -521,7 +515,7 @@ public class StateImpl implements IState {
IType type= tsEntry.getType();
SourceEntry sEntry= tsEntry.getSourceEntry();
IBinaryType binaryType= null;
-
+
/* if its a class file, get descriptor from binary index */
if (sEntry.isBinary()) {
try {
@@ -580,9 +574,9 @@ public class StateImpl implements IState {
if (!fPackageMap.containsPackage(pkg)) {
return null;
}
-
+
// TBD: Doesn't support lazy builds.
-
+
int max= 30;
TypeStructureEntry[] list= new TypeStructureEntry[max];
int count= 0;
@@ -611,12 +605,12 @@ public class StateImpl implements IState {
}
IType nssHandle= (IType) type.nonStateSpecific();
TypeStructureEntry tsEntry= buildTypeStructureEntry(nssHandle);
-
+
/* Attempt to retrieve binary from binary output */
byte[] binary= getBinaryOutput().getBinary(tsEntry, nssHandle);
if (binary != null)
return binary;
-
+
/*
* We have a built entry, but couldn't get the bytes from the binary output.
* Need to recompile.
@@ -624,7 +618,7 @@ public class StateImpl implements IState {
if (!lazyBuildCU) {
return null;
}
-
+
/* make sure the entry is a compilation unit */
PackageElement unit= packageElementFromSourceEntry(tsEntry.getSourceEntry());
new BatchImageBuilder(this).lazyBuild(unit);
@@ -654,7 +648,7 @@ public class StateImpl implements IState {
* is thrown.
*/
protected IBinaryType getBinaryType(TypeStructureEntry tsEntry) throws NotPresentException {
-
+
/* rebuild descriptor from indexes or binary */
IBinaryType binaryType= forceBinaryType(tsEntry, false); // Use false for 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
if (binaryType == null) {
@@ -668,7 +662,7 @@ public class StateImpl implements IState {
* the binary is not available (doesn't invoke a lazy build)
*/
protected IBinaryType getBinaryTypeOrNull(TypeStructureEntry tsEntry) {
-
+
/* rebuild descriptor from binary */
return forceBinaryType(tsEntry, false);
}
@@ -728,12 +722,7 @@ public class StateImpl implements IState {
return null;
return new PackageElement(pkg, entry);
}
- /**
- * Returns the compiler options used to build this state.
- */
- public ConfigurableOption[] getCompilerOptions() {
- return fCompilerOptions;
- }
+
/**
* Returns an enumeration of TypeStructureEntry objects for all top-level types
* in the given package. Returns null if the package does not exist.
@@ -1092,10 +1081,10 @@ static Comparator getPathComparator() {
* The resulting packages are in no particular order.
*/
protected IPackage[] getReferencedPackages(IPackage pkgHandle) {
-
+
/* set of referenced builder packages */
Hashtable pkgTable= getTableOfReferencedPackages(pkgHandle);
-
+
/* convert to array and return */
IPackage[] results= new IPackage[pkgTable.size()];
int i= 0;
@@ -1135,11 +1124,11 @@ static Comparator getPathComparator() {
* This is an extremely slow implementation (n^3?). Avoid using it if possible.
*/
protected IPackage[] getReferencingPackages(IPackage pkgHandle, IImageContext context) {
-
+
/* the results */
Vector vResults= new Vector();
IImage image= fDevelopmentContext.getImage();
-
+
/* do for each package in the image context */
IPackage[] pkgs= context.getPackages();
for (int i= 0; i < pkgs.length; i++) {
@@ -1292,15 +1281,15 @@ static Comparator getPathComparator() {
if (entries != null) {
return entries;
}
-
+
/* Need to build the table for the package */
-
+
/* go through package fragments and compute all source entries */
IPath[] frags= fPackageMap.getFragments(pkg);
if (frags == null) {
return null; // package not present
}
-
+
/* build a table of source entries, keyed by filename */
LookupTable entryTable= new LookupTable(20);
for (int i= 0; i < frags.length; i++) {
@@ -1426,14 +1415,14 @@ static Comparator getPathComparator() {
protected Hashtable getTableOfReferencedPackages(IPackage pkgHandle) {
/* set of referenced builder packages */
Hashtable pkgTable= new Hashtable();
-
+
/* do for each type in this package */
TypeStructureEntry[] types= getAllTypesForPackage(pkgHandle);
if (types != null) {
for (int i= 0; i < types.length; i++) {
PackageElement element= packageElementFromSourceEntry(types[i].getSourceEntry());
IPackage[] deps= getInternalDependencyGraph().getNamespaceDependencies(element);
-
+
/* make sure namespaces are actually packages */
for (int j= 0; j < deps.length; j++) {
if (fPackageMap.getEntry(deps[j]) != null) {
@@ -1442,7 +1431,7 @@ static Comparator getPathComparator() {
}
}
}
-
+
/* remove this package */
pkgTable.remove(pkgHandle);
return pkgTable;
@@ -1469,16 +1458,16 @@ static Comparator getPathComparator() {
if (tsEntry != null) {
return tsEntry;
}
-
+
// TBD: Doesn't handle lazy builds.
-
+
/* get the source element */
IPackage pkg= handle.getPackage();
SourceEntry sEntry= getSourceEntry(handle);
if (sEntry == null) {
return null;
}
-
+
/* if its a class file, parse it */
if (sEntry.isBinary()) {
//byte[] bytes = getElementContentBytes(sEntry);
@@ -1493,13 +1482,13 @@ static Comparator getPathComparator() {
// Don't try again.
return null;
}
-
+
// make sure the entry is a compilation unit
PackageElement unit= packageElementFromSourceEntry(sEntry);
-
+
// compile it
new BatchImageBuilder(this).lazyBuild(unit);
-
+
// try to get the entry again; may still be null
tsEntry= (TypeStructureEntry) fPrincipalStructureTable.get(handle);
}
@@ -1567,7 +1556,7 @@ static Comparator getPathComparator() {
protected IPackage packageFromSourceEntry(SourceEntry entry) {
IPath path= entry.getPath();
IPackage pkgHandle;
-
+
/* if it's a zip file */
String zipEntryFileName = entry.fZipEntryFileName;
if (zipEntryFileName != null) {
@@ -1592,23 +1581,23 @@ static Comparator getPathComparator() {
*/
protected void putCompilationResult(ConvertedCompilationResult result) {
PackageElement unit= result.getPackageElement();
-
+
/* get source entry for result */
SourceEntry sEntry= getSourceEntry(unit);
-
+
/* record problems */
fProblemReporter.removeNonSyntaxErrors(sEntry);
IProblemDetail[] problems= result.getProblems();
for (int i= 0; i < problems.length; ++i) {
fProblemReporter.putProblem(sEntry, problems[i]);
}
-
+
/* This records the types actually contributed, */
/* to record in the dependency graph. */
TypeStructureEntry[] tsEntries= result.getTypes();
IType[] types= new IType[tsEntries.length];
int count= 0;
-
+
/* record type structure */
for (int i= 0; i < tsEntries.length; i++) {
TypeStructureEntry tsEntry= tsEntries[i];
@@ -1625,12 +1614,12 @@ static Comparator getPathComparator() {
continue;
}
}
-
+
// Finally, put it in table.
fPrincipalStructureTable.put(typeHandle, tsEntry);
types[count++]= typeHandle;
}
-
+
/* Update the dependency graph. */
if (count < types.length) {
System.arraycopy(types, 0, types= new IType[count], 0, count);
@@ -1723,7 +1712,7 @@ static Comparator getPathComparator() {
if (!vSourceDeps.contains(fDevelopmentContext.getDefaultPackage())) {
vSourceDeps.addElement(fDevelopmentContext.getDefaultPackage());
}
-
+
/* do for each file dependency */
if (fileDependencies != null) {
for (int i= 0; i < fileDependencies.length; i++) {
@@ -1756,13 +1745,6 @@ static Comparator getPathComparator() {
fBuildContext= context;
}
/**
- * Sets the compiler options that were in effect when
- * this state was built.
- */
- protected void setCompilerOptions(ConfigurableOption[] options) {
- fCompilerOptions= options;
- }
- /**
* Sets the fingerprint for this state.
*/
protected void setFingerprint(byte[] fp) {
@@ -1868,7 +1850,7 @@ static Comparator getPathComparator() {
++i;
c= sig.charAt(i);
}
-
+
/* if its a class */
IType elementType;
if (c == 'L') {
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
index cb4834e103..c66bbdbd91 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
@@ -11,14 +11,13 @@ import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.eval.*;
import org.eclipse.jdt.internal.codeassist.ISelectionRequestor;
import org.eclipse.jdt.internal.codeassist.ICompletionRequestor;
-import org.eclipse.jdt.internal.compiler.ConfigurableOption;
-import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
-import org.eclipse.jdt.internal.compiler.IProblemFactory;
+import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.util.CharOperation;
import org.eclipse.jdt.internal.core.*;
import org.eclipse.jdt.internal.core.builder.impl.JavaBuilder;
import org.eclipse.jdt.internal.core.builder.impl.ProblemFactory;
+import org.eclipse.jdt.internal.core.ClassFile;
import org.eclipse.jdt.internal.eval.*;
import java.util.Locale;
@@ -66,7 +65,7 @@ public void codeComplete(String codeSnippet, int position, ICodeCompletionReques
position,
this.project.getSearchableNameEnvironment(),
new CompletionRequestorWrapper(requestor),
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions())
+ JavaModelManager.getOptions()
);
}
/**
@@ -80,7 +79,7 @@ public IJavaElement[] codeSelect(String codeSnippet, int offset, int length) thr
offset + length - 1,
this.project.getSearchableNameEnvironment(),
requestor,
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions())
+ JavaModelManager.getOptions()
);
return requestor.getElements();
}
@@ -204,7 +203,7 @@ protected INameEnvironment getBuildNameEnvironment() throws JavaModelException {
* Returns the compiler's configurable options.
*/
protected ConfigurableOption[] getCompilerOptions() throws JavaModelException {
- return JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
+ return JavaModelManager.getOptions();
}
/**
* @see org.eclipse.jdt.core.eval.IEvaluationContext#getImports
diff --git a/org.eclipse.jdt.core/plugin.jars b/org.eclipse.jdt.core/plugin.jars
new file mode 100644
index 0000000000..95b28d5d40
--- /dev/null
+++ b/org.eclipse.jdt.core/plugin.jars
@@ -0,0 +1,9 @@
+jdtcore.jar=\
+ Eclipse Java Ant Compiler,\
+ Eclipse Java Batch Compiler,\
+ Eclipse Java Code Assist,\
+ Eclipse Java Formatter,\
+ Eclipse Java Compiler,\
+ Eclipse Java Evaluation,\
+ Eclipse Java Core Search,\
+ Eclipse Java Model

Back to the top