Auto-cleanup of com.google.gwt.dev.jjs
- Sort, format, imports, auto-fixes, etc.
Review by: zundel@google.com
git-svn-id: https://google-web-toolkit.googlecode.com/svn/trunk@10031 8db76d5a-ed1c-0410-87a9-c151d255dfc7
diff --git a/dev/core/src/com/google/gwt/dev/jjs/AbstractCompiler.java b/dev/core/src/com/google/gwt/dev/jjs/AbstractCompiler.java
index 92e40b8..8f581e2 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/AbstractCompiler.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/AbstractCompiler.java
@@ -1,12 +1,12 @@
/*
* Copyright 2009 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -28,7 +28,7 @@
/**
* Performs a precompilation, returning an object that can then be used to
* compile individual permutations..
- *
+ *
* @param logger the logger to use
* @param module the module to compile
* @param rpo the RebindPermutationOracle
@@ -45,9 +45,8 @@
* @throws UnableToCompleteException if an error other than
* {@link OutOfMemoryError} occurs
*/
- UnifiedAst precompile(TreeLogger logger, ModuleDef module,
- RebindPermutationOracle rpo, String[] declEntryPts,
- String[] additionalRootTypes, JJSOptions options,
- boolean singlePermutation,
- PrecompilationMetricsArtifact precompilationMetrics) throws UnableToCompleteException;
+ UnifiedAst precompile(TreeLogger logger, ModuleDef module, RebindPermutationOracle rpo,
+ String[] declEntryPts, String[] additionalRootTypes, JJSOptions options,
+ boolean singlePermutation, PrecompilationMetricsArtifact precompilationMetrics)
+ throws UnableToCompleteException;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/Correlation.java b/dev/core/src/com/google/gwt/dev/jjs/Correlation.java
index 6ec5e64..87e8d16 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/Correlation.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/Correlation.java
@@ -71,7 +71,7 @@
* Specifies the type of literal value.
*/
public enum Literal {
- STRING("string"), CLASS("class");
+ CLASS("class"), STRING("string");
private final String description;
@@ -89,16 +89,17 @@
* limitations of mapping AST nodes into Strings, this Comparator may not
* always agree with {@link Correlation#equals(Object)}.
*/
- public static final Comparator<Correlation> AXIS_IDENT_COMPARATOR = new Comparator<Correlation>() {
- public int compare(Correlation a, Correlation b) {
- int r = a.axis.compareTo(b.axis);
- if (r != 0) {
- return r;
- }
+ public static final Comparator<Correlation> AXIS_IDENT_COMPARATOR =
+ new Comparator<Correlation>() {
+ public int compare(Correlation a, Correlation b) {
+ int r = a.axis.compareTo(b.axis);
+ if (r != 0) {
+ return r;
+ }
- return a.ident.compareTo(b.ident);
- }
- };
+ return a.ident.compareTo(b.ident);
+ }
+ };
/**
* This may contain a reference to either a Java or Js AST node.
@@ -136,8 +137,9 @@
}
Correlation c = (Correlation) obj;
- boolean astSame = astReference == c.astReference
- || (astReference != null && astReference.equals(c.astReference));
+ boolean astSame =
+ astReference == c.astReference
+ || (astReference != null && astReference.equals(c.astReference));
return axis == c.axis && astSame;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/CorrelationFactory.java b/dev/core/src/com/google/gwt/dev/jjs/CorrelationFactory.java
index e110f03..c8b99cb 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/CorrelationFactory.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/CorrelationFactory.java
@@ -88,13 +88,12 @@
* Correlations based on Literals are all the same, so we'll just cook up a
* Map to make {@link #by(Literal)} fast.
*/
- private static final Map<Literal, Correlation> LITERAL_CORRELATIONS = new EnumMap<Literal, Correlation>(
- Literal.class);
+ private static final Map<Literal, Correlation> LITERAL_CORRELATIONS =
+ new EnumMap<Literal, Correlation>(Literal.class);
static {
for (Literal l : Literal.values()) {
- LITERAL_CORRELATIONS.put(l,
- new Correlation(Axis.LITERAL, l.getDescription(), l));
+ LITERAL_CORRELATIONS.put(l, new Correlation(Axis.LITERAL, l.getDescription(), l));
}
}
@@ -114,8 +113,8 @@
* This cuts down on the total number of Correlation objects allocated.
*/
@SuppressWarnings("unchecked")
- private final Map<Object, Correlation> canonicalMap = Collections.synchronizedMap(new ReferenceMap(
- ReferenceMap.WEAK, ReferenceMap.WEAK));
+ private final Map<Object, Correlation> canonicalMap = Collections
+ .synchronizedMap(new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK));
private RealCorrelationFactory() {
}
@@ -134,8 +133,9 @@
public Correlation by(JField field) {
Correlation toReturn = canonicalMap.get(field);
if (toReturn == null) {
- toReturn = new Correlation(Axis.FIELD,
- field.getEnclosingType().getName() + "::" + field.getName(), field);
+ toReturn =
+ new Correlation(Axis.FIELD,
+ field.getEnclosingType().getName() + "::" + field.getName(), field);
canonicalMap.put(field, toReturn);
}
return toReturn;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/EnumNameObfuscator.java b/dev/core/src/com/google/gwt/dev/jjs/EnumNameObfuscator.java
index 147d5d8..2dd2af0 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/EnumNameObfuscator.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/EnumNameObfuscator.java
@@ -1,12 +1,12 @@
/*
* Copyright 2010 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -36,12 +36,12 @@
private static class EnumNameCallChecker extends JModVisitor {
- private final TreeLogger logger;
+ private final JDeclaredType classType;
private final JMethod enumNameMethod;
private final JMethod enumToStringMethod;
- private final JMethod enumValueOfMethod;
- private final JDeclaredType classType;
private final JDeclaredType enumType;
+ private final JMethod enumValueOfMethod;
+ private final TreeLogger logger;
private final JDeclaredType stringType;
public EnumNameCallChecker(JProgram jprogram, TreeLogger logger) {
@@ -51,26 +51,25 @@
this.classType = jprogram.getIndexedType("Class");
this.enumType = jprogram.getIndexedType("Enum");
this.stringType = jprogram.getIndexedType("String");
-
+
/*
* Find the correct version of enumValueOfMethod.
+ *
* Note: it doesn't work to check against a ref returned by
- * jprogram.getIndexedMethod("Enum.valueOf"), since there are
- * 2 different versions of Enum.valueOf in our jre emulation library,
- * and the indexed ref won't reliably flag the public instance, which
- * is the one we want here (i.e. Enum.valueOf(Class<T>,String)).
- * The other version is protected, but is called by the generated
- * constructors for sub-classes of Enum, and we don't want to warn for
- * those cases.
+ * jprogram.getIndexedMethod("Enum.valueOf"), since there are 2 different
+ * versions of Enum.valueOf in our jre emulation library, and the indexed
+ * ref won't reliably flag the public instance, which is the one we want
+ * here (i.e. Enum.valueOf(Class<T>,String)). The other version is
+ * protected, but is called by the generated constructors for sub-classes
+ * of Enum, and we don't want to warn for those cases.
*/
JMethod foundMethod = null;
List<JMethod> enumMethods = enumType.getMethods();
for (JMethod enumMethod : enumMethods) {
if ("valueOf".equals(enumMethod.getName())) {
List<JParameter> jParameters = enumMethod.getParams();
- if (jParameters.size() == 2 &&
- jParameters.get(0).getType() == classType &&
- jParameters.get(1).getType() == stringType) {
+ if (jParameters.size() == 2 && jParameters.get(0).getType() == classType
+ && jParameters.get(1).getType() == stringType) {
foundMethod = enumMethod;
break;
}
@@ -78,7 +77,7 @@
}
this.enumValueOfMethod = foundMethod;
}
-
+
@Override
public void endVisit(JMethodCall x, Context ctx) {
JMethod target = x.getTarget();
@@ -86,55 +85,53 @@
if (type instanceof JClassType) {
JClassType cType = (JClassType) type;
-
- if (target == enumNameMethod ||
- target == enumToStringMethod ||
- target == enumValueOfMethod) {
+
+ if (target == enumNameMethod || target == enumToStringMethod || target == enumValueOfMethod) {
warn(x);
} else if (cType.isEnumOrSubclass() != null) {
if ("valueOf".equals(target.getName())) {
/*
- * Check for calls to the auto-generated EnumSubType.valueOf(String).
- * Note, the check of the signature for the single String arg version
- * is to avoid flagging user-defined overloaded versions of the
- * method, which are presumably ok.
+ * Check for calls to the auto-generated
+ * EnumSubType.valueOf(String). Note, the check of the signature for
+ * the single String arg version is to avoid flagging user-defined
+ * overloaded versions of the method, which are presumably ok.
*/
List<JParameter> jParameters = target.getParams();
- if (jParameters.size() == 1 &&
- jParameters.get(0).getType() == stringType) {
+ if (jParameters.size() == 1 && jParameters.get(0).getType() == stringType) {
warn(x);
}
}
}
}
}
-
+
@Override
public boolean visit(JClassType x, Context ctx) {
if (x == enumType) {
- // don't traverse into Enum class itself, don't warn on internal method calls
+ // don't traverse into Enum class itself, don't warn on internal method
+ // calls
return false;
}
return true;
}
-
+
private void warn(JMethodCall x) {
- /* TODO: add a way to suppress warning with annotation if you know what
+ /*
+ * TODO: add a way to suppress warning with annotation if you know what
* you're doing.
*/
- logger.log(TreeLogger.WARN, "Call to Enum method "
- + x.getTarget().getName() + " when enum obfuscation is enabled: "
- + x.getSourceInfo().getFileName() + ":"
+ logger.log(TreeLogger.WARN, "Call to Enum method " + x.getTarget().getName()
+ + " when enum obfuscation is enabled: " + x.getSourceInfo().getFileName() + ":"
+ x.getSourceInfo().getStartLine());
}
}
private static class EnumNameReplacer extends JModVisitor {
- private final TreeLogger logger;
- private final JProgram jprogram;
private final JMethod enumObfuscatedName;
private final JClassType enumType;
+ private final JProgram jprogram;
+ private final TreeLogger logger;
public EnumNameReplacer(JProgram jprogram, TreeLogger logger) {
this.logger = logger;
@@ -146,20 +143,19 @@
@Override
public void endVisit(JReturnStatement x, Context ctx) {
info(x);
- JReturnStatement toReturn = new JReturnStatement(x.getSourceInfo(),
- new JMethodCall(x.getSourceInfo(),
- new JThisRef(x.getSourceInfo(),enumType), enumObfuscatedName));
+ JReturnStatement toReturn =
+ new JReturnStatement(x.getSourceInfo(), new JMethodCall(x.getSourceInfo(), new JThisRef(x
+ .getSourceInfo(), enumType), enumObfuscatedName));
ctx.replaceMe(toReturn);
}
public void exec() {
accept(jprogram.getIndexedMethod("Enum.name"));
}
-
+
private void info(JReturnStatement x) {
logger.log(TreeLogger.INFO, "Replacing Enum.name method : "
- + x.getSourceInfo().getFileName() + ":"
- + x.getSourceInfo().getStartLine());
+ + x.getSourceInfo().getFileName() + ":" + x.getSourceInfo().getStartLine());
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/InternalCompilerException.java b/dev/core/src/com/google/gwt/dev/jjs/InternalCompilerException.java
index 5e36ba3..b1168f6 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/InternalCompilerException.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/InternalCompilerException.java
@@ -59,7 +59,7 @@
}
/**
- * Returns the node's source info, if available; otherwise <code>null</code>.
+ * Returns the node's source info, if available; otherwise {@code null}.
*/
public SourceInfo getSourceInfo() {
return sourceInfo;
@@ -69,7 +69,8 @@
/**
* Tracks if there's a pending addNode() to avoid recursion sickness.
*/
- private static final ThreadLocal<InternalCompilerException> pendingICE = new ThreadLocal<InternalCompilerException>();
+ private static final ThreadLocal<InternalCompilerException> pendingICE =
+ new ThreadLocal<InternalCompilerException>();
/**
* Force this class to be preloaded. If we don't preload this class, we can
@@ -87,8 +88,7 @@
/**
* Constructs a new exception with the specified node, message, and cause.
*/
- public InternalCompilerException(HasSourceInfo node, String message,
- Throwable cause) {
+ public InternalCompilerException(HasSourceInfo node, String message, Throwable cause) {
this(message, cause);
addNode(node);
}
@@ -142,8 +142,7 @@
* Adds information about a a node to the end of the node trace. This is
* similar to how a stack trace works.
*/
- public void addNode(String className, String description,
- SourceInfo sourceInfo) {
+ public void addNode(String className, String description, SourceInfo sourceInfo) {
nodeTrace.add(new NodeInfo(className, description, sourceInfo));
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/JJSOptions.java b/dev/core/src/com/google/gwt/dev/jjs/JJSOptions.java
index 10bf933..74182e8 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/JJSOptions.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/JJSOptions.java
@@ -32,9 +32,7 @@
* Controls options for the {@link JavaToJavaScriptCompiler}.
*/
public interface JJSOptions extends OptionOptimize, OptionAggressivelyOptimize,
- OptionDisableClassMetadata, OptionDisableCastChecking,
- OptionEnableAssertions, OptionEnableGeneratorResultCaching,
- OptionRunAsyncEnabled, OptionScriptStyle,
- OptionSoycEnabled, OptionSoycDetailed, OptionOptimizePrecompile,
- OptionStrict {
+ OptionDisableClassMetadata, OptionDisableCastChecking, OptionEnableAssertions,
+ OptionEnableGeneratorResultCaching, OptionRunAsyncEnabled, OptionScriptStyle,
+ OptionSoycEnabled, OptionSoycDetailed, OptionOptimizePrecompile, OptionStrict {
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/JJSOptionsImpl.java b/dev/core/src/com/google/gwt/dev/jjs/JJSOptionsImpl.java
index 322915a..b34cd1c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/JJSOptionsImpl.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/JJSOptionsImpl.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -25,18 +25,18 @@
public class JJSOptionsImpl implements JJSOptions, Serializable {
private boolean aggressivelyOptimize = true;
+ private boolean compilerMetricsEnabled = false;
private boolean disableCastChecking = false;
private boolean disableClassMetadata = false;
private boolean enableAssertions;
private boolean enableGeneratorResultCaching = false;
+ private int optimizationLevel = OptionOptimize.OPTIMIZE_LEVEL_MAX;
private boolean optimizePrecompile = false;
private JsOutputOption output = JsOutputOption.OBFUSCATED;
private boolean runAsyncEnabled = true;
private boolean soycEnabled = false;
private boolean soycExtra = false;
private boolean strict = false;
- private int optimizationLevel = OptionOptimize.OPTIMIZE_LEVEL_MAX;
- private boolean compilerMetricsEnabled = false;
public JJSOptionsImpl() {
}
@@ -91,7 +91,7 @@
public boolean isEnableAssertions() {
return enableAssertions;
}
-
+
public boolean isGeneratorResultCachingEnabled() {
return enableGeneratorResultCaching;
}
@@ -135,7 +135,7 @@
public void setEnableAssertions(boolean enableAssertions) {
this.enableAssertions = enableAssertions;
}
-
+
public void setGeneratorResultCachingEnabled(boolean enabled) {
this.enableGeneratorResultCaching = enabled;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/JavaScriptCompiler.java b/dev/core/src/com/google/gwt/dev/jjs/JavaScriptCompiler.java
index e3fe2b2..305f27c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/JavaScriptCompiler.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/JavaScriptCompiler.java
@@ -1,12 +1,12 @@
/*
* Copyright 2009 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -26,14 +26,11 @@
*/
public class JavaScriptCompiler implements AbstractCompiler {
- public UnifiedAst precompile(TreeLogger logger, ModuleDef module,
- RebindPermutationOracle rpo, String[] declEntryPts,
- String[] additionalRootTypes, JJSOptions options,
- boolean singlePermutation,
- PrecompilationMetricsArtifact precompilationMetrics)
+ public UnifiedAst precompile(TreeLogger logger, ModuleDef module, RebindPermutationOracle rpo,
+ String[] declEntryPts, String[] additionalRootTypes, JJSOptions options,
+ boolean singlePermutation, PrecompilationMetricsArtifact precompilationMetrics)
throws UnableToCompleteException {
- return JavaToJavaScriptCompiler.precompile(logger, module, rpo,
- declEntryPts, additionalRootTypes, options, singlePermutation,
- precompilationMetrics);
+ return JavaToJavaScriptCompiler.precompile(logger, module, rpo, declEntryPts,
+ additionalRootTypes, options, singlePermutation, precompilationMetrics);
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/JavaToJavaScriptCompiler.java b/dev/core/src/com/google/gwt/dev/jjs/JavaToJavaScriptCompiler.java
index 60d889f..0c19f94 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/JavaToJavaScriptCompiler.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/JavaToJavaScriptCompiler.java
@@ -172,12 +172,12 @@
private static class PermutationResultImpl implements PermutationResult {
private final ArtifactSet artifacts = new ArtifactSet();
private final byte[][] js;
- private Permutation permutation;
+ private final Permutation permutation;
private final byte[] serializedSymbolMap;
private final StatementRanges[] statementRanges;
- public PermutationResultImpl(String[] js, Permutation permutation,
- SymbolData[] symbolMap, StatementRanges[] statementRanges) {
+ public PermutationResultImpl(String[] js, Permutation permutation, SymbolData[] symbolMap,
+ StatementRanges[] statementRanges) {
byte[][] bytes = new byte[js.length][];
for (int i = 0; i < js.length; ++i) {
bytes[i] = Util.getBytes(js[i]);
@@ -189,8 +189,7 @@
Util.writeObjectToStream(baos, (Object) symbolMap);
this.serializedSymbolMap = baos.toByteArray();
} catch (IOException e) {
- throw new RuntimeException("Should never happen with in-memory stream",
- e);
+ throw new RuntimeException("Should never happen with in-memory stream", e);
}
this.statementRanges = statementRanges;
}
@@ -247,21 +246,19 @@
* @throws UnableToCompleteException if an error other than
* {@link OutOfMemoryError} occurs
*/
- public static PermutationResult compilePermutation(TreeLogger logger,
- UnifiedAst unifiedAst, Permutation permutation)
- throws UnableToCompleteException {
+ public static PermutationResult compilePermutation(TreeLogger logger, UnifiedAst unifiedAst,
+ Permutation permutation) throws UnableToCompleteException {
JJSOptions options = unifiedAst.getOptions();
long startTimeMilliseconds = System.currentTimeMillis();
- Event jjsCompilePermutationEvent = SpeedTracerLogger.start(
- CompilerEventType.JJS_COMPILE_PERMUTATION, "name",
- permutation.prettyPrint());
+ Event jjsCompilePermutationEvent =
+ SpeedTracerLogger.start(CompilerEventType.JJS_COMPILE_PERMUTATION, "name", permutation
+ .prettyPrint());
InternalCompilerException.preload();
PropertyOracle[] propertyOracles = permutation.getPropertyOracles();
int permutationId = permutation.getId();
- logger.log(TreeLogger.INFO, "Compiling permutation " + permutationId
- + "...");
+ logger.log(TreeLogger.INFO, "Compiling permutation " + permutationId + "...");
long permStart = System.currentTimeMillis();
try {
if (JProgram.isTracingEnabled()) {
@@ -275,8 +272,8 @@
JProgram jprogram = ast.getJProgram();
JsProgram jsProgram = ast.getJsProgram();
- Map<StandardSymbolData, JsName> symbolTable = new TreeMap<StandardSymbolData, JsName>(
- new SymbolData.ClassIdentComparator());
+ Map<StandardSymbolData, JsName> symbolTable =
+ new TreeMap<StandardSymbolData, JsName>(new SymbolData.ClassIdentComparator());
ResolveRebinds.exec(jprogram, permutation.getOrderedRebindAnswers());
@@ -308,8 +305,9 @@
// (7) Generate a JavaScript code DOM from the Java type declarations
jprogram.typeOracle.recomputeAfterOptimizations();
- JavaToJavaScriptMap jjsmap = GenerateJavaScriptAST.exec(jprogram,
- jsProgram, options.getOutput(), symbolTable, propertyOracles);
+ JavaToJavaScriptMap jjsmap =
+ GenerateJavaScriptAST.exec(jprogram, jsProgram, options.getOutput(), symbolTable,
+ propertyOracles);
// (8) Normalize the JS AST.
// Fix invalid constructs created during JS AST gen.
@@ -345,14 +343,15 @@
SyntheticArtifact dependencies = null;
if (options.isRunAsyncEnabled()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- CodeSplitter.exec(logger, jprogram, jsProgram, jjsmap,
- chooseDependencyRecorder(options.isSoycEnabled(), baos));
+ CodeSplitter.exec(logger, jprogram, jsProgram, jjsmap, chooseDependencyRecorder(options
+ .isSoycEnabled(), baos));
if (baos.size() == 0 && options.isSoycEnabled()) {
recordNonSplitDependencies(jprogram, baos);
}
if (baos.size() > 0) {
- dependencies = new SyntheticArtifact(SoycReportLinker.class,
- "dependencies" + permutationId + ".xml.gz", baos.toByteArray());
+ dependencies =
+ new SyntheticArtifact(SoycReportLinker.class, "dependencies" + permutationId
+ + ".xml.gz", baos.toByteArray());
}
}
@@ -360,8 +359,7 @@
boolean isIE6orUnknown = false;
for (PropertyOracle oracle : propertyOracles) {
try {
- SelectionProperty userAgentProperty = oracle.getSelectionProperty(
- logger, "user.agent");
+ SelectionProperty userAgentProperty = oracle.getSelectionProperty(logger, "user.agent");
if ("ie6".equals(userAgentProperty.getCurrentValue())) {
isIE6orUnknown = true;
break;
@@ -384,8 +382,7 @@
boolean changed = false;
for (int i = 0; i < jsProgram.getFragmentCount(); i++) {
JsBlock fragment = jsProgram.getFragmentBlock(i);
- changed = JsDuplicateFunctionRemover.exec(jsProgram, fragment)
- || changed;
+ changed = JsDuplicateFunctionRemover.exec(jsProgram, fragment) || changed;
}
if (changed) {
JsUnusedFunctionRemover.exec(jsProgram);
@@ -426,16 +423,16 @@
// (12) Generate the final output text.
String[] js = new String[jsProgram.getFragmentCount()];
StatementRanges[] ranges = new StatementRanges[js.length];
- SizeBreakdown[] sizeBreakdowns = options.isSoycEnabled()
- || options.isCompilerMetricsEnabled() ? new SizeBreakdown[js.length]
- : null;
- List<Map<Range, SourceInfo>> sourceInfoMaps = options.isSoycExtra()
- ? new ArrayList<Map<Range, SourceInfo>>() : null;
- generateJavaScriptCode(options, jsProgram, jjsmap, js, ranges,
- sizeBreakdowns, sourceInfoMaps, splitBlocks);
+ SizeBreakdown[] sizeBreakdowns =
+ options.isSoycEnabled() || options.isCompilerMetricsEnabled()
+ ? new SizeBreakdown[js.length] : null;
+ List<Map<Range, SourceInfo>> sourceInfoMaps =
+ options.isSoycExtra() ? new ArrayList<Map<Range, SourceInfo>>() : null;
+ generateJavaScriptCode(options, jsProgram, jjsmap, js, ranges, sizeBreakdowns,
+ sourceInfoMaps, splitBlocks);
- PermutationResult toReturn = new PermutationResultImpl(js, permutation,
- makeSymbolMap(symbolTable), ranges);
+ PermutationResult toReturn =
+ new PermutationResultImpl(js, permutation, makeSymbolMap(symbolTable), ranges);
CompilationMetricsArtifact compilationMetrics = null;
if (options.isCompilerMetricsEnabled()) {
compilationMetrics = new CompilationMetricsArtifact(permutation.getId());
@@ -445,18 +442,16 @@
- ManagementFactory.getRuntimeMXBean().getStartTime());
compilationMetrics.setJsSize(sizeBreakdowns);
compilationMetrics.setPermutationDescription(permutation.prettyPrint());
- toReturn.addArtifacts(Lists.create(unifiedAst.getModuleMetrics(),
- unifiedAst.getPrecompilationMetrics(), compilationMetrics));
+ toReturn.addArtifacts(Lists.create(unifiedAst.getModuleMetrics(), unifiedAst
+ .getPrecompilationMetrics(), compilationMetrics));
}
- toReturn.addArtifacts(makeSoycArtifacts(logger, permutationId, jprogram,
- js, sizeBreakdowns, sourceInfoMaps, dependencies, jjsmap,
- obfuscateMap, unifiedAst.getModuleMetrics(),
+ toReturn.addArtifacts(makeSoycArtifacts(logger, permutationId, jprogram, js, sizeBreakdowns,
+ sourceInfoMaps, dependencies, jjsmap, obfuscateMap, unifiedAst.getModuleMetrics(),
unifiedAst.getPrecompilationMetrics(), compilationMetrics));
logTrackingStats(logger);
- logger.log(TreeLogger.TRACE,
- "Permutation took " + (System.currentTimeMillis() - permStart)
- + " ms");
+ logger.log(TreeLogger.TRACE, "Permutation took " + (System.currentTimeMillis() - permStart)
+ + " ms");
return toReturn;
} catch (Throwable e) {
throw logAndTranslateException(logger, e);
@@ -466,11 +461,10 @@
}
public static UnifiedAst precompile(TreeLogger logger, ModuleDef module,
- RebindPermutationOracle rpo, String[] declEntryPts,
- String[] additionalRootTypes, JJSOptions options,
- boolean singlePermutation) throws UnableToCompleteException {
- return precompile(logger, module, rpo, declEntryPts, additionalRootTypes,
- options, singlePermutation, null);
+ RebindPermutationOracle rpo, String[] declEntryPts, String[] additionalRootTypes,
+ JJSOptions options, boolean singlePermutation) throws UnableToCompleteException {
+ return precompile(logger, module, rpo, declEntryPts, additionalRootTypes, options,
+ singlePermutation, null);
}
/**
@@ -493,11 +487,9 @@
* {@link OutOfMemoryError} occurs
*/
public static UnifiedAst precompile(TreeLogger logger, ModuleDef module,
- RebindPermutationOracle rpo, String[] declEntryPts,
- String[] additionalRootTypes, JJSOptions options,
- boolean singlePermutation,
- PrecompilationMetricsArtifact precompilationMetrics)
- throws UnableToCompleteException {
+ RebindPermutationOracle rpo, String[] declEntryPts, String[] additionalRootTypes,
+ JJSOptions options, boolean singlePermutation,
+ PrecompilationMetricsArtifact precompilationMetrics) throws UnableToCompleteException {
InternalCompilerException.preload();
@@ -524,15 +516,16 @@
Memory.maybeDumpMemory("CompStateBuilt");
// Compile the source and get the compiler so we can get the parse tree
- CompilationUnitDeclaration[] goldenCuds = WebModeCompilerFrontEnd.getCompilationUnitDeclarations(
- logger, allRootTypes.toArray(new String[allRootTypes.size()]), rpo,
- TypeLinker.NULL_TYPE_LINKER).compiledUnits;
+ CompilationUnitDeclaration[] goldenCuds =
+ WebModeCompilerFrontEnd.getCompilationUnitDeclarations(logger, allRootTypes
+ .toArray(new String[allRootTypes.size()]), rpo, TypeLinker.NULL_TYPE_LINKER).compiledUnits;
List<String> finalTypeOracleTypes = Lists.create();
if (precompilationMetrics != null) {
- for (com.google.gwt.core.ext.typeinfo.JClassType type : rpo.getCompilationState().getTypeOracle().getTypes()) {
- finalTypeOracleTypes = Lists.add(finalTypeOracleTypes,
- type.getPackage().getName() + "." + type.getName());
+ for (com.google.gwt.core.ext.typeinfo.JClassType type : rpo.getCompilationState()
+ .getTypeOracle().getTypes()) {
+ finalTypeOracleTypes =
+ Lists.add(finalTypeOracleTypes, type.getPackage().getName() + "." + type.getName());
}
precompilationMetrics.setFinalTypeOracleTypes(finalTypeOracleTypes);
}
@@ -545,8 +538,8 @@
// found here will have already been logged by AbstractCompiler.
checkForErrors(logger, goldenCuds, false);
- CorrelationFactory correlator = options.isSoycExtra()
- ? RealCorrelationFactory.INSTANCE : DummyCorrelationFactory.INSTANCE;
+ CorrelationFactory correlator =
+ options.isSoycExtra() ? RealCorrelationFactory.INSTANCE : DummyCorrelationFactory.INSTANCE;
JProgram jprogram = new JProgram(correlator);
JsProgram jsProgram = new JsProgram(correlator);
@@ -557,8 +550,7 @@
* all JSNI.
*/
TypeMap typeMap = new TypeMap(jprogram);
- TypeDeclaration[] allTypeDeclarations = BuildTypeMap.exec(typeMap,
- goldenCuds, jsProgram);
+ TypeDeclaration[] allTypeDeclarations = BuildTypeMap.exec(typeMap, goldenCuds, jsProgram);
// BuildTypeMap can uncover syntactic JSNI errors; report & abort
checkForErrors(logger, goldenCuds, true);
@@ -584,8 +576,8 @@
// See if we should run the EnumNameObfuscator
if (module != null) {
- ConfigurationProperty enumNameObfuscationProp = (ConfigurationProperty) module.getProperties().find(
- ENUM_NAME_OBFUSCATION_PROPERTY);
+ ConfigurationProperty enumNameObfuscationProp =
+ (ConfigurationProperty) module.getProperties().find(ENUM_NAME_OBFUSCATION_PROPERTY);
if (enumNameObfuscationProp != null
&& Boolean.parseBoolean(enumNameObfuscationProp.getValue())) {
EnumNameObfuscator.exec(jprogram, logger);
@@ -613,15 +605,14 @@
// Fix up GWT.runAsync()
if (module != null && options.isRunAsyncEnabled()) {
ReplaceRunAsyncs.exec(logger, jprogram);
- CodeSplitter.pickInitialLoadSequence(logger, jprogram,
- module.getProperties());
+ CodeSplitter.pickInitialLoadSequence(logger, jprogram, module.getProperties());
}
// Resolve entry points, rebinding non-static entry points.
findEntryPoints(logger, rpo, declEntryPts, jprogram);
ImplementClassLiteralsAsFields.exec(jprogram);
-
+
/*
* 4) Possibly optimize some.
*
@@ -661,8 +652,8 @@
logTrackingStats(logger);
Event createUnifiedAstEvent = SpeedTracerLogger.start(CompilerEventType.CREATE_UNIFIED_AST);
- UnifiedAst result = new UnifiedAst(options, new AST(jprogram, jsProgram),
- singlePermutation, rebindRequests);
+ UnifiedAst result =
+ new UnifiedAst(options, new AST(jprogram, jsProgram), singlePermutation, rebindRequests);
createUnifiedAstEvent.end();
return result;
} catch (Throwable e) {
@@ -684,8 +675,7 @@
draftOptimizeEvent.end();
}
- protected static void optimize(JJSOptions options, JProgram jprogram)
- throws InterruptedException {
+ protected static void optimize(JJSOptions options, JProgram jprogram) throws InterruptedException {
Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE);
List<OptimizerStats> allOptimizerStats = new ArrayList<OptimizerStats>();
@@ -693,8 +683,7 @@
int optimizationLevel = options.getOptimizationLevel();
while (true) {
counter++;
- if (optimizationLevel < OptionOptimize.OPTIMIZE_LEVEL_MAX
- && counter > optimizationLevel) {
+ if (optimizationLevel < OptionOptimize.OPTIMIZE_LEVEL_MAX && counter > optimizationLevel) {
break;
}
if (Thread.interrupted()) {
@@ -702,8 +691,8 @@
throw new InterruptedException();
}
AstDumper.maybeDumpAST(jprogram);
- OptimizerStats stats = optimizeLoop("Pass " + counter, jprogram,
- options.isAggressivelyOptimize());
+ OptimizerStats stats =
+ optimizeLoop("Pass " + counter, jprogram, options.isAggressivelyOptimize());
allOptimizerStats.add(stats);
if (!stats.didChange()) {
break;
@@ -768,15 +757,13 @@
}
}
- protected static OptimizerStats optimizeLoop(String passName,
- JProgram jprogram, boolean isAggressivelyOptimize) {
- Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "phase", "loop");
+ protected static OptimizerStats optimizeLoop(String passName, JProgram jprogram,
+ boolean isAggressivelyOptimize) {
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "phase", "loop");
// Count the number of nodes in the AST so we can measure the efficiency of
// the optimizers.
- Event countEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "phase", "countNodes");
+ Event countEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "phase", "countNodes");
TreeStatistics treeStats = new TreeStatistics();
treeStats.accept(jprogram);
int numNodes = treeStats.getNodeCount();
@@ -816,8 +803,7 @@
if (isAggressivelyOptimize) {
// remove same parameters value
- stats.add(SameParameterValueOptimizer.exec(jprogram).recordVisits(
- numNodes));
+ stats.add(SameParameterValueOptimizer.exec(jprogram).recordVisits(numNodes));
/*
* Enum ordinalization.
@@ -840,15 +826,14 @@
* console.
*
* @param logger logger to use for compilation errors
- * @param cuds compiled units to analyze for errors.
+ * @param cuds compiled units to analyze for errors.
* @param itemizeErrors log each error or simply log one message if the build
* failed.
* @throws UnableToCompleteException if a compilation error is found in the
* cuds argument.
*/
- static void checkForErrors(TreeLogger logger,
- CompilationUnitDeclaration[] cuds, boolean itemizeErrors)
- throws UnableToCompleteException {
+ static void checkForErrors(TreeLogger logger, CompilationUnitDeclaration[] cuds,
+ boolean itemizeErrors) throws UnableToCompleteException {
Event checkForErrorsEvent = SpeedTracerLogger.start(CompilerEventType.CHECK_FOR_ERRORS);
boolean compilationFailed = false;
if (cuds.length == 0) {
@@ -873,14 +858,13 @@
}
checkForErrorsEvent.end();
if (compilationFailed) {
- logger.log(TreeLogger.ERROR, "Cannot proceed due to previous errors",
- null);
+ logger.log(TreeLogger.ERROR, "Cannot proceed due to previous errors", null);
throw new UnableToCompleteException();
}
}
- private static MultipleDependencyGraphRecorder chooseDependencyRecorder(
- boolean soycEnabled, OutputStream out) {
+ private static MultipleDependencyGraphRecorder chooseDependencyRecorder(boolean soycEnabled,
+ OutputStream out) {
MultipleDependencyGraphRecorder dependencyRecorder = CodeSplitter.NULL_RECORDER;
if (soycEnabled) {
dependencyRecorder = new DependencyRecorder(out);
@@ -889,18 +873,18 @@
}
private static JMethodCall createReboundModuleLoad(TreeLogger logger,
- JDeclaredType reboundEntryType, String originalMainClassName,
- JDeclaredType enclosingType) throws UnableToCompleteException {
+ JDeclaredType reboundEntryType, String originalMainClassName, JDeclaredType enclosingType)
+ throws UnableToCompleteException {
if (!(reboundEntryType instanceof JClassType)) {
- logger.log(TreeLogger.ERROR, "Module entry point class '"
- + originalMainClassName + "' must be a class", null);
+ logger.log(TreeLogger.ERROR, "Module entry point class '" + originalMainClassName
+ + "' must be a class", null);
throw new UnableToCompleteException();
}
JClassType entryClass = (JClassType) reboundEntryType;
if (entryClass.isAbstract()) {
- logger.log(TreeLogger.ERROR, "Module entry point class '"
- + originalMainClassName + "' must not be abstract", null);
+ logger.log(TreeLogger.ERROR, "Module entry point class '" + originalMainClassName
+ + "' must not be abstract", null);
throw new UnableToCompleteException();
}
@@ -913,39 +897,34 @@
}
if (entryMethod.isAbstract()) {
- logger.log(TreeLogger.ERROR,
- "Entry method 'onModuleLoad' in entry point class '"
- + originalMainClassName + "' must not be abstract", null);
+ logger.log(TreeLogger.ERROR, "Entry method 'onModuleLoad' in entry point class '"
+ + originalMainClassName + "' must not be abstract", null);
throw new UnableToCompleteException();
}
SourceInfo sourceInfo = entryClass.getSourceInfo();
JExpression qualifier = null;
if (!entryMethod.isStatic()) {
- qualifier = JGwtCreate.createInstantiationExpression(sourceInfo,
- entryClass, enclosingType);
+ qualifier = JGwtCreate.createInstantiationExpression(sourceInfo, entryClass, enclosingType);
if (qualifier == null) {
- logger.log(
- TreeLogger.ERROR,
+ logger.log(TreeLogger.ERROR,
"No default (zero argument) constructor could be found in entry point class '"
+ originalMainClassName
- + "' to qualify a call to non-static entry method 'onModuleLoad'",
- null);
+ + "' to qualify a call to non-static entry method 'onModuleLoad'", null);
throw new UnableToCompleteException();
}
}
return new JMethodCall(sourceInfo, qualifier, entryMethod);
}
- private static void findEntryPoints(TreeLogger logger,
- RebindPermutationOracle rpo, String[] mainClassNames, JProgram program)
- throws UnableToCompleteException {
+ private static void findEntryPoints(TreeLogger logger, RebindPermutationOracle rpo,
+ String[] mainClassNames, JProgram program) throws UnableToCompleteException {
Event findEntryPointsEvent = SpeedTracerLogger.start(CompilerEventType.FIND_ENTRY_POINTS);
SourceInfo sourceInfo = program.createSourceInfoSynthetic(JavaToJavaScriptCompiler.class);
- JMethod bootStrapMethod = program.createMethod(sourceInfo, "init",
- program.getIndexedType("EntryMethodHolder"), program.getTypeVoid(),
- false, true, true, false, false);
+ JMethod bootStrapMethod =
+ program.createMethod(sourceInfo, "init", program.getIndexedType("EntryMethodHolder"),
+ program.getTypeVoid(), false, true, true, false, false);
bootStrapMethod.freezeParamTypes();
bootStrapMethod.setSynthetic();
@@ -961,9 +940,8 @@
JDeclaredType mainType = program.getFromTypeMap(mainClassName);
if (mainType == null) {
- logger.log(TreeLogger.ERROR,
- "Could not find module entry point class '" + mainClassName + "'",
- null);
+ logger.log(TreeLogger.ERROR, "Could not find module entry point class '" + mainClassName
+ + "'", null);
throw new UnableToCompleteException();
}
@@ -975,29 +953,28 @@
}
// Couldn't find a static main method; must rebind the class
- String[] resultTypeNames = rpo.getAllPossibleRebindAnswers(logger,
- mainClassName);
+ String[] resultTypeNames = rpo.getAllPossibleRebindAnswers(logger, mainClassName);
List<JClassType> resultTypes = new ArrayList<JClassType>();
List<JExpression> entryCalls = new ArrayList<JExpression>();
for (String resultTypeName : resultTypeNames) {
JDeclaredType resultType = program.getFromTypeMap(resultTypeName);
if (resultType == null) {
- logger.log(TreeLogger.ERROR,
- "Could not find module entry point class '" + resultTypeName
- + "' after rebinding from '" + mainClassName + "'", null);
+ logger.log(TreeLogger.ERROR, "Could not find module entry point class '" + resultTypeName
+ + "' after rebinding from '" + mainClassName + "'", null);
throw new UnableToCompleteException();
}
- JMethodCall onModuleLoadCall = createReboundModuleLoad(logger,
- resultType, mainClassName, bootStrapMethod.getEnclosingType());
+ JMethodCall onModuleLoadCall =
+ createReboundModuleLoad(logger, resultType, mainClassName, bootStrapMethod
+ .getEnclosingType());
resultTypes.add((JClassType) resultType);
entryCalls.add(onModuleLoadCall);
}
if (resultTypes.size() == 1) {
block.addStmt(entryCalls.get(0).makeStatement());
} else {
- JReboundEntryPoint reboundEntryPoint = new JReboundEntryPoint(
- mainType.getSourceInfo(), mainType, resultTypes, entryCalls);
+ JReboundEntryPoint reboundEntryPoint =
+ new JReboundEntryPoint(mainType.getSourceInfo(), mainType, resultTypes, entryCalls);
block.addStmt(reboundEntryPoint);
}
}
@@ -1042,13 +1019,12 @@
* JavaScript
* @param splitBlocks true if current permutation is for IE6 or unknown
*/
- private static void generateJavaScriptCode(JJSOptions options,
- JsProgram jsProgram, JavaToJavaScriptMap jjsMap, String[] js,
- StatementRanges[] ranges, SizeBreakdown[] sizeBreakdowns,
- List<Map<Range, SourceInfo>> sourceInfoMaps, boolean splitBlocks) {
+ private static void generateJavaScriptCode(JJSOptions options, JsProgram jsProgram,
+ JavaToJavaScriptMap jjsMap, String[] js, StatementRanges[] ranges,
+ SizeBreakdown[] sizeBreakdowns, List<Map<Range, SourceInfo>> sourceInfoMaps,
+ boolean splitBlocks) {
for (int i = 0; i < js.length; i++) {
- DefaultTextOutput out = new DefaultTextOutput(
- options.getOutput().shouldMinimize());
+ DefaultTextOutput out = new DefaultTextOutput(options.getOutput().shouldMinimize());
JsSourceGenerationVisitorWithSizeBreakdown v;
if (sourceInfoMaps != null) {
v = new JsReportGenerationVisitor(out, jjsMap);
@@ -1062,17 +1038,15 @@
* the top level blocks into sub-blocks if they exceed 32767 statements.
*/
Event functionClusterEvent = SpeedTracerLogger.start(CompilerEventType.FUNCTION_CLUSTER);
- JsFunctionClusterer clusterer = new JsFunctionClusterer(out.toString(),
- v.getStatementRanges());
+ JsFunctionClusterer clusterer =
+ new JsFunctionClusterer(out.toString(), v.getStatementRanges());
// only cluster for obfuscated mode
- if (options.isAggressivelyOptimize()
- && options.getOutput() == JsOutputOption.OBFUSCATED) {
+ if (options.isAggressivelyOptimize() && options.getOutput() == JsOutputOption.OBFUSCATED) {
clusterer.exec();
}
functionClusterEvent.end();
// rewrite top-level blocks to limit the number of statements
- JsIEBlockTextTransformer ieXformer = new JsIEBlockTextTransformer(
- clusterer);
+ JsIEBlockTextTransformer ieXformer = new JsIEBlockTextTransformer(clusterer);
if (splitBlocks) {
ieXformer.exec();
}
@@ -1108,14 +1082,13 @@
return v.classNames.toArray(new String[v.classNames.size()]);
}
- private static UnableToCompleteException logAndTranslateException(
- TreeLogger logger, Throwable e) {
+ private static UnableToCompleteException logAndTranslateException(TreeLogger logger, Throwable e) {
if (e instanceof UnableToCompleteException) {
// just rethrow
return (UnableToCompleteException) e;
} else if (e instanceof InternalCompilerException) {
- TreeLogger topBranch = logger.branch(TreeLogger.ERROR,
- "An internal compiler exception occurred", e);
+ TreeLogger topBranch =
+ logger.branch(TreeLogger.ERROR, "An internal compiler exception occurred", e);
List<NodeInfo> nodeTrace = ((InternalCompilerException) e).getNodeTrace();
for (NodeInfo nodeInfo : nodeTrace) {
SourceInfo info = nodeInfo.getSourceInfo();
@@ -1152,8 +1125,9 @@
}
/*
- * This method is intended as a central location for producing optional tracking output.
- * This will be called after all optimization/normalization passes have completed.
+ * This method is intended as a central location for producing optional
+ * tracking output. This will be called after all optimization/normalization
+ * passes have completed.
*/
private static void logTrackingStats(TreeLogger logger) {
EnumOrdinalizer.Tracker eot = EnumOrdinalizer.getTracker();
@@ -1162,16 +1136,13 @@
}
}
- private static Collection<? extends Artifact<?>> makeSoycArtifacts(
- TreeLogger logger, int permutationId, JProgram jprogram, String[] js,
- SizeBreakdown[] sizeBreakdowns,
- List<Map<Range, SourceInfo>> sourceInfoMaps,
- SyntheticArtifact dependencies, JavaToJavaScriptMap jjsmap,
- Map<JsName, String> obfuscateMap,
+ private static Collection<? extends Artifact<?>> makeSoycArtifacts(TreeLogger logger,
+ int permutationId, JProgram jprogram, String[] js, SizeBreakdown[] sizeBreakdowns,
+ List<Map<Range, SourceInfo>> sourceInfoMaps, SyntheticArtifact dependencies,
+ JavaToJavaScriptMap jjsmap, Map<JsName, String> obfuscateMap,
ModuleMetricsArtifact moduleMetricsArtifact,
PrecompilationMetricsArtifact precompilationMetricsArtifact,
- CompilationMetricsArtifact compilationMetrics) throws IOException,
- UnableToCompleteException {
+ CompilationMetricsArtifact compilationMetrics) throws IOException, UnableToCompleteException {
Memory.maybeDumpMemory("makeSoycArtifactsStart");
List<SyntheticArtifact> soycArtifacts = new ArrayList<SyntheticArtifact>();
@@ -1179,35 +1150,36 @@
Event soycEvent = SpeedTracerLogger.start(CompilerEventType.MAKE_SOYC_ARTIFACTS);
- Event recordSplitPoints = SpeedTracerLogger.start(
- CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSplitPoints");
+ Event recordSplitPoints =
+ SpeedTracerLogger
+ .start(CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSplitPoints");
SplitPointRecorder.recordSplitPoints(jprogram, baos, logger);
- SyntheticArtifact splitPoints = new SyntheticArtifact(
- SoycReportLinker.class, "splitPoints" + permutationId + ".xml.gz",
- baos.toByteArray());
+ SyntheticArtifact splitPoints =
+ new SyntheticArtifact(SoycReportLinker.class, "splitPoints" + permutationId + ".xml.gz",
+ baos.toByteArray());
soycArtifacts.add(splitPoints);
recordSplitPoints.end();
SyntheticArtifact sizeMaps = null;
if (sizeBreakdowns != null) {
- Event recordSizeMap = SpeedTracerLogger.start(
- CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSizeMap");
+ Event recordSizeMap =
+ SpeedTracerLogger.start(CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSizeMap");
baos.reset();
- SizeMapRecorder.recordMap(logger, baos, sizeBreakdowns, jjsmap,
- obfuscateMap);
- sizeMaps = new SyntheticArtifact(SoycReportLinker.class, "stories"
- + permutationId + ".xml.gz", baos.toByteArray());
+ SizeMapRecorder.recordMap(logger, baos, sizeBreakdowns, jjsmap, obfuscateMap);
+ sizeMaps =
+ new SyntheticArtifact(SoycReportLinker.class, "stories" + permutationId + ".xml.gz", baos
+ .toByteArray());
soycArtifacts.add(sizeMaps);
recordSizeMap.end();
}
if (sourceInfoMaps != null) {
- Event recordStories = SpeedTracerLogger.start(
- CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordStories");
+ Event recordStories =
+ SpeedTracerLogger.start(CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordStories");
baos.reset();
StoryRecorder.recordStories(logger, baos, sourceInfoMaps, js);
- soycArtifacts.add(new SyntheticArtifact(SoycReportLinker.class,
- "detailedStories" + permutationId + ".xml.gz", baos.toByteArray()));
+ soycArtifacts.add(new SyntheticArtifact(SoycReportLinker.class, "detailedStories"
+ + permutationId + ".xml.gz", baos.toByteArray()));
recordStories.end();
}
@@ -1221,9 +1193,9 @@
}
if (sizeBreakdowns != null) {
- Event generateCompileReport = SpeedTracerLogger.start(
- CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase",
- "generateCompileReport");
+ Event generateCompileReport =
+ SpeedTracerLogger.start(CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase",
+ "generateCompileReport");
ArtifactsOutputDirectory outDir = new ArtifactsOutputDirectory();
SoycDashboard dashboard = new SoycDashboard(outDir);
dashboard.startNewPermutation(Integer.toString(permutationId));
@@ -1238,20 +1210,16 @@
Memory.maybeDumpMemory("soycReadDependenciesEnd");
} catch (ParserConfigurationException e) {
throw new InternalCompilerException(
- "Error reading compile report information that was just generated",
- e);
+ "Error reading compile report information that was just generated", e);
} catch (SAXException e) {
throw new InternalCompilerException(
- "Error reading compile report information that was just generated",
- e);
+ "Error reading compile report information that was just generated", e);
}
dashboard.generateForOnePermutation();
- if (moduleMetricsArtifact != null
- && precompilationMetricsArtifact != null
+ if (moduleMetricsArtifact != null && precompilationMetricsArtifact != null
&& compilationMetrics != null) {
- dashboard.generateCompilerMetricsForOnePermuation(
- moduleMetricsArtifact, precompilationMetricsArtifact,
- compilationMetrics);
+ dashboard.generateCompilerMetricsForOnePermuation(moduleMetricsArtifact,
+ precompilationMetricsArtifact, compilationMetrics);
}
soycArtifacts.addAll(outDir.getArtifacts());
generateCompileReport.end();
@@ -1270,27 +1238,23 @@
* Stats.onModuleStart("mainClassName");
* </pre>
*/
- private static JStatement makeStatsCalls(JProgram program,
- String mainClassName) {
+ private static JStatement makeStatsCalls(JProgram program, String mainClassName) {
SourceInfo sourceInfo = program.createSourceInfoSynthetic(JavaToJavaScriptCompiler.class);
JMethod isStatsAvailableMethod = program.getIndexedMethod("Stats.isStatsAvailable");
JMethod onModuleStartMethod = program.getIndexedMethod("Stats.onModuleStart");
- JMethodCall availableCall = new JMethodCall(sourceInfo, null,
- isStatsAvailableMethod);
- JMethodCall onModuleStartCall = new JMethodCall(sourceInfo, null,
- onModuleStartMethod);
+ JMethodCall availableCall = new JMethodCall(sourceInfo, null, isStatsAvailableMethod);
+ JMethodCall onModuleStartCall = new JMethodCall(sourceInfo, null, onModuleStartMethod);
onModuleStartCall.addArg(program.getLiteralString(sourceInfo, mainClassName));
- JBinaryOperation amp = new JBinaryOperation(sourceInfo,
- program.getTypePrimitiveBoolean(), JBinaryOperator.AND, availableCall,
- onModuleStartCall);
+ JBinaryOperation amp =
+ new JBinaryOperation(sourceInfo, program.getTypePrimitiveBoolean(), JBinaryOperator.AND,
+ availableCall, onModuleStartCall);
return amp.makeStatement();
}
- private static SymbolData[] makeSymbolMap(
- Map<StandardSymbolData, JsName> symbolTable) {
+ private static SymbolData[] makeSymbolMap(Map<StandardSymbolData, JsName> symbolTable) {
SymbolData[] result = new SymbolData[symbolTable.size()];
int i = 0;
@@ -1305,8 +1269,8 @@
/**
* Open an emitted artifact and gunzip its contents.
*/
- private static GZIPInputStream openWithGunzip(EmittedArtifact artifact)
- throws IOException, UnableToCompleteException {
+ private static GZIPInputStream openWithGunzip(EmittedArtifact artifact) throws IOException,
+ UnableToCompleteException {
return new GZIPInputStream(artifact.getContents(TreeLogger.NULL));
}
@@ -1316,8 +1280,7 @@
* then this method can be used instead to record a single dependency graph
* for the whole program.
*/
- private static void recordNonSplitDependencies(JProgram program,
- OutputStream out) {
+ private static void recordNonSplitDependencies(JProgram program, OutputStream out) {
DependencyRecorder deps = new DependencyRecorder(out);
deps.open();
deps.startDependencyGraph("initial", null);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/SourceInfoCorrelation.java b/dev/core/src/com/google/gwt/dev/jjs/SourceInfoCorrelation.java
index 70eeb59..c9d5a27 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/SourceInfoCorrelation.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/SourceInfoCorrelation.java
@@ -49,8 +49,7 @@
this.parent = null;
}
- private SourceInfoCorrelation(SourceInfoCorrelation parent,
- SourceOrigin origin) {
+ private SourceInfoCorrelation(SourceInfoCorrelation parent, SourceOrigin origin) {
this.origin = origin;
this.parent = parent;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/SourceOrigin.java b/dev/core/src/com/google/gwt/dev/jjs/SourceOrigin.java
index 1a3b7d7..3e42270 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/SourceOrigin.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/SourceOrigin.java
@@ -39,8 +39,7 @@
private final int endPos;
private final int startPos;
- private SourceOriginPos(String location, int startLine, int startPos,
- int endPos) {
+ private SourceOriginPos(String location, int startLine, int startPos, int endPos) {
super(location, startLine);
this.startPos = startPos;
this.endPos = endPos;
@@ -73,21 +72,20 @@
* get barely any reuse in the Java AST. Synchronized since several threads
* could operate on it at once during parallel optimization phases.
*/
- private static final Map<SourceOrigin, SourceOrigin> CANONICAL_SOURCE_ORIGINS = Collections.synchronizedMap(new LinkedHashMap<SourceOrigin, SourceOrigin>(
- 150, 0.75f, true) {
- @Override
- protected boolean removeEldestEntry(Entry<SourceOrigin, SourceOrigin> eldest) {
- return size() > 100;
- }
- });
+ private static final Map<SourceOrigin, SourceOrigin> CANONICAL_SOURCE_ORIGINS = Collections
+ .synchronizedMap(new LinkedHashMap<SourceOrigin, SourceOrigin>(150, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(Entry<SourceOrigin, SourceOrigin> eldest) {
+ return size() > 100;
+ }
+ });
private static final Correlation[] NO_CORRELATIONS = new Correlation[0];
/**
* Creates SourceOrigin nodes.
*/
- public static SourceOrigin create(int startPos, int endPos, int startLine,
- String fileName) {
+ public static SourceOrigin create(int startPos, int endPos, int startLine, String fileName) {
if (startPos < 0 && endPos < 0) {
return create(startLine, fileName);
}
@@ -104,8 +102,7 @@
SourceOrigin newInstance = new SourceOrigin(fileName, startLine);
SourceOrigin canonical = CANONICAL_SOURCE_ORIGINS.get(newInstance);
- assert canonical == null
- || (newInstance != canonical && newInstance.equals(canonical));
+ assert canonical == null || (newInstance != canonical && newInstance.equals(canonical));
if (canonical != null) {
return canonical;
@@ -134,8 +131,7 @@
}
SourceOrigin other = (SourceOrigin) o;
return startLine == other.startLine && getEndPos() == other.getEndPos()
- && getStartPos() == other.getStartPos()
- && fileName.equals(other.fileName);
+ && getStartPos() == other.getStartPos() && fileName.equals(other.fileName);
}
public Correlation getCorrelation(Axis axis) {
@@ -172,8 +168,7 @@
@Override
public int hashCode() {
- return 2 + 13 * fileName.hashCode() + 17 * startLine + 29 * getStartPos()
- + 31 * getEndPos();
+ return 2 + 13 * fileName.hashCode() + 17 * startLine + 29 * getStartPos() + 31 * getEndPos();
}
public SourceInfo makeChild() {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/UnifiedAst.java b/dev/core/src/com/google/gwt/dev/jjs/UnifiedAst.java
index 3a5cdf2..25f3b16 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/UnifiedAst.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/UnifiedAst.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -70,7 +70,7 @@
private transient AST initialAst;
/**
- * Metrics for the module load phase. Stored here so they can be written out
+ * Metrics for the module load phase. Stored here so they can be written out
* as artifacts in the compile phase.
*/
private ModuleMetricsArtifact moduleMetrics;
@@ -86,8 +86,8 @@
private final JJSOptions options;
/**
- * Metrics for the precompilation phase. Stored here so they can be written out
- * as artifacts in the compile phase.
+ * Metrics for the precompilation phase. Stored here so they can be written
+ * out as artifacts in the compile phase.
*/
private PrecompilationMetricsArtifact precompilationMetrics;
@@ -101,14 +101,12 @@
*/
private transient long serializedAstToken;
- public UnifiedAst(JJSOptions options, AST initialAst,
- boolean singlePermutation, Set<String> rebindRequests) {
+ public UnifiedAst(JJSOptions options, AST initialAst, boolean singlePermutation,
+ Set<String> rebindRequests) {
this.options = new JJSOptionsImpl(options);
this.initialAst = initialAst;
- this.rebindRequests = Collections.unmodifiableSortedSet(new TreeSet<String>(
- rebindRequests));
- this.serializedAstToken = singlePermutation ? -1
- : diskCache.writeObject(initialAst);
+ this.rebindRequests = Collections.unmodifiableSortedSet(new TreeSet<String>(rebindRequests));
+ this.serializedAstToken = singlePermutation ? -1 : diskCache.writeObject(initialAst);
}
/**
@@ -124,23 +122,22 @@
/**
* Compiles a particular permutation.
- *
+ *
* @param logger the logger to use
* @param permutation the permutation to compile
* @return the permutation result
* @throws UnableToCompleteException if an error other than
* {@link OutOfMemoryError} occurs
*/
- public PermutationResult compilePermutation(TreeLogger logger,
- Permutation permutation) throws UnableToCompleteException {
- return JavaToJavaScriptCompiler.compilePermutation(logger, this,
- permutation);
+ public PermutationResult compilePermutation(TreeLogger logger, Permutation permutation)
+ throws UnableToCompleteException {
+ return JavaToJavaScriptCompiler.compilePermutation(logger, this, permutation);
}
/**
* Return the current AST so that clients can explicitly walk the Java or
* JavaScript parse trees.
- *
+ *
* @return the current AST object holding the Java and JavaScript trees.
*/
public AST getFreshAst() {
@@ -216,8 +213,7 @@
/**
* Re-initialize lock object; copy serialized AST straight to cache.
*/
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
myLockObject = new Object();
serializedAstToken = diskCache.transferFromStream(stream);
@@ -235,8 +231,7 @@
// Serialize into raw bytes.
Util.writeObjectToStream(stream, initialAst);
} else {
- throw new IllegalStateException(
- "No serialized AST was cached and AST was already consumed.");
+ throw new IllegalStateException("No serialized AST was cached and AST was already consumed.");
}
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeAbstract.java b/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeAbstract.java
index 2fac72b..b514284 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeAbstract.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeAbstract.java
@@ -16,7 +16,7 @@
package com.google.gwt.dev.jjs.ast;
/**
- * Interfaces implemented by entities which can be abstract.
+ * Interfaces implemented by entities which can be abstract.
*/
public interface CanBeAbstract {
boolean isAbstract();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeStatic.java b/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeStatic.java
index 4b42414..7e2420b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeStatic.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/CanBeStatic.java
@@ -16,7 +16,7 @@
package com.google.gwt.dev.jjs.ast;
/**
- * Interface implemented by entities that maybe static.
+ * Interface implemented by entities that maybe static.
*/
public interface CanBeStatic {
boolean isStatic();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/CanHaveInitializer.java b/dev/core/src/com/google/gwt/dev/jjs/ast/CanHaveInitializer.java
index 89b17c0..7d8528a 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/CanHaveInitializer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/CanHaveInitializer.java
@@ -21,6 +21,8 @@
*/
public interface CanHaveInitializer {
JLiteral getConstInitializer();
+
boolean hasInitializer();
+
void setInitializer(JDeclarationStatement declStmt);
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/HasEnclosingType.java b/dev/core/src/com/google/gwt/dev/jjs/ast/HasEnclosingType.java
index 5279c66..65a8f3a 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/HasEnclosingType.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/HasEnclosingType.java
@@ -16,7 +16,7 @@
package com.google.gwt.dev.jjs.ast;
/**
- * Interface implemented by anything that can be enclosed by a type.
+ * Interface implemented by anything that can be enclosed by a type.
*/
public interface HasEnclosingType {
JDeclaredType getEnclosingType();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/HasName.java b/dev/core/src/com/google/gwt/dev/jjs/ast/HasName.java
index b3e43d5..d12cf10 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/HasName.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/HasName.java
@@ -23,8 +23,7 @@
* Interface implemented by named entities.
*/
public interface HasName {
- String getName();
-
+
/**
* Collection of utilities to deal with HasName objects.
*/
@@ -37,4 +36,6 @@
});
}
}
+
+ String getName();
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JAbsentArrayDimension.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JAbsentArrayDimension.java
index 29d7659..6881fc4 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JAbsentArrayDimension.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JAbsentArrayDimension.java
@@ -24,8 +24,7 @@
*/
public class JAbsentArrayDimension extends JLiteral {
- public static final JExpression INSTANCE = new JAbsentArrayDimension(
- SourceOrigin.UNKNOWN);
+ public static final JExpression INSTANCE = new JAbsentArrayDimension(SourceOrigin.UNKNOWN);
/**
* These are only supposed to be constructed by JProgram.
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayLength.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayLength.java
index fc64c21..96854e9 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayLength.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayLength.java
@@ -1,12 +1,12 @@
/*
* Copyright 2010 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayRef.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayRef.java
index 948122c..faca01c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayRef.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayRef.java
@@ -49,8 +49,7 @@
public JType getType() {
JArrayType arrayType = getArrayType();
- return (arrayType == null) ? JNullType.INSTANCE
- : arrayType.getElementType();
+ return (arrayType == null) ? JNullType.INSTANCE : arrayType.getElementType();
}
@Override
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayType.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayType.java
index 0fe86e0..80c5f60 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayType.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JArrayType.java
@@ -27,8 +27,7 @@
private transient JType leafType = null;
public JArrayType(JType elementType) {
- super(elementType.getSourceInfo().makeChild(SourceOrigin.UNKNOWN),
- elementType.getName() + "[]");
+ super(elementType.getSourceInfo().makeChild(SourceOrigin.UNKNOWN), elementType.getName() + "[]");
assert !(elementType instanceof JNonNullType);
this.elementType = elementType;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JAssertStatement.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JAssertStatement.java
index fbd2fcb..a2df292 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JAssertStatement.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JAssertStatement.java
@@ -22,8 +22,8 @@
*/
public class JAssertStatement extends JStatement {
- private JExpression testExpr;
private JExpression arg;
+ private JExpression testExpr;
public JAssertStatement(SourceInfo info, JExpression testExpr, JExpression arg) {
super(info);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperation.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperation.java
index 3f17ba6..e34460f 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperation.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperation.java
@@ -27,8 +27,8 @@
private JExpression rhs;
private JType type;
- public JBinaryOperation(SourceInfo info, JType type, JBinaryOperator op,
- JExpression lhs, JExpression rhs) {
+ public JBinaryOperation(SourceInfo info, JType type, JBinaryOperator op, JExpression lhs,
+ JExpression rhs) {
super(info);
this.op = op;
this.type = type;
@@ -60,8 +60,7 @@
@Override
public boolean hasSideEffects() {
- return op.isAssignment() || getLhs().hasSideEffects()
- || getRhs().hasSideEffects();
+ return op.isAssignment() || getLhs().hasSideEffects() || getRhs().hasSideEffects();
}
public boolean isAssignment() {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperator.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperator.java
index e4a18fc..12e5038 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperator.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JBinaryOperator.java
@@ -32,9 +32,9 @@
SHR), ASG_SHRU(">>>=", 14, SHRU), ASG_BIT_AND("&=", 14, BIT_AND), ASG_BIT_OR(
"|=", 14, BIT_OR), ASG_BIT_XOR("^=", 14, BIT_XOR);
- private final char[] symbol;
private final JBinaryOperator nonAsg;
private final int precedence;
+ private final char[] symbol;
private JBinaryOperator(String symbol, int precedence) {
this(symbol, precedence, null);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JBooleanLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JBooleanLiteral.java
index ed86fbb..2db044c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JBooleanLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JBooleanLiteral.java
@@ -23,11 +23,9 @@
*/
public class JBooleanLiteral extends JValueLiteral {
- public static final JBooleanLiteral FALSE = new JBooleanLiteral(
- SourceOrigin.UNKNOWN, false);
+ public static final JBooleanLiteral FALSE = new JBooleanLiteral(SourceOrigin.UNKNOWN, false);
- public static final JBooleanLiteral TRUE = new JBooleanLiteral(
- SourceOrigin.UNKNOWN, true);
+ public static final JBooleanLiteral TRUE = new JBooleanLiteral(SourceOrigin.UNKNOWN, true);
public static JBooleanLiteral get(boolean value) {
return value ? TRUE : FALSE;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JCastOperation.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JCastOperation.java
index cda2c46..74e914c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JCastOperation.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JCastOperation.java
@@ -22,8 +22,8 @@
*/
public class JCastOperation extends JExpression {
- private JExpression expr;
private final JType castType;
+ private JExpression expr;
public JCastOperation(SourceInfo info, JType castType, JExpression expr) {
super(info);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JCharLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JCharLiteral.java
index e0618bd..79e2533 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JCharLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JCharLiteral.java
@@ -23,8 +23,7 @@
*/
public class JCharLiteral extends JValueLiteral {
- public static final JCharLiteral NULL = new JCharLiteral(
- SourceOrigin.UNKNOWN, (char) 0);
+ public static final JCharLiteral NULL = new JCharLiteral(SourceOrigin.UNKNOWN, (char) 0);
public static JCharLiteral get(char value) {
return (value == 0) ? NULL : new JCharLiteral(SourceOrigin.UNKNOWN, value);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JClassType.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JClassType.java
index 3962459..494dd7c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JClassType.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JClassType.java
@@ -33,8 +33,7 @@
}
private Object readResolve() {
- JClassType result = new JClassType(SourceOrigin.UNKNOWN, name, false,
- false);
+ JClassType result = new JClassType(SourceOrigin.UNKNOWN, name, false, false);
result.setExternal(true);
return result;
}
@@ -44,8 +43,7 @@
private boolean isFinal;
private JClassType superClass;
- public JClassType(SourceInfo info, String name, boolean isAbstract,
- boolean isFinal) {
+ public JClassType(SourceInfo info, String name, boolean isAbstract, boolean isFinal) {
super(info, name);
this.isAbstract = isAbstract;
this.isFinal = isFinal;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JConditional.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JConditional.java
index a780f6e..bb41a95 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JConditional.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JConditional.java
@@ -27,8 +27,8 @@
private JExpression thenExpr;
private JType type;
- public JConditional(SourceInfo info, JType type, JExpression ifTest,
- JExpression thenExpr, JExpression elseExpr) {
+ public JConditional(SourceInfo info, JType type, JExpression ifTest, JExpression thenExpr,
+ JExpression elseExpr) {
super(info);
this.type = type;
this.ifTest = ifTest;
@@ -54,8 +54,7 @@
@Override
public boolean hasSideEffects() {
- return ifTest.hasSideEffects() || thenExpr.hasSideEffects()
- || elseExpr.hasSideEffects();
+ return ifTest.hasSideEffects() || thenExpr.hasSideEffects() || elseExpr.hasSideEffects();
}
public void setType(JType newType) {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JConstructor.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JConstructor.java
index 011f582..2cab0dd 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JConstructor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JConstructor.java
@@ -37,8 +37,7 @@
}
private Object readResolve() {
- JConstructor result = new JConstructor(SourceOrigin.UNKNOWN,
- enclosingType);
+ JConstructor result = new JConstructor(SourceOrigin.UNKNOWN, enclosingType);
result.signature = signature;
return result;
}
@@ -51,8 +50,8 @@
private boolean isEmpty = false;
public JConstructor(SourceInfo info, JClassType enclosingType) {
- super(info, enclosingType.getShortName(), enclosingType,
- JPrimitiveType.VOID, false, false, true, false);
+ super(info, enclosingType.getShortName(), enclosingType, JPrimitiveType.VOID, false, false,
+ true, false);
}
@Override
@@ -127,6 +126,7 @@
traceAfter(visitor, before);
}
+ @Override
protected Object writeReplace() {
if (getEnclosingType() != null && getEnclosingType().isExternal()) {
return new ExternalSerializedForm(this);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclarationStatement.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclarationStatement.java
index 10fb994..a1de3bd 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclarationStatement.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclarationStatement.java
@@ -25,8 +25,7 @@
public JExpression initializer;
private JVariableRef variableRef;
- public JDeclarationStatement(SourceInfo info, JVariableRef variableRef,
- JExpression intializer) {
+ public JDeclarationStatement(SourceInfo info, JVariableRef variableRef, JExpression intializer) {
super(info);
this.variableRef = variableRef;
this.initializer = intializer;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclaredType.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclaredType.java
index faeb049..892ca1c 100755
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclaredType.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JDeclaredType.java
@@ -288,8 +288,7 @@
* @see #writeMembers(ObjectOutputStream)
*/
@SuppressWarnings("unchecked")
- void readMembers(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ void readMembers(ObjectInputStream stream) throws IOException, ClassNotFoundException {
fields = (List<JField>) stream.readObject();
methods = (List<JMethod>) stream.readObject();
artificialRescues = (List<JNode>) stream.readObject();
@@ -300,8 +299,7 @@
*
* @see #writeMethodBodies(ObjectOutputStream)
*/
- void readMethodBodies(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ void readMethodBodies(ObjectInputStream stream) throws IOException, ClassNotFoundException {
for (JMethod method : methods) {
method.readBody(stream);
}
@@ -316,11 +314,11 @@
}
if (newClinitTarget != null && getClass().desiredAssertionStatus()) {
// Make sure this is a pure upgrade to a superclass or null.
- for (JClassType current = (JClassType) clinitTarget; current != newClinitTarget; current = current.getSuperClass()) {
- Preconditions.checkNotNull(
- current.getSuperClass(),
- "Null super class for: %s (currentTarget: %s; newTarget: %s) in %s",
- current, clinitTarget, newClinitTarget, this);
+ for (JClassType current = (JClassType) clinitTarget; current != newClinitTarget; current =
+ current.getSuperClass()) {
+ Preconditions.checkNotNull(current.getSuperClass(),
+ "Null super class for: %s (currentTarget: %s; newTarget: %s) in %s", current,
+ clinitTarget, newClinitTarget, this);
}
}
clinitTarget = newClinitTarget;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JDoubleLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JDoubleLiteral.java
index 6d49b1c..3c1be00 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JDoubleLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JDoubleLiteral.java
@@ -23,12 +23,11 @@
*/
public class JDoubleLiteral extends JValueLiteral {
- public static final JDoubleLiteral ZERO = new JDoubleLiteral(
- SourceOrigin.UNKNOWN, Double.longBitsToDouble(0L));
+ public static final JDoubleLiteral ZERO = new JDoubleLiteral(SourceOrigin.UNKNOWN, Double
+ .longBitsToDouble(0L));
public static JDoubleLiteral get(double value) {
- return isZero(value) ? ZERO : new JDoubleLiteral(SourceOrigin.UNKNOWN,
- value);
+ return isZero(value) ? ZERO : new JDoubleLiteral(SourceOrigin.UNKNOWN, value);
}
/**
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JEnumField.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JEnumField.java
index 4347df1..d745407 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JEnumField.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JEnumField.java
@@ -22,10 +22,10 @@
*/
public class JEnumField extends JField {
- private int ordinal;
+ private final int ordinal;
- public JEnumField(SourceInfo info, String name, int ordinal,
- JEnumType enclosingType, JClassType type) {
+ public JEnumField(SourceInfo info, String name, int ordinal, JEnumType enclosingType,
+ JClassType type) {
super(info, name, enclosingType, type, true, Disposition.FINAL);
this.ordinal = ordinal;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JField.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JField.java
index 9b3bc0c..412198f 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JField.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JField.java
@@ -59,8 +59,9 @@
private Object readResolve() {
String name = signature.substring(0, signature.indexOf(':'));
- JField result = new JField(SourceOrigin.UNKNOWN, name, enclosingType,
- JNullType.INSTANCE, false, Disposition.NONE);
+ JField result =
+ new JField(SourceOrigin.UNKNOWN, name, enclosingType, JNullType.INSTANCE, false,
+ Disposition.NONE);
result.signature = signature;
return result;
}
@@ -69,7 +70,7 @@
private final JDeclaredType enclosingType;
private final boolean isCompileTimeConstant;
private final boolean isStatic;
- private boolean isThisRef;
+ private final boolean isThisRef;
private boolean isVolatile;
private transient String signature;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JFieldRef.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JFieldRef.java
index 73695ab..4f3cc9b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JFieldRef.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JFieldRef.java
@@ -44,8 +44,7 @@
*/
private final JType overriddenType;
- public JFieldRef(SourceInfo info, JExpression instance, JField field,
- JDeclaredType enclosingType) {
+ public JFieldRef(SourceInfo info, JExpression instance, JField field, JDeclaredType enclosingType) {
this(info, instance, field, enclosingType, null);
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JFloatLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JFloatLiteral.java
index 1131c1b..1123320 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JFloatLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JFloatLiteral.java
@@ -23,12 +23,11 @@
*/
public class JFloatLiteral extends JValueLiteral {
- public static final JFloatLiteral ZERO = new JFloatLiteral(
- SourceOrigin.UNKNOWN, Float.intBitsToFloat(0));
+ public static final JFloatLiteral ZERO = new JFloatLiteral(SourceOrigin.UNKNOWN, Float
+ .intBitsToFloat(0));
public static JFloatLiteral get(float value) {
- return isZero(value) ? ZERO
- : new JFloatLiteral(SourceOrigin.UNKNOWN, value);
+ return isZero(value) ? ZERO : new JFloatLiteral(SourceOrigin.UNKNOWN, value);
}
/**
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JForStatement.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JForStatement.java
index 7121c8b..81a73c6 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JForStatement.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JForStatement.java
@@ -30,9 +30,8 @@
private List<JStatement> initializers;
private JExpression testExpr;
- public JForStatement(SourceInfo info, List<JStatement> initializers,
- JExpression testExpr, List<JExpressionStatement> increments,
- JStatement body) {
+ public JForStatement(SourceInfo info, List<JStatement> initializers, JExpression testExpr,
+ List<JExpressionStatement> increments, JStatement body) {
super(info);
this.initializers = Lists.normalize(initializers);
this.testExpr = testExpr;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JGwtCreate.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JGwtCreate.java
index 3accec7..94be737 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JGwtCreate.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JGwtCreate.java
@@ -27,8 +27,8 @@
*/
public class JGwtCreate extends JExpression {
- public static JExpression createInstantiationExpression(SourceInfo info,
- JClassType classType, JDeclaredType enclosingType) {
+ public static JExpression createInstantiationExpression(SourceInfo info, JClassType classType,
+ JDeclaredType enclosingType) {
/*
* Find the appropriate (noArg) constructor. In our AST, constructors are
* instance methods that should be qualified with a new expression.
@@ -49,12 +49,11 @@
return new JNewInstance(info, noArgCtor, enclosingType);
}
- private static ArrayList<JExpression> createInstantiationExpressions(
- SourceInfo info, List<JClassType> classTypes, JDeclaredType enclosingType) {
+ private static ArrayList<JExpression> createInstantiationExpressions(SourceInfo info,
+ List<JClassType> classTypes, JDeclaredType enclosingType) {
ArrayList<JExpression> exprs = new ArrayList<JExpression>();
for (JClassType classType : classTypes) {
- JExpression expr = createInstantiationExpression(info, classType,
- enclosingType);
+ JExpression expr = createInstantiationExpression(info, classType, enclosingType);
assert expr != null;
exprs.add(expr);
}
@@ -71,20 +70,10 @@
private JType type;
/**
- * Public constructor used during AST creation.
- */
- public JGwtCreate(SourceInfo info, JReferenceType sourceType,
- List<JClassType> resultTypes, JType type, JDeclaredType enclosingType) {
- this(info, sourceType, resultTypes, type, createInstantiationExpressions(
- info, resultTypes, enclosingType));
- }
-
- /**
* Constructor used for cloning an existing node.
*/
- public JGwtCreate(SourceInfo info, JReferenceType sourceType,
- List<JClassType> resultTypes, JType type,
- ArrayList<JExpression> instantiationExpressions) {
+ public JGwtCreate(SourceInfo info, JReferenceType sourceType, List<JClassType> resultTypes,
+ JType type, ArrayList<JExpression> instantiationExpressions) {
super(info);
this.sourceType = sourceType;
this.resultTypes = resultTypes;
@@ -92,6 +81,15 @@
this.instantiationExpressions = instantiationExpressions;
}
+ /**
+ * Public constructor used during AST creation.
+ */
+ public JGwtCreate(SourceInfo info, JReferenceType sourceType, List<JClassType> resultTypes,
+ JType type, JDeclaredType enclosingType) {
+ this(info, sourceType, resultTypes, type, createInstantiationExpressions(info, resultTypes,
+ enclosingType));
+ }
+
public ArrayList<JExpression> getInstantiationExpressions() {
return instantiationExpressions;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JIfStatement.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JIfStatement.java
index 2a053fb..b5a232a 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JIfStatement.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JIfStatement.java
@@ -26,8 +26,7 @@
private JExpression ifExpr;
private JStatement thenStmt;
- public JIfStatement(SourceInfo info, JExpression ifExpr, JStatement thenStmt,
- JStatement elseStmt) {
+ public JIfStatement(SourceInfo info, JExpression ifExpr, JStatement thenStmt, JStatement elseStmt) {
super(info);
this.ifExpr = ifExpr;
this.thenStmt = thenStmt;
@@ -61,15 +60,13 @@
@Override
public boolean unconditionalControlBreak() {
- boolean thenBreaks = thenStmt != null
- && thenStmt.unconditionalControlBreak();
+ boolean thenBreaks = thenStmt != null && thenStmt.unconditionalControlBreak();
if (thenBreaks && ifExpr == JBooleanLiteral.get(true)) {
// if(true) { /* unconditional break */ }
return true;
}
- boolean elseBreaks = elseStmt != null
- && elseStmt.unconditionalControlBreak();
+ boolean elseBreaks = elseStmt != null && elseStmt.unconditionalControlBreak();
if (elseBreaks && ifExpr == JBooleanLiteral.get(false)) {
// if(false) { } else { /* unconditional break */ }
return true;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JInstanceOf.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JInstanceOf.java
index 3018075..50812c1 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JInstanceOf.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JInstanceOf.java
@@ -25,8 +25,7 @@
private JExpression expr;
private final JReferenceType testType;
- public JInstanceOf(SourceInfo info, JReferenceType testType,
- JExpression expression) {
+ public JInstanceOf(SourceInfo info, JReferenceType testType, JExpression expression) {
super(info);
this.testType = testType;
this.expr = expression;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JIntLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JIntLiteral.java
index 4133ec0..2da5db3 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JIntLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JIntLiteral.java
@@ -23,8 +23,7 @@
*/
public class JIntLiteral extends JValueLiteral {
- public static final JIntLiteral ZERO = new JIntLiteral(SourceOrigin.UNKNOWN,
- 0);
+ public static final JIntLiteral ZERO = new JIntLiteral(SourceOrigin.UNKNOWN, 0);
public static JIntLiteral get(int value) {
return (value == 0) ? ZERO : new JIntLiteral(SourceOrigin.UNKNOWN, value);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JLocal.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JLocal.java
index e725118..34a6133 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JLocal.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JLocal.java
@@ -24,8 +24,7 @@
private final JMethodBody enclosingMethodBody;
- JLocal(SourceInfo info, String name, JType type, boolean isFinal,
- JMethodBody enclosingMethodBody) {
+ JLocal(SourceInfo info, String name, JType type, boolean isFinal, JMethodBody enclosingMethodBody) {
super(info, name, type, isFinal);
this.enclosingMethodBody = enclosingMethodBody;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JLongLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JLongLiteral.java
index 36bdc33..6411227 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JLongLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JLongLiteral.java
@@ -23,8 +23,7 @@
*/
public class JLongLiteral extends JValueLiteral {
- public static final JLongLiteral ZERO = new JLongLiteral(
- SourceOrigin.UNKNOWN, 0L);
+ public static final JLongLiteral ZERO = new JLongLiteral(SourceOrigin.UNKNOWN, 0L);
public static JLongLiteral get(long value) {
return (value == 0) ? ZERO : new JLongLiteral(SourceOrigin.UNKNOWN, value);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JMethod.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JMethod.java
index 4d7ebef..4b5172e 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JMethod.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JMethod.java
@@ -48,8 +48,8 @@
private Object readResolve() {
String name = signature.substring(0, signature.indexOf('('));
- JMethod result = new JMethod(SourceOrigin.UNKNOWN, name, enclosingType,
- null, false, false, false, false);
+ JMethod result =
+ new JMethod(SourceOrigin.UNKNOWN, name, enclosingType, null, false, false, false, false);
result.signature = signature;
return result;
}
@@ -96,9 +96,8 @@
/**
* These are only supposed to be constructed by JProgram.
*/
- public JMethod(SourceInfo info, String name, JDeclaredType enclosingType,
- JType returnType, boolean isAbstract, boolean isStatic, boolean isFinal,
- boolean isPrivate) {
+ public JMethod(SourceInfo info, String name, JDeclaredType enclosingType, JType returnType,
+ boolean isAbstract, boolean isStatic, boolean isFinal, boolean isPrivate) {
super(info);
this.name = StringInterner.get().intern(name);
this.enclosingType = enclosingType;
@@ -131,7 +130,7 @@
public void addParam(JParameter x) {
params = Lists.add(params, x);
}
-
+
public void addThrownException(JClassType exceptionType) {
thrownExceptions = Lists.add(thrownExceptions, exceptionType);
}
@@ -363,8 +362,7 @@
*
* @see #writeBody(ObjectOutputStream)
*/
- void readBody(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ void readBody(ObjectInputStream stream) throws IOException, ClassNotFoundException {
body = (JAbstractMethodBody) stream.readObject();
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JMethodCall.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JMethodCall.java
index 25ebf7d..c394d50 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JMethodCall.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JMethodCall.java
@@ -67,8 +67,7 @@
* allows us to preserve type information during the latter phases of
* compilation.
*/
- public JMethodCall(SourceInfo info, JExpression instance, JMethod method,
- JType overrideReturnType) {
+ public JMethodCall(SourceInfo info, JExpression instance, JMethod method, JType overrideReturnType) {
super(info);
assert (method != null);
assert (instance != null || method.isStatic());
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JModVisitor.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JModVisitor.java
index 2087a21..2fb9af9 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JModVisitor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JModVisitor.java
@@ -254,8 +254,7 @@
throw new InternalCompilerException("Cannot replace with null");
}
if (newNode == origNode) {
- throw new InternalCompilerException(
- "The replacement is the same as the original");
+ throw new InternalCompilerException("The replacement is the same as the original");
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JNewArray.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JNewArray.java
index 1ce797a..b0980d9 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JNewArray.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JNewArray.java
@@ -25,8 +25,7 @@
*/
public class JNewArray extends JExpression {
- public static JNewArray createDims(SourceInfo info, JArrayType arrayType,
- List<JExpression> dims) {
+ public static JNewArray createDims(SourceInfo info, JArrayType arrayType, List<JExpression> dims) {
List<JClassLiteral> classLiterals = new ArrayList<JClassLiteral>();
// Produce all class literals that will eventually get generated.
@@ -45,29 +44,27 @@
classLiterals.add(classLit);
cur = ((JArrayType) cur).getElementType();
}
- return new JNewArray(info, arrayType.getNonNull(), dims, null,
- classLiterals);
+ return new JNewArray(info, arrayType.getNonNull(), dims, null, classLiterals);
}
- public static JNewArray createInitializers(SourceInfo info,
- JArrayType arrayType, List<JExpression> initializers) {
+ public static JNewArray createInitializers(SourceInfo info, JArrayType arrayType,
+ List<JExpression> initializers) {
List<JClassLiteral> classLiterals = new ArrayList<JClassLiteral>();
classLiterals.add(new JClassLiteral(info.makeChild(), arrayType));
- return new JNewArray(info, arrayType.getNonNull(), null, initializers,
- classLiterals);
+ return new JNewArray(info, arrayType.getNonNull(), null, initializers, classLiterals);
}
public final List<JExpression> dims;
public final List<JExpression> initializers;
- private JNonNullType type;
-
/**
* The list of class literals that will be needed to support this expression.
*/
private final List<JClassLiteral> classLiterals;
+ private JNonNullType type;
+
public JNewArray(SourceInfo info, JNonNullType type, List<JExpression> dims,
List<JExpression> initializers, List<JClassLiteral> classLits) {
super(info);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JNewInstance.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JNewInstance.java
index aeebb67..a38873e 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JNewInstance.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JNewInstance.java
@@ -25,7 +25,7 @@
/**
* The enclosing type of this new operation, used to compute clinit.
*/
- private JDeclaredType enclosingType;
+ private final JDeclaredType enclosingType;
/**
* Initialize a new instance operation equivalent to another one. The new
@@ -37,8 +37,7 @@
this.enclosingType = other.enclosingType;
}
- public JNewInstance(SourceInfo info, JConstructor ctor,
- JDeclaredType enclosingType) {
+ public JNewInstance(SourceInfo info, JConstructor ctor, JDeclaredType enclosingType) {
super(info, null, ctor);
this.enclosingType = enclosingType;
setStaticDispatchOnly();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JNullLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JNullLiteral.java
index 07f1526..09f4e63 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JNullLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JNullLiteral.java
@@ -23,19 +23,12 @@
*/
public class JNullLiteral extends JValueLiteral {
- public static final JNullLiteral INSTANCE = new JNullLiteral(
- SourceOrigin.UNKNOWN);
+ public static final JNullLiteral INSTANCE = new JNullLiteral(SourceOrigin.UNKNOWN);
private JNullLiteral(SourceInfo sourceInfo) {
super(sourceInfo);
}
- @Override
- protected
- JValueLiteral cloneFrom(JValueLiteral value) {
- throw new UnsupportedOperationException();
- }
-
public JType getType() {
return JNullType.INSTANCE;
}
@@ -51,6 +44,11 @@
visitor.endVisit(this, ctx);
}
+ @Override
+ protected JValueLiteral cloneFrom(JValueLiteral value) {
+ throw new UnsupportedOperationException();
+ }
+
/**
* Note, if this ever becomes not-a-singleton, we'll need to check the
* SourceInfo == SourceOrigin.UNKNOWN.
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JNullType.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JNullType.java
index dea6b2e..0bd8bff 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JNullType.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JNullType.java
@@ -32,8 +32,7 @@
@Override
public String getClassLiteralFactoryMethod() {
- throw new InternalCompilerException(
- "Cannot get class literal for null type");
+ throw new InternalCompilerException("Cannot get class literal for null type");
}
@Override
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JParameter.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JParameter.java
index 9e3fe20..92c0069 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JParameter.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JParameter.java
@@ -22,14 +22,13 @@
*/
public class JParameter extends JVariable implements HasEnclosingMethod {
- public static JParameter create(SourceInfo info, String name, JType type,
- boolean isFinal, boolean isThis, JMethod enclosingMethod) {
+ public static JParameter create(SourceInfo info, String name, JType type, boolean isFinal,
+ boolean isThis, JMethod enclosingMethod) {
assert (name != null);
assert (type != null);
assert (enclosingMethod != null);
- JParameter x = new JParameter(info, name, type,
- isFinal, isThis, enclosingMethod);
+ JParameter x = new JParameter(info, name, type, isFinal, isThis, enclosingMethod);
enclosingMethod.addParam(x);
return x;
@@ -38,8 +37,8 @@
private final JMethod enclosingMethod;
private final boolean isThis;
- public JParameter(SourceInfo info, String name, JType type, boolean isFinal,
- boolean isThis, JMethod enclosingMethod) {
+ public JParameter(SourceInfo info, String name, JType type, boolean isFinal, boolean isThis,
+ JMethod enclosingMethod) {
super(info, name, type, isFinal);
this.enclosingMethod = enclosingMethod;
this.isThis = isThis;
@@ -58,8 +57,7 @@
}
public void setInitializer(JDeclarationStatement declStmt) {
- throw new UnsupportedOperationException(
- "A JParameter cannot have an initializer");
+ throw new UnsupportedOperationException("A JParameter cannot have an initializer");
}
public void traverse(JVisitor visitor, Context ctx) {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JPrimitiveType.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JPrimitiveType.java
index a639b43..a28a380 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JPrimitiveType.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JPrimitiveType.java
@@ -26,39 +26,38 @@
*/
public class JPrimitiveType extends JType {
/*
- * Primitive types are static singletons. Serialization via readResolve().
+ * Primitive types are static singletons. Serialization via readResolve().
*/
private static final class Singletons {
public static final Map<String, JPrimitiveType> map = new HashMap<String, JPrimitiveType>();
}
- public static final JPrimitiveType BOOLEAN = new JPrimitiveType("boolean",
- "Z", "java.lang.Boolean", JBooleanLiteral.FALSE);
+ public static final JPrimitiveType BOOLEAN = new JPrimitiveType("boolean", "Z",
+ "java.lang.Boolean", JBooleanLiteral.FALSE);
- public static final JPrimitiveType BYTE = new JPrimitiveType("byte", "B",
- "java.lang.Byte", JIntLiteral.ZERO);
+ public static final JPrimitiveType BYTE = new JPrimitiveType("byte", "B", "java.lang.Byte",
+ JIntLiteral.ZERO);
- public static final JPrimitiveType CHAR = new JPrimitiveType("char", "C",
- "java.lang.Character", JCharLiteral.NULL);
+ public static final JPrimitiveType CHAR = new JPrimitiveType("char", "C", "java.lang.Character",
+ JCharLiteral.NULL);
- public static final JPrimitiveType DOUBLE = new JPrimitiveType("double", "D",
- "java.lang.Double", JDoubleLiteral.ZERO);
+ public static final JPrimitiveType DOUBLE = new JPrimitiveType("double", "D", "java.lang.Double",
+ JDoubleLiteral.ZERO);
- public static final JPrimitiveType FLOAT = new JPrimitiveType("float", "F",
- "java.lang.Float", JFloatLiteral.ZERO);
+ public static final JPrimitiveType FLOAT = new JPrimitiveType("float", "F", "java.lang.Float",
+ JFloatLiteral.ZERO);
- public static final JPrimitiveType INT = new JPrimitiveType("int", "I",
- "java.lang.Integer", JIntLiteral.ZERO);
+ public static final JPrimitiveType INT = new JPrimitiveType("int", "I", "java.lang.Integer",
+ JIntLiteral.ZERO);
- public static final JPrimitiveType LONG = new JPrimitiveType("long", "J",
- "java.lang.Long", JLongLiteral.ZERO);
+ public static final JPrimitiveType LONG = new JPrimitiveType("long", "J", "java.lang.Long",
+ JLongLiteral.ZERO);
- public static final JPrimitiveType SHORT = new JPrimitiveType("short", "S",
- "java.lang.Short", JIntLiteral.ZERO);
+ public static final JPrimitiveType SHORT = new JPrimitiveType("short", "S", "java.lang.Short",
+ JIntLiteral.ZERO);
- public static final JPrimitiveType VOID = new JPrimitiveType("void", "V",
- "java.lang.Void", null);
+ public static final JPrimitiveType VOID = new JPrimitiveType("void", "V", "java.lang.Void", null);
private final transient JValueLiteral defaultValue;
@@ -66,8 +65,8 @@
private final transient String wrapperTypeName;
- private JPrimitiveType(String name, String signatureName,
- String wrapperTypeName, JValueLiteral defaultValue) {
+ private JPrimitiveType(String name, String signatureName, String wrapperTypeName,
+ JValueLiteral defaultValue) {
super(SourceOrigin.UNKNOWN, name);
this.defaultValue = defaultValue;
this.signatureName = StringInterner.get().intern(signatureName);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JProgram.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JProgram.java
index 6af8399..d0563b9 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JProgram.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JProgram.java
@@ -51,8 +51,7 @@
* Root for the AST representing an entire Java program.
*/
public class JProgram extends JNode {
- private static final class ArrayTypeComparator implements
- Comparator<JArrayType>, Serializable {
+ private static final class ArrayTypeComparator implements Comparator<JArrayType>, Serializable {
public int compare(JArrayType o1, JArrayType o2) {
int comp = o1.getDims() - o2.getDims();
if (comp != 0) {
@@ -62,30 +61,22 @@
}
}
- public static final Set<String> CODEGEN_TYPES_SET = new LinkedHashSet<String>(
- Arrays.asList(
- "com.google.gwt.lang.Array", "com.google.gwt.lang.Cast",
- "com.google.gwt.lang.CollapsedPropertyHolder",
- "com.google.gwt.lang.Exceptions", "com.google.gwt.lang.LongLib",
- "com.google.gwt.lang.Stats", "com.google.gwt.lang.Util"));
+ public static final Set<String> CODEGEN_TYPES_SET = new LinkedHashSet<String>(Arrays.asList(
+ "com.google.gwt.lang.Array", "com.google.gwt.lang.Cast",
+ "com.google.gwt.lang.CollapsedPropertyHolder", "com.google.gwt.lang.Exceptions",
+ "com.google.gwt.lang.LongLib", "com.google.gwt.lang.Stats", "com.google.gwt.lang.Util"));
- public static final Set<String> INDEX_TYPES_SET = new LinkedHashSet<String>(
- Arrays.asList(
- "java.io.Serializable", "java.lang.Object", "java.lang.String",
- "java.lang.Class", "java.lang.CharSequence", "java.lang.Cloneable",
- "java.lang.Comparable", "java.lang.Enum", "java.lang.Iterable",
- "java.util.Iterator", "java.lang.AssertionError", "java.lang.Boolean",
- "java.lang.Byte", "java.lang.Character", "java.lang.Short",
- "java.lang.Integer", "java.lang.Float", "java.lang.Double",
- "java.lang.Throwable",
- "com.google.gwt.core.client.GWT",
- "com.google.gwt.core.client.JavaScriptObject",
- "com.google.gwt.lang.ClassLiteralHolder",
- "com.google.gwt.core.client.RunAsyncCallback",
- "com.google.gwt.core.client.impl.AsyncFragmentLoader",
- "com.google.gwt.core.client.impl.Impl",
- "com.google.gwt.lang.EntryMethodHolder",
- "com.google.gwt.core.client.prefetch.RunAsyncCode"));
+ public static final Set<String> INDEX_TYPES_SET = new LinkedHashSet<String>(Arrays.asList(
+ "java.io.Serializable", "java.lang.Object", "java.lang.String", "java.lang.Class",
+ "java.lang.CharSequence", "java.lang.Cloneable", "java.lang.Comparable", "java.lang.Enum",
+ "java.lang.Iterable", "java.util.Iterator", "java.lang.AssertionError", "java.lang.Boolean",
+ "java.lang.Byte", "java.lang.Character", "java.lang.Short", "java.lang.Integer",
+ "java.lang.Float", "java.lang.Double", "java.lang.Throwable",
+ "com.google.gwt.core.client.GWT", "com.google.gwt.core.client.JavaScriptObject",
+ "com.google.gwt.lang.ClassLiteralHolder", "com.google.gwt.core.client.RunAsyncCallback",
+ "com.google.gwt.core.client.impl.AsyncFragmentLoader",
+ "com.google.gwt.core.client.impl.Impl", "com.google.gwt.lang.EntryMethodHolder",
+ "com.google.gwt.core.client.prefetch.RunAsyncCode"));
static final Map<String, Set<String>> traceMethods = new HashMap<String, Set<String>>();
@@ -99,10 +90,12 @@
private static final int IS_NULL = 0;
- private static final Map<String, JPrimitiveType> primitiveTypes = new HashMap<String, JPrimitiveType>();
+ private static final Map<String, JPrimitiveType> primitiveTypes =
+ new HashMap<String, JPrimitiveType>();
@Deprecated
- private static final Map<String, JPrimitiveType> primitiveTypesDeprecated = new HashMap<String, JPrimitiveType>();
+ private static final Map<String, JPrimitiveType> primitiveTypesDeprecated =
+ new HashMap<String, JPrimitiveType>();
static {
INDEX_TYPES_SET.addAll(CODEGEN_TYPES_SET);
@@ -144,36 +137,29 @@
primitiveTypesDeprecated.put(JPrimitiveType.BOOLEAN.getJsniSignatureName(),
JPrimitiveType.BOOLEAN);
- primitiveTypesDeprecated.put(JPrimitiveType.BYTE.getJsniSignatureName(),
- JPrimitiveType.BYTE);
- primitiveTypesDeprecated.put(JPrimitiveType.CHAR.getJsniSignatureName(),
- JPrimitiveType.CHAR);
+ primitiveTypesDeprecated.put(JPrimitiveType.BYTE.getJsniSignatureName(), JPrimitiveType.BYTE);
+ primitiveTypesDeprecated.put(JPrimitiveType.CHAR.getJsniSignatureName(), JPrimitiveType.CHAR);
primitiveTypesDeprecated.put(JPrimitiveType.DOUBLE.getJsniSignatureName(),
JPrimitiveType.DOUBLE);
- primitiveTypesDeprecated.put(JPrimitiveType.FLOAT.getJsniSignatureName(),
- JPrimitiveType.FLOAT);
- primitiveTypesDeprecated.put(JPrimitiveType.INT.getJsniSignatureName(),
- JPrimitiveType.INT);
- primitiveTypesDeprecated.put(JPrimitiveType.LONG.getJsniSignatureName(),
- JPrimitiveType.LONG);
- primitiveTypesDeprecated.put(JPrimitiveType.SHORT.getJsniSignatureName(),
- JPrimitiveType.SHORT);
- primitiveTypesDeprecated.put(JPrimitiveType.VOID.getJsniSignatureName(),
- JPrimitiveType.VOID);
+ primitiveTypesDeprecated.put(JPrimitiveType.FLOAT.getJsniSignatureName(), JPrimitiveType.FLOAT);
+ primitiveTypesDeprecated.put(JPrimitiveType.INT.getJsniSignatureName(), JPrimitiveType.INT);
+ primitiveTypesDeprecated.put(JPrimitiveType.LONG.getJsniSignatureName(), JPrimitiveType.LONG);
+ primitiveTypesDeprecated.put(JPrimitiveType.SHORT.getJsniSignatureName(), JPrimitiveType.SHORT);
+ primitiveTypesDeprecated.put(JPrimitiveType.VOID.getJsniSignatureName(), JPrimitiveType.VOID);
}
/**
* Helper to create an assignment, used to initalize fields, etc.
*/
- public static JExpressionStatement createAssignmentStmt(SourceInfo info,
- JExpression lhs, JExpression rhs) {
- JBinaryOperation assign = new JBinaryOperation(info, lhs.getType(),
- JBinaryOperator.ASG, lhs, rhs);
+ public static JExpressionStatement createAssignmentStmt(SourceInfo info, JExpression lhs,
+ JExpression rhs) {
+ JBinaryOperation assign =
+ new JBinaryOperation(info, lhs.getType(), JBinaryOperator.ASG, lhs, rhs);
return assign.makeStatement();
}
- public static JLocal createLocal(SourceInfo info, String name, JType type,
- boolean isFinal, JMethodBody enclosingMethodBody) {
+ public static JLocal createLocal(SourceInfo info, String name, JType type, boolean isFinal,
+ JMethodBody enclosingMethodBody) {
assert (name != null);
assert (type != null);
assert (enclosingMethodBody != null);
@@ -182,21 +168,20 @@
return x;
}
- public static JParameter createParameter(SourceInfo info, String name,
- JType type, boolean isFinal, boolean isThis, JMethod enclosingMethod) {
+ public static JParameter createParameter(SourceInfo info, String name, JType type,
+ boolean isFinal, boolean isThis, JMethod enclosingMethod) {
assert (name != null);
assert (type != null);
assert (enclosingMethod != null);
- JParameter x = new JParameter(info, name, type, isFinal, isThis,
- enclosingMethod);
+ JParameter x = new JParameter(info, name, type, isFinal, isThis, enclosingMethod);
enclosingMethod.addParam(x);
return x;
}
- public static List<JDeclaredType> deserializeTypes(ObjectInputStream stream)
- throws IOException, ClassNotFoundException {
+ public static List<JDeclaredType> deserializeTypes(ObjectInputStream stream) throws IOException,
+ ClassNotFoundException {
@SuppressWarnings("unchecked")
List<JDeclaredType> types = (List<JDeclaredType>) stream.readObject();
for (JDeclaredType type : types) {
@@ -229,8 +214,7 @@
public static boolean isClinit(JMethod method) {
JDeclaredType enclosingType = method.getEnclosingType();
- if ((enclosingType != null)
- && (method == enclosingType.getMethods().get(0))) {
+ if ((enclosingType != null) && (method == enclosingType.getMethods().get(0))) {
assert (method.getName().equals("$clinit"));
return true;
} else {
@@ -252,18 +236,17 @@
* @param firstFragment The first fragment to consider
* @param restFragments The rest of the fragments to consider
*/
- public static int lastFragmentLoadingBefore(List<Integer> initialSeq,
- int numSps, int firstFragment, int... restFragments) {
+ public static int lastFragmentLoadingBefore(List<Integer> initialSeq, int numSps,
+ int firstFragment, int... restFragments) {
int latest = firstFragment;
for (int frag : restFragments) {
- latest = pairwiseLastFragmentLoadingBefore(initialSeq, numSps, latest,
- frag);
+ latest = pairwiseLastFragmentLoadingBefore(initialSeq, numSps, latest, frag);
}
return latest;
}
- public static void serializeTypes(List<JDeclaredType> types,
- ObjectOutputStream stream) throws IOException {
+ public static void serializeTypes(List<JDeclaredType> types, ObjectOutputStream stream)
+ throws IOException {
stream.writeObject(types);
for (JDeclaredType type : types) {
type.writeMembers(stream);
@@ -277,8 +260,8 @@
* The main logic behind {@link #lastFragmentLoadingBefore(int, int...)} and
* {@link #lastFragmentLoadingBefore(List, int, int, int...)}.
*/
- private static int pairwiseLastFragmentLoadingBefore(
- List<Integer> initialSeq, int numSps, int frag1, int frag2) {
+ private static int pairwiseLastFragmentLoadingBefore(List<Integer> initialSeq, int numSps,
+ int frag1, int frag2) {
if (frag1 == frag2) {
return frag1;
}
@@ -339,6 +322,8 @@
private final HashMap<JType, JArrayType> arrayTypes = new HashMap<JType, JArrayType>();
+ private IdentityHashMap<JReferenceType, JsonObject> castableTypeMaps;
+
/**
* A factory to create correlations.
*/
@@ -352,8 +337,6 @@
private final Map<JMethod, JMethod> instanceToStaticMap = new IdentityHashMap<JMethod, JMethod>();
- private IdentityHashMap<JReferenceType, JsonObject> castableTypeMaps;
-
private JField nullField;
private JMethod nullMethod;
@@ -400,8 +383,7 @@
* cost of memory and object allocations.
*/
public JProgram(CorrelationFactory correlator) {
- super(correlator.makeSourceInfo(SourceOrigin.create(0,
- JProgram.class.getName())));
+ super(correlator.makeSourceInfo(SourceOrigin.create(0, JProgram.class.getName())));
this.correlator = correlator;
}
@@ -421,8 +403,7 @@
}
}
- public JClassType createClass(SourceInfo info, String name,
- boolean isAbstract, boolean isFinal) {
+ public JClassType createClass(SourceInfo info, String name, boolean isAbstract, boolean isFinal) {
JClassType x = new JClassType(info, name, isAbstract, isFinal);
allTypes.add(x);
@@ -451,13 +432,11 @@
return x;
}
- public JConstructor createConstructor(SourceInfo info,
- JClassType enclosingType) {
+ public JConstructor createConstructor(SourceInfo info, JClassType enclosingType) {
JConstructor x = new JConstructor(info, enclosingType);
x.setBody(new JMethodBody(info));
if (indexedTypes.containsValue(enclosingType)) {
- indexedMethods.put(enclosingType.getShortName() + '.'
- + enclosingType.getShortName(), x);
+ indexedMethods.put(enclosingType.getShortName() + '.' + enclosingType.getShortName(), x);
}
enclosingType.addMethod(x);
@@ -474,8 +453,8 @@
return x;
}
- public JField createEnumField(SourceInfo info, String name,
- JEnumType enclosingType, JClassType type, int ordinal) {
+ public JField createEnumField(SourceInfo info, String name, JEnumType enclosingType,
+ JClassType type, int ordinal) {
assert (name != null);
assert (type != null);
assert (ordinal >= 0);
@@ -485,15 +464,13 @@
return x;
}
- public JField createField(SourceInfo info, String name,
- JDeclaredType enclosingType, JType type, boolean isStatic,
- Disposition disposition) {
+ public JField createField(SourceInfo info, String name, JDeclaredType enclosingType, JType type,
+ boolean isStatic, Disposition disposition) {
assert (name != null);
assert (enclosingType != null);
assert (type != null);
- JField x = new JField(info, name, enclosingType, type, isStatic,
- disposition);
+ JField x = new JField(info, name, enclosingType, type, isStatic, disposition);
if (indexedTypes.containsValue(enclosingType)) {
indexedFields.put(enclosingType.getShortName() + '.' + name, x);
@@ -521,15 +498,15 @@
return x;
}
- public JMethod createMethod(SourceInfo info, String name,
- JDeclaredType enclosingType, JType returnType, boolean isAbstract,
- boolean isStatic, boolean isFinal, boolean isPrivate, boolean isNative) {
+ public JMethod createMethod(SourceInfo info, String name, JDeclaredType enclosingType,
+ JType returnType, boolean isAbstract, boolean isStatic, boolean isFinal, boolean isPrivate,
+ boolean isNative) {
assert (name != null);
assert (enclosingType != null);
assert (returnType != null);
assert (!isAbstract || !isNative);
- JMethod x = new JMethod(info, name, enclosingType, returnType, isAbstract,
- isStatic, isFinal, isPrivate);
+ JMethod x =
+ new JMethod(info, name, enclosingType, returnType, isAbstract, isStatic, isFinal, isPrivate);
if (isNative) {
x.setBody(new JsniMethodBody(info));
} else if (!isAbstract) {
@@ -548,10 +525,8 @@
* Create a SourceInfo object when the source is derived from a physical
* location.
*/
- public SourceInfo createSourceInfo(int startPos, int endPos, int startLine,
- String fileName) {
- return correlator.makeSourceInfo(SourceOrigin.create(startPos, endPos,
- startLine, fileName));
+ public SourceInfo createSourceInfo(int startPos, int endPos, int startLine, String fileName) {
+ return correlator.makeSourceInfo(SourceOrigin.create(startPos, endPos, startLine, fileName));
}
/**
@@ -576,8 +551,7 @@
* Return the least upper bound of a set of types. That is, the smallest type
* that is a supertype of all the input types.
*/
- public JReferenceType generalizeTypes(
- Collection<? extends JReferenceType> types) {
+ public JReferenceType generalizeTypes(Collection<? extends JReferenceType> types) {
assert (types != null);
assert (!types.isEmpty());
Iterator<? extends JReferenceType> it = types.iterator();
@@ -592,8 +566,7 @@
* Return the least upper bound of two types. That is, the smallest type that
* is a supertype of both types.
*/
- public JReferenceType generalizeTypes(JReferenceType type1,
- JReferenceType type2) {
+ public JReferenceType generalizeTypes(JReferenceType type1, JReferenceType type2) {
if (type1 == type2) {
return type1;
}
@@ -667,8 +640,7 @@
JType leafType1 = aType1.getLeafType();
JType leafType2 = aType2.getLeafType();
- if (!(leafType1 instanceof JReferenceType)
- || !(leafType2 instanceof JReferenceType)) {
+ if (!(leafType1 instanceof JReferenceType) || !(leafType2 instanceof JReferenceType)) {
return minimalGeneralType;
}
@@ -680,8 +652,7 @@
*/
JReferenceType leafRefType1 = (JReferenceType) leafType1;
JReferenceType leafRefType2 = (JReferenceType) leafType2;
- JReferenceType leafGeneralization = generalizeTypes(leafRefType1,
- leafRefType2);
+ JReferenceType leafGeneralization = generalizeTypes(leafRefType1, leafRefType2);
return getTypeArray(leafGeneralization, dims1);
} else {
@@ -762,8 +733,7 @@
* over without introducing nondeterminism.
*/
public List<JArrayType> getAllArrayTypes() {
- ArrayList<JArrayType> result = new ArrayList<JArrayType>(
- arrayTypes.values());
+ ArrayList<JArrayType> result = new ArrayList<JArrayType>(arrayTypes.values());
Collections.sort(result, ARRAYTYPE_COMPARATOR);
return result;
}
@@ -785,8 +755,7 @@
JsonObject returnMap = castableTypeMaps.get(referenceType);
if (returnMap == null) {
// add a new empty map
- returnMap = new JsonObject(createSourceInfoSynthetic(JProgram.class),
- getJavaScriptObject());
+ returnMap = new JsonObject(createSourceInfoSynthetic(JProgram.class), getJavaScriptObject());
castableTypeMaps.put(referenceType, returnMap);
}
return returnMap;
@@ -817,8 +786,7 @@
public JField getIndexedField(String string) {
JField field = indexedFields.get(string);
if (field == null) {
- throw new InternalCompilerException("Unable to locate index field: "
- + string);
+ throw new InternalCompilerException("Unable to locate index field: " + string);
}
return field;
}
@@ -826,8 +794,7 @@
public JMethod getIndexedMethod(String string) {
JMethod method = indexedMethods.get(string);
if (method == null) {
- throw new InternalCompilerException("Unable to locate index method: "
- + string);
+ throw new InternalCompilerException("Unable to locate index method: " + string);
}
return method;
}
@@ -839,8 +806,7 @@
public JDeclaredType getIndexedType(String string) {
JDeclaredType type = indexedTypes.get(string);
if (type == null) {
- throw new InternalCompilerException("Unable to locate index type: "
- + string);
+ throw new InternalCompilerException("Unable to locate index type: " + string);
}
return type;
}
@@ -892,16 +858,18 @@
public JField getNullField() {
if (nullField == null) {
- nullField = new JField(createSourceInfoSynthetic(JProgram.class),
- "nullField", null, JNullType.INSTANCE, false, Disposition.FINAL);
+ nullField =
+ new JField(createSourceInfoSynthetic(JProgram.class), "nullField", null,
+ JNullType.INSTANCE, false, Disposition.FINAL);
}
return nullField;
}
public JMethod getNullMethod() {
if (nullMethod == null) {
- nullMethod = new JMethod(createSourceInfoSynthetic(JProgram.class),
- "nullMethod", null, JNullType.INSTANCE, false, false, true, false);
+ nullMethod =
+ new JMethod(createSourceInfoSynthetic(JProgram.class), "nullMethod", null,
+ JNullType.INSTANCE, false, false, true, false);
nullMethod.setSynthetic();
}
return nullMethod;
@@ -1048,8 +1016,7 @@
public boolean isJavaScriptObject(JType type) {
if (type instanceof JReferenceType && typeSpecialJavaScriptObject != null) {
- return typeOracle.canTriviallyCast((JReferenceType) type,
- typeSpecialJavaScriptObject);
+ return typeOracle.canTriviallyCast((JReferenceType) type, typeSpecialJavaScriptObject);
}
return false;
}
@@ -1064,8 +1031,8 @@
* supplied fragments, or it might be a common predecessor.
*/
public int lastFragmentLoadingBefore(int firstFragment, int... restFragments) {
- return lastFragmentLoadingBefore(splitPointInitialSequence,
- entryMethods.size() - 1, firstFragment, restFragments);
+ return lastFragmentLoadingBefore(splitPointInitialSequence, entryMethods.size() - 1,
+ firstFragment, restFragments);
}
public void putIntoTypeMap(String qualifiedBinaryName, JDeclaredType type) {
@@ -1170,8 +1137,7 @@
*
* @see #writeObject(ObjectOutputStream)
*/
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
allTypes = deserializeTypes(stream);
stream.defaultReadObject();
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JStringLiteral.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JStringLiteral.java
index ce1aae0..4ba909a 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JStringLiteral.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JStringLiteral.java
@@ -25,8 +25,7 @@
private final JClassType stringType;
private final String value;
- public JStringLiteral(SourceInfo sourceInfo, String value,
- JClassType stringType) {
+ public JStringLiteral(SourceInfo sourceInfo, String value, JClassType stringType) {
super(sourceInfo);
this.value = value;
this.stringType = stringType;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JTryStatement.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JTryStatement.java
index 75c3f56..1f2d0ca 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JTryStatement.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JTryStatement.java
@@ -29,8 +29,8 @@
private final JBlock finallyBlock;
private final JBlock tryBlock;
- public JTryStatement(SourceInfo info, JBlock tryBlock,
- List<JLocalRef> catchArgs, List<JBlock> catchBlocks, JBlock finallyBlock) {
+ public JTryStatement(SourceInfo info, JBlock tryBlock, List<JLocalRef> catchArgs,
+ List<JBlock> catchBlocks, JBlock finallyBlock) {
super(info);
assert (catchArgs.size() == catchBlocks.size());
this.tryBlock = tryBlock;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JTypeOracle.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JTypeOracle.java
index 6be467b..e43a25e 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JTypeOracle.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JTypeOracle.java
@@ -192,13 +192,15 @@
* A map of all interfaces to the set of classes that could theoretically
* implement them.
*/
- private final Map<JInterfaceType, Set<JClassType>> couldBeImplementedMap = new IdentityHashMap<JInterfaceType, Set<JClassType>>();
+ private final Map<JInterfaceType, Set<JClassType>> couldBeImplementedMap =
+ new IdentityHashMap<JInterfaceType, Set<JClassType>>();
/**
* A map of all classes to the set of interfaces that they could theoretically
* implement.
*/
- private final Map<JClassType, Set<JInterfaceType>> couldImplementMap = new IdentityHashMap<JClassType, Set<JInterfaceType>>();
+ private final Map<JClassType, Set<JInterfaceType>> couldImplementMap =
+ new IdentityHashMap<JClassType, Set<JInterfaceType>>();
/**
* The set of all interfaces that are initially implemented by both a Java and
@@ -210,7 +212,8 @@
* A map of all classes to the set of interfaces they directly implement,
* possibly through inheritance.
*/
- private final Map<JClassType, Set<JInterfaceType>> implementsMap = new IdentityHashMap<JClassType, Set<JInterfaceType>>();
+ private final Map<JClassType, Set<JInterfaceType>> implementsMap =
+ new IdentityHashMap<JClassType, Set<JInterfaceType>>();
/**
* The types in the program that are instantiable. All types in this set
@@ -223,7 +226,8 @@
* A map of all interfaces to the set of classes that directly implement them,
* possibly through inheritance.
*/
- private final Map<JInterfaceType, Set<JClassType>> isImplementedMap = new IdentityHashMap<JInterfaceType, Set<JClassType>>();
+ private final Map<JInterfaceType, Set<JClassType>> isImplementedMap =
+ new IdentityHashMap<JInterfaceType, Set<JClassType>>();
private JDeclaredType javaIoSerializable;
@@ -238,7 +242,8 @@
* A map of all interfaces that are implemented by overlay types to the
* overlay type that initially implements it.
*/
- private final Map<JInterfaceType, JClassType> jsoSingleImpls = new IdentityHashMap<JInterfaceType, JClassType>();
+ private final Map<JInterfaceType, JClassType> jsoSingleImpls =
+ new IdentityHashMap<JInterfaceType, JClassType>();
/**
* The associated {@link JProgram}.
@@ -249,25 +254,29 @@
* A map of all classes to the set of classes that extend them, directly or
* indirectly.
*/
- private final Map<JClassType, Set<JClassType>> subClassMap = new IdentityHashMap<JClassType, Set<JClassType>>();
+ private final Map<JClassType, Set<JClassType>> subClassMap =
+ new IdentityHashMap<JClassType, Set<JClassType>>();
/**
* A map of all interfaces to the set of interfaces that extend them, directly
* or indirectly.
*/
- private final Map<JInterfaceType, Set<JInterfaceType>> subInterfaceMap = new IdentityHashMap<JInterfaceType, Set<JInterfaceType>>();
+ private final Map<JInterfaceType, Set<JInterfaceType>> subInterfaceMap =
+ new IdentityHashMap<JInterfaceType, Set<JInterfaceType>>();
/**
* A map of all classes to the set of classes they extend, directly or
* indirectly.
*/
- private final Map<JClassType, Set<JClassType>> superClassMap = new IdentityHashMap<JClassType, Set<JClassType>>();
+ private final Map<JClassType, Set<JClassType>> superClassMap =
+ new IdentityHashMap<JClassType, Set<JClassType>>();
/**
* A map of all interfaces to the set of interfaces they extend, directly or
* indirectly.
*/
- private final Map<JInterfaceType, Set<JInterfaceType>> superInterfaceMap = new IdentityHashMap<JInterfaceType, Set<JInterfaceType>>();
+ private final Map<JInterfaceType, Set<JInterfaceType>> superInterfaceMap =
+ new IdentityHashMap<JInterfaceType, Set<JInterfaceType>>();
/**
* A map of all methods with virtual overrides, onto the collection of
* overridden methods. Each key method's collections is a map of the set of
@@ -275,7 +284,8 @@
* methods the key method virtually implements. For a definition of a virtual
* override, see {@link #getAllVirtualOverrides(JMethod)}.
*/
- private final Map<JMethod, Map<JClassType, Set<JMethod>>> virtualUpRefMap = new IdentityHashMap<JMethod, Map<JClassType, Set<JMethod>>>();
+ private final Map<JMethod, Map<JClassType, Set<JMethod>>> virtualUpRefMap =
+ new IdentityHashMap<JMethod, Map<JClassType, Set<JMethod>>>();
public JTypeOracle(JProgram program) {
this.program = program;
@@ -283,6 +293,7 @@
/**
* True if the type is a JSO or interface implemented by JSO..
+ *
* @param type
* @return
*/
@@ -290,8 +301,7 @@
if (type instanceof JNonNullType) {
type = ((JNonNullType) type).getUnderlyingType();
}
- return program.isJavaScriptObject(type)
- || program.typeOracle.isSingleJsoImpl(type);
+ return program.isJavaScriptObject(type) || program.typeOracle.isSingleJsoImpl(type);
}
public boolean canTheoreticallyCast(JReferenceType type, JReferenceType qType) {
@@ -316,7 +326,7 @@
if (canBeJavaScriptObject(type) && canBeJavaScriptObject(qType)) {
return true;
}
-
+
if (canTriviallyCast(type, qType)) {
return true;
}
@@ -338,10 +348,8 @@
}
if (dims == qDims) {
- if (leafType instanceof JReferenceType
- && qLeafType instanceof JReferenceType) {
- return canTheoreticallyCast((JReferenceType) leafType,
- (JReferenceType) qLeafType);
+ if (leafType instanceof JReferenceType && qLeafType instanceof JReferenceType) {
+ return canTheoreticallyCast((JReferenceType) leafType, (JReferenceType) qLeafType);
}
}
}
@@ -398,16 +406,13 @@
int qDims = qaType.getDims();
// int[][] -> Object[] or null[] trivially true
- if (dims > qDims
- && (qLeafType == jlo || qLeafType instanceof JNullType)) {
+ if (dims > qDims && (qLeafType == jlo || qLeafType instanceof JNullType)) {
return true;
}
if (dims == qDims) {
- if (leafType instanceof JReferenceType
- && qLeafType instanceof JReferenceType) {
- return canTriviallyCast((JReferenceType) leafType,
- (JReferenceType) qLeafType);
+ if (leafType instanceof JReferenceType && qLeafType instanceof JReferenceType) {
+ return canTriviallyCast((JReferenceType) leafType, (JReferenceType) qLeafType);
}
}
}
@@ -443,8 +448,7 @@
public boolean canTriviallyCast(JType type, JType qType) {
if (type instanceof JPrimitiveType && qType instanceof JPrimitiveType) {
return type == qType;
- } else if (type instanceof JReferenceType
- && qType instanceof JReferenceType) {
+ } else if (type instanceof JReferenceType && qType instanceof JReferenceType) {
return canTriviallyCast((JReferenceType) type, (JReferenceType) qType);
}
return false;
@@ -474,9 +478,9 @@
}
}
- /*
- * Now that the basic type hierarchy is computed, compute which
- * JSOs implement interfaces singlely or dually.
+ /*
+ * Now that the basic type hierarchy is computed, compute which JSOs
+ * implement interfaces singlely or dually.
*/
JClassType jsoType = program.getJavaScriptObject();
List<JClassType> jsoSubTypes = Lists.create();
@@ -531,8 +535,7 @@
* References to any methods which this method implementation might override
* or implement in any instantiable class.
*/
- public Set<JMethod> getAllOverrides(JMethod method,
- Set<JReferenceType> instantiatedTypes) {
+ public Set<JMethod> getAllOverrides(JMethod method, Set<JReferenceType> instantiatedTypes) {
Set<JMethod> results = new IdentityHashSet<JMethod>();
getAllRealOverrides(method, results);
getAllVirtualOverrides(method, instantiatedTypes, results);
@@ -591,30 +594,28 @@
}
/**
- * True if either a JSO, or is an interface that is ONLY
- * implemented by a JSO.
- */
- public boolean isEffectivelyJavaScriptObject(JType type) {
- if (type instanceof JReferenceType) {
- JReferenceType refType = (JReferenceType) type;
- return program.isJavaScriptObject(refType) ||
- (isSingleJsoImpl(refType) && !isDualJsoInterface(refType));
- } else {
- return false;
- }
- }
+ * True if either a JSO, or is an interface that is ONLY implemented by a JSO.
+ */
+ public boolean isEffectivelyJavaScriptObject(JType type) {
+ if (type instanceof JReferenceType) {
+ JReferenceType refType = (JReferenceType) type;
+ return program.isJavaScriptObject(refType)
+ || (isSingleJsoImpl(refType) && !isDualJsoInterface(refType));
+ } else {
+ return false;
+ }
+ }
public boolean isInstantiatedType(JReferenceType type) {
return isInstantiatedType(type, instantiatedTypes);
}
public boolean isSameOrSuper(JClassType type, JClassType qType) {
- return (type == qType || isSuperClass(type, qType));
+ return (type == qType || isSuperClass(type, qType));
}
public boolean isSingleJsoImpl(JType type) {
- return type instanceof JReferenceType
- && getSingleJsoImpl((JReferenceType) type) != null;
+ return type instanceof JReferenceType && getSingleJsoImpl((JReferenceType) type) != null;
}
/**
@@ -641,13 +642,11 @@
for (JDeclaredType type : program.getDeclaredTypes()) {
computeClinitTarget(type, computed);
}
- nextDual: for (Iterator<JInterfaceType> it = dualImpls.iterator();
- it.hasNext();) {
+ nextDual : for (Iterator<JInterfaceType> it = dualImpls.iterator(); it.hasNext();) {
JInterfaceType dualIntf = it.next();
Set<JClassType> implementors = get(isImplementedMap, dualIntf);
for (JClassType implementor : implementors) {
- if (isInstantiatedType(implementor)
- && !program.isJavaScriptObject(implementor)) {
+ if (isInstantiatedType(implementor) && !program.isJavaScriptObject(implementor)) {
// This dual is still implemented by a Java class.
continue nextDual;
}
@@ -674,8 +673,7 @@
getOrCreate(map, key).add(value);
}
- private void computeClinitTarget(JDeclaredType type,
- Set<JDeclaredType> computed) {
+ private void computeClinitTarget(JDeclaredType type, Set<JDeclaredType> computed) {
if (type.isExternal() || !type.hasClinit() || computed.contains(type)) {
return;
}
@@ -696,8 +694,8 @@
type.setClinitTarget(superClass.getClinitTarget());
} else {
// I still have a real clinit, actually compute.
- JDeclaredType target = computeClinitTargetRecursive(type, computed,
- new IdentityHashSet<JDeclaredType>());
+ JDeclaredType target =
+ computeClinitTargetRecursive(type, computed, new IdentityHashSet<JDeclaredType>());
type.setClinitTarget(target);
}
computed.add(type);
@@ -848,7 +846,8 @@
// this class does not directly implement the interface method
// if any super classes do, create a virtual up ref
- for (JClassType superType = type.getSuperClass(); superType != javaLangObject; superType = superType.getSuperClass()) {
+ for (JClassType superType = type.getSuperClass(); superType != javaLangObject; superType =
+ superType.getSuperClass()) {
for (JMethod superMethod : superType.getMethods()) {
if (methodsDoMatch(intfMethod, superMethod)) {
// this super class directly implements the interface method
@@ -858,8 +857,8 @@
// + "." + superMethod.getName() + " to " + intf.getName() + "."
// + intfMethod.getName() + " via " + type.getName());
- Map<JClassType, Set<JMethod>> classToMethodMap = getOrCreateMap(
- virtualUpRefMap, superMethod);
+ Map<JClassType, Set<JMethod>> classToMethodMap =
+ getOrCreateMap(virtualUpRefMap, superMethod);
add(classToMethodMap, type, intfMethod);
// do not search additional super types
@@ -892,8 +891,8 @@
}
}
- private void getAllVirtualOverrides(JMethod method,
- Set<JReferenceType> instantiatedTypes, Set<JMethod> results) {
+ private void getAllVirtualOverrides(JMethod method, Set<JReferenceType> instantiatedTypes,
+ Set<JMethod> results) {
Map<JClassType, Set<JMethod>> overrideMap = virtualUpRefMap.get(method);
if (overrideMap != null) {
for (Map.Entry<JClassType, Set<JMethod>> entry : overrideMap.entrySet()) {
@@ -941,8 +940,7 @@
* are instantiated.
* @return whether the type is instantiated
*/
- private boolean isInstantiatedType(JReferenceType type,
- Set<JReferenceType> instantiatedTypes) {
+ private boolean isInstantiatedType(JReferenceType type, Set<JReferenceType> instantiatedTypes) {
type = type.getUnderlyingType();
if (type.isExternal()) {
@@ -1003,8 +1001,8 @@
/**
* Recursively record all of my super interfaces.
*/
- private void recordSuperSubInfo(JInterfaceType base,
- Set<JInterfaceType> superSet, JInterfaceType cur) {
+ private void recordSuperSubInfo(JInterfaceType base, Set<JInterfaceType> superSet,
+ JInterfaceType cur) {
for (JInterfaceType intf : cur.getImplements()) {
superSet.add(intf);
add(subInterfaceMap, intf, base);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JVariable.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JVariable.java
index 0338a67..13bdb59 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JVariable.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JVariable.java
@@ -21,8 +21,8 @@
/**
* Base class for any storage location.
*/
-public abstract class JVariable extends JNode implements CanBeSetFinal,
- CanHaveInitializer, HasName, HasType {
+public abstract class JVariable extends JNode implements CanBeSetFinal, CanHaveInitializer,
+ HasName, HasType {
protected JDeclarationStatement declStmt = null;
private boolean isFinal;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/JVisitor.java b/dev/core/src/com/google/gwt/dev/jjs/ast/JVisitor.java
index ae7c201..b043a1c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/JVisitor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/JVisitor.java
@@ -95,8 +95,7 @@
};
- protected static InternalCompilerException translateException(JNode node,
- Throwable e) {
+ protected static InternalCompilerException translateException(JNode node, Throwable e) {
if (e instanceof VirtualMachineError) {
// Always rethrow VM errors (an attempt to wrap may fail).
throw (VirtualMachineError) e;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniFieldRef.java b/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniFieldRef.java
index 0accf75..862b9c3 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniFieldRef.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniFieldRef.java
@@ -31,10 +31,9 @@
private final String ident;
private final boolean isLvalue;
- public JsniFieldRef(SourceInfo info, String ident, JField field,
- JDeclaredType enclosingType, boolean isLvalue) {
- super(info, field.isStatic() ? null : JNullLiteral.INSTANCE, field,
- enclosingType);
+ public JsniFieldRef(SourceInfo info, String ident, JField field, JDeclaredType enclosingType,
+ boolean isLvalue) {
+ super(info, field.isStatic() ? null : JNullLiteral.INSTANCE, field, enclosingType);
this.ident = ident;
this.isLvalue = isLvalue;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniMethodRef.java b/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniMethodRef.java
index ef11525..189390b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniMethodRef.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsniMethodRef.java
@@ -32,8 +32,7 @@
private final String ident;
private final JClassType jsoType;
- public JsniMethodRef(SourceInfo info, String ident, JMethod method,
- JClassType jsoType) {
+ public JsniMethodRef(SourceInfo info, String ident, JMethod method, JClassType jsoType) {
// Just use a null literal as the qualifier on a non-static method
super(info, method.isStatic() ? null : JNullLiteral.INSTANCE, method);
this.ident = ident;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsonObject.java b/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsonObject.java
index ee749ca..627f14f 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsonObject.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/ast/js/JsonObject.java
@@ -39,8 +39,7 @@
public JExpression labelExpr;
public JExpression valueExpr;
- public JsonPropInit(SourceInfo sourceInfo, JExpression labelExpr,
- JExpression valueExpr) {
+ public JsonPropInit(SourceInfo sourceInfo, JExpression labelExpr, JExpression valueExpr) {
super(sourceInfo);
this.labelExpr = labelExpr;
this.valueExpr = valueExpr;
@@ -70,8 +69,7 @@
@Override
public boolean hasSideEffects() {
for (JsonPropInit propInit : propInits) {
- if (propInit.labelExpr.hasSideEffects()
- || propInit.valueExpr.hasSideEffects()) {
+ if (propInit.labelExpr.hasSideEffects() || propInit.valueExpr.hasSideEffects()) {
return true;
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ArrayNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ArrayNormalizer.java
index e023e72..74d5d87 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ArrayNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ArrayNormalizer.java
@@ -62,14 +62,11 @@
*/
if (elementType instanceof JReferenceType) {
if (!((JReferenceType) elementType).isFinal()
- || !program.typeOracle.canTriviallyCast(
- (JReferenceType) x.getRhs().getType(),
+ || !program.typeOracle.canTriviallyCast((JReferenceType) x.getRhs().getType(),
(JReferenceType) elementType)) {
// replace this assignment with a call to setCheck()
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null,
- setCheckMethod);
- call.addArgs(arrayRef.getInstance(), arrayRef.getIndexExpr(),
- x.getRhs());
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, setCheckMethod);
+ call.addArgs(arrayRef.getInstance(), arrayRef.getIndexExpr(), x.getRhs());
ctx.replaceMe(call);
}
}
@@ -121,31 +118,24 @@
private void processDim(JNewArray x, Context ctx, JArrayType arrayType) {
// override the type of the called method with the array's type
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null, initDim,
- arrayType);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, initDim, arrayType);
JLiteral classLit = x.getClassLiteral();
JsonObject castableTypeMap = program.getCastableTypeMap(arrayType);
JLiteral queryIdLit = program.getLiteralInt(tryGetQueryId(arrayType));
JExpression dim = x.dims.get(0);
JType elementType = arrayType.getElementType();
- call.addArgs(classLit, castableTypeMap, queryIdLit, dim,
- getSeedTypeLiteralFor(elementType));
+ call.addArgs(classLit, castableTypeMap, queryIdLit, dim, getSeedTypeLiteralFor(elementType));
ctx.replaceMe(call);
}
- private void processDims(JNewArray x, Context ctx, JArrayType arrayType,
- int dims) {
+ private void processDims(JNewArray x, Context ctx, JArrayType arrayType, int dims) {
// override the type of the called method with the array's type
SourceInfo sourceInfo = x.getSourceInfo();
JMethodCall call = new JMethodCall(sourceInfo, null, initDims, arrayType);
- JsonArray classLitList = new JsonArray(sourceInfo,
- program.getJavaScriptObject());
- JsonArray castableTypeMapList = new JsonArray(sourceInfo,
- program.getJavaScriptObject());
- JsonArray queryIdList = new JsonArray(sourceInfo,
- program.getJavaScriptObject());
- JsonArray dimList = new JsonArray(sourceInfo,
- program.getJavaScriptObject());
+ JsonArray classLitList = new JsonArray(sourceInfo, program.getJavaScriptObject());
+ JsonArray castableTypeMapList = new JsonArray(sourceInfo, program.getJavaScriptObject());
+ JsonArray queryIdList = new JsonArray(sourceInfo, program.getJavaScriptObject());
+ JsonArray dimList = new JsonArray(sourceInfo, program.getJavaScriptObject());
JType cur = arrayType;
for (int i = 0; i < dims; ++i) {
// Walk down each type from most dims to least.
@@ -153,7 +143,7 @@
JLiteral classLit = x.getClassLiterals().get(i);
classLitList.exprs.add(classLit);
-
+
JsonObject castableTypeMap = program.getCastableTypeMap(curArrayType);
castableTypeMapList.exprs.add(castableTypeMap);
@@ -163,22 +153,19 @@
dimList.exprs.add(x.dims.get(i));
cur = curArrayType.getElementType();
}
- call.addArgs(classLitList, castableTypeMapList, queryIdList,
- dimList, program.getLiteralInt(dims), getSeedTypeLiteralFor(cur));
+ call.addArgs(classLitList, castableTypeMapList, queryIdList, dimList, program
+ .getLiteralInt(dims), getSeedTypeLiteralFor(cur));
ctx.replaceMe(call);
}
- private void processInitializers(JNewArray x, Context ctx,
- JArrayType arrayType) {
+ private void processInitializers(JNewArray x, Context ctx, JArrayType arrayType) {
// override the type of the called method with the array's type
SourceInfo sourceInfo = x.getSourceInfo();
- JMethodCall call = new JMethodCall(sourceInfo, null, initValues,
- arrayType);
+ JMethodCall call = new JMethodCall(sourceInfo, null, initValues, arrayType);
JLiteral classLit = x.getClassLiteral();
JsonObject castableTypeMap = program.getCastableTypeMap(arrayType);
JLiteral queryIdLit = program.getLiteralInt(tryGetQueryId(arrayType));
- JsonArray initList = new JsonArray(sourceInfo,
- program.getJavaScriptObject());
+ JsonArray initList = new JsonArray(sourceInfo, program.getJavaScriptObject());
for (int i = 0; i < x.initializers.size(); ++i) {
initList.exprs.add(x.initializers.get(i));
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionNormalizer.java
index 3e0e241..468d6d2f 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionNormalizer.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -44,15 +44,15 @@
@Override
public void endVisit(JAssertStatement x, Context ctx) {
JExpression lhs = x.getTestExpr();
- String methodName = "Exceptions.throwAssertionError"
- + getAssertMethodSuffix(x.getArg());
+ String methodName = "Exceptions.throwAssertionError" + getAssertMethodSuffix(x.getArg());
JMethod method = program.getIndexedMethod(methodName);
JMethodCall rhs = new JMethodCall(x.getSourceInfo(), null, method);
if (x.getArg() != null) {
rhs.addArg(x.getArg());
}
- JBinaryOperation binOp = new JBinaryOperation(x.getSourceInfo(), program.getTypePrimitiveBoolean(),
- JBinaryOperator.OR, lhs, rhs);
+ JBinaryOperation binOp =
+ new JBinaryOperation(x.getSourceInfo(), program.getTypePrimitiveBoolean(),
+ JBinaryOperator.OR, lhs, rhs);
ctx.replaceMe(binOp.makeStatement());
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionRemover.java b/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionRemover.java
index 70fc984..d8ff00d 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionRemover.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/AssertionRemover.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/AstDumper.java b/dev/core/src/com/google/gwt/dev/jjs/impl/AstDumper.java
index 9897530..576444b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/AstDumper.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/AstDumper.java
@@ -26,29 +26,30 @@
/**
* A simple utility to dump a JProgram to a temp file, which can be called
- * sequentially during a compilation/optimization run, so intermediate steps
- * can be compared.
+ * sequentially during a compilation/optimization run, so intermediate steps can
+ * be compared.
*
- * It uses the system property "gwt.jjs.dumpAst" to determine the name
- * (or prefix) of the file to dump the AST to.
+ * It uses the system property "gwt.jjs.dumpAst" to determine the name (or
+ * prefix) of the file to dump the AST to.
*
- * TODO(jbrosenberg): Add proper logging and/or exception handling for the
+ * TODO(jbrosenberg): Add proper logging and/or exception handling for the
* potential IOException that might occur when writing the file.
*/
public class AstDumper {
-
+
private static int autoVersionNumber = 0;
-
+
/**
- * Appends a new version of the AST at the end of the file, each time it's called.
+ * Appends a new version of the AST at the end of the file, each time it's
+ * called.
*/
public static void maybeDumpAST(JProgram jprogram) {
maybeDumpAST(jprogram, null, true);
}
-
+
/**
- * Writes the AST to the file with a versioned extension, using an
- * auto-incrementing version number (starting from 1), each time it's called.
+ * Writes the AST to the file with a versioned extension, using an
+ * auto-incrementing version number (starting from 1), each time it's called.
* Any previous contents of the file written to will be overwritten.
*/
public static void maybeDumpAST(JProgram jprogram, boolean autoIncrementVersion) {
@@ -58,27 +59,26 @@
maybeDumpAST(jprogram, autoVersionNumber++);
}
}
-
+
/**
- * Writes the AST to the file with the provided version number extension.
- * Any previous contents of the file written to will be overwritten.
+ * Writes the AST to the file with the provided version number extension. Any
+ * previous contents of the file written to will be overwritten.
*/
public static void maybeDumpAST(JProgram jprogram, int versionNumber) {
String fileExtension = "." + versionNumber;
maybeDumpAST(jprogram, fileExtension, false);
}
-
+
/**
- * Writes the AST to the file with the provided version string extension.
- * Any previous contents of the file written to will be overwritten.
+ * Writes the AST to the file with the provided version string extension. Any
+ * previous contents of the file written to will be overwritten.
*/
public static void maybeDumpAST(JProgram jprogram, String versionString) {
String fileExtension = "." + versionString;
maybeDumpAST(jprogram, fileExtension, false);
}
-
- private static void maybeDumpAST(JProgram jprogram,
- String fileExtension, boolean append) {
+
+ private static void maybeDumpAST(JProgram jprogram, String fileExtension, boolean append) {
String dumpFile = System.getProperty("gwt.jjs.dumpAst");
if (dumpFile != null) {
if (fileExtension != null) {
@@ -99,6 +99,6 @@
System.out.println("Could not dump AST");
e.printStackTrace();
}
- }
+ }
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/AutoboxUtils.java b/dev/core/src/com/google/gwt/dev/jjs/impl/AutoboxUtils.java
index ef11d1c..040de32 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/AutoboxUtils.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/AutoboxUtils.java
@@ -61,17 +61,16 @@
/**
* Box the expression <code>toBox</code> into the wrapper type corresponding
- * to <code>primitiveType</code>. If <code>toBox</code> is not already of
- * type <code>primitiveType</code>, then a cast may be necessary.
+ * to <code>primitiveType</code>. If <code>toBox</code> is not already of type
+ * <code>primitiveType</code>, then a cast may be necessary.
*/
public JExpression box(JExpression toBox, JPrimitiveType primitiveType) {
// Find the wrapper type for this primitive type.
String wrapperTypeName = primitiveType.getWrapperTypeName();
JClassType wrapperType = (JClassType) program.getFromTypeMap(wrapperTypeName);
if (wrapperType == null) {
- throw new InternalCompilerException(toBox, "Cannot find wrapper type '"
- + wrapperTypeName + "' associated with primitive type '"
- + primitiveType.getName() + "'", null);
+ throw new InternalCompilerException(toBox, "Cannot find wrapper type '" + wrapperTypeName
+ + "' associated with primitive type '" + primitiveType.getName() + "'", null);
}
return box(toBox, primitiveType, wrapperType);
@@ -100,8 +99,7 @@
return null;
}
- private JExpression box(JExpression toBox, JPrimitiveType primitiveType,
- JClassType wrapperType) {
+ private JExpression box(JExpression toBox, JPrimitiveType primitiveType, JClassType wrapperType) {
// Add a cast to toBox if need be
if (toBox.getType() != primitiveType) {
toBox = new JCastOperation(toBox.getSourceInfo(), primitiveType, toBox);
@@ -124,11 +122,9 @@
if (valueOfMethod == null || !valueOfMethod.isStatic()
|| valueOfMethod.getType() != wrapperType) {
- throw new InternalCompilerException(toBox,
- "Expected to find a method on '" + wrapperType.getName()
- + "' whose signature matches 'public static "
- + wrapperType.getName() + " valueOf(" + primitiveType.getName()
- + ")'", null);
+ throw new InternalCompilerException(toBox, "Expected to find a method on '"
+ + wrapperType.getName() + "' whose signature matches 'public static "
+ + wrapperType.getName() + " valueOf(" + primitiveType.getName() + ")'", null);
}
// Create the boxing call.
@@ -169,8 +165,7 @@
if (boxType != null) {
for (JMethod method : boxType.getMethods()) {
if (!method.isStatic() && method.getParams().isEmpty()
- && method.getName().endsWith("Value")
- && (method.getType() instanceof JPrimitiveType)) {
+ && method.getName().endsWith("Value") && (method.getType() instanceof JPrimitiveType)) {
unboxMethods.add(method);
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/BuildTypeMap.java b/dev/core/src/com/google/gwt/dev/jjs/impl/BuildTypeMap.java
index d0c0a46..cab8d72 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/BuildTypeMap.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/BuildTypeMap.java
@@ -119,15 +119,14 @@
private String currentFileName;
private int[] currentSeparatorPositions;
- private List<TypeDeclaration> typeDecls = new ArrayList<TypeDeclaration>();
+ private final List<TypeDeclaration> typeDecls = new ArrayList<TypeDeclaration>();
public TypeDeclaration[] getTypeDeclarataions() {
return typeDecls.toArray(new TypeDeclaration[typeDecls.size()]);
}
@Override
- public boolean visit(AnnotationMethodDeclaration methodDeclaration,
- ClassScope scope) {
+ public boolean visit(AnnotationMethodDeclaration methodDeclaration, ClassScope scope) {
return visit((MethodDeclaration) methodDeclaration, scope);
}
@@ -146,8 +145,9 @@
SourceInfo info = makeSourceInfo(argument, enclosingBody.getMethod());
LocalVariableBinding b = argument.binding;
JType localType = getType(b.type);
- JLocal newLocal = JProgram.createLocal(info, String.valueOf(argument.name),
- localType, b.isFinal(), enclosingBody);
+ JLocal newLocal =
+ JProgram.createLocal(info, String.valueOf(argument.name), localType, b.isFinal(),
+ enclosingBody);
typeMap.put(b, newLocal);
return true;
} catch (Throwable e) {
@@ -159,8 +159,7 @@
public boolean visit(ConstructorDeclaration ctorDecl, ClassScope scope) {
try {
MethodBinding b = ctorDecl.binding;
- JClassType enclosingType = (JClassType) getType(
- scope.enclosingSourceType());
+ JClassType enclosingType = (JClassType) getType(scope.enclosingSourceType());
SourceInfo info = makeSourceInfo(ctorDecl, enclosingType);
processConstructor(b, ctorDecl, info);
return true;
@@ -173,12 +172,10 @@
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
try {
FieldBinding b = fieldDeclaration.binding;
- JDeclaredType enclosingType = (JDeclaredType) getType(
- scope.enclosingSourceType());
+ JDeclaredType enclosingType = (JDeclaredType) getType(scope.enclosingSourceType());
SourceInfo info = makeSourceInfo(fieldDeclaration, enclosingType);
Expression initialization = fieldDeclaration.initialization;
- if (initialization != null
- && initialization instanceof AllocationExpression
+ if (initialization != null && initialization instanceof AllocationExpression
&& ((AllocationExpression) initialization).enumConstant != null) {
createEnumField(info, b, enclosingType);
} else {
@@ -208,9 +205,9 @@
return true;
}
SourceInfo info = makeSourceInfo(localDeclaration, enclosingBody.getMethod());
- JLocal newLocal = JProgram.createLocal(info,
- String.valueOf(localDeclaration.name), localType, b.isFinal(),
- enclosingBody);
+ JLocal newLocal =
+ JProgram.createLocal(info, String.valueOf(localDeclaration.name), localType, b
+ .isFinal(), enclosingBody);
typeMap.put(b, newLocal);
return true;
} catch (Throwable e) {
@@ -222,8 +219,7 @@
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
try {
MethodBinding b = methodDeclaration.binding;
- JDeclaredType enclosingType = (JDeclaredType) getType(
- scope.enclosingSourceType());
+ JDeclaredType enclosingType = (JDeclaredType) getType(scope.enclosingSourceType());
SourceInfo info = makeSourceInfo(methodDeclaration, enclosingType);
JMethod newMethod = processMethodBinding(b, enclosingType, info);
SourceInfo methodInfo = makeSourceInfo(methodDeclaration, newMethod);
@@ -246,23 +242,21 @@
}
@Override
- public boolean visit(TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
+ public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
return process(typeDeclaration);
}
@Override
- public boolean visitValid(TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
+ public boolean visitValid(TypeDeclaration localTypeDeclaration, BlockScope scope) {
return process(localTypeDeclaration);
}
private JField createEnumField(SourceInfo info, FieldBinding binding,
JReferenceType enclosingType) {
JType type = getType(binding.type);
- JField field = program.createEnumField(info,
- String.valueOf(binding.name), (JEnumType) enclosingType,
- (JClassType) type, binding.original().id);
+ JField field =
+ program.createEnumField(info, String.valueOf(binding.name), (JEnumType) enclosingType,
+ (JClassType) type, binding.original().id);
info.addCorrelation(info.getCorrelator().by(field));
typeMap.put(binding, field);
return field;
@@ -272,8 +266,8 @@
JMethod method;
MethodScope methodScope = scope.methodScope();
if (methodScope.isInsideInitializer()) {
- JDeclaredType enclosingType = (JDeclaredType) getType(
- scope.classScope().referenceContext.binding);
+ JDeclaredType enclosingType =
+ (JDeclaredType) getType(scope.classScope().referenceContext.binding);
if (methodScope.isStatic) {
// clinit
method = enclosingType.getMethods().get(0);
@@ -287,16 +281,16 @@
method = (JMethod) typeMap.get(referenceMethod.binding);
}
assert !method.isNative() && !method.isAbstract();
- return (JMethodBody) (method.getEnclosingType().isExternal() ? null :
- method.getBody());
+ return (JMethodBody) (method.getEnclosingType().isExternal() ? null : method.getBody());
}
- private SourceInfo makeSourceInfo(AbstractMethodDeclaration methodDecl,
- HasSourceInfo enclosing) {
- int startLine = Util.getLineNumber(methodDecl.sourceStart,
- currentSeparatorPositions, 0, currentSeparatorPositions.length - 1);
- SourceOrigin toReturn = SourceOrigin.create(methodDecl.sourceStart,
- methodDecl.bodyEnd, startLine, currentFileName);
+ private SourceInfo makeSourceInfo(AbstractMethodDeclaration methodDecl, HasSourceInfo enclosing) {
+ int startLine =
+ Util.getLineNumber(methodDecl.sourceStart, currentSeparatorPositions, 0,
+ currentSeparatorPositions.length - 1);
+ SourceOrigin toReturn =
+ SourceOrigin.create(methodDecl.sourceStart, methodDecl.bodyEnd, startLine,
+ currentFileName);
if (enclosing != null) {
return enclosing.getSourceInfo().makeChild(toReturn);
}
@@ -304,10 +298,11 @@
}
private SourceInfo makeSourceInfo(Statement stmt, HasSourceInfo enclosing) {
- int startLine = Util.getLineNumber(stmt.sourceStart,
- currentSeparatorPositions, 0, currentSeparatorPositions.length - 1);
- SourceOrigin toReturn = SourceOrigin.create(stmt.sourceStart,
- stmt.sourceEnd, startLine, currentFileName);
+ int startLine =
+ Util.getLineNumber(stmt.sourceStart, currentSeparatorPositions, 0,
+ currentSeparatorPositions.length - 1);
+ SourceOrigin toReturn =
+ SourceOrigin.create(stmt.sourceStart, stmt.sourceEnd, startLine, currentFileName);
if (enclosing != null) {
return enclosing.getSourceInfo().makeChild(toReturn);
}
@@ -339,15 +334,15 @@
return false;
}
- private void processNativeMethod(MethodDeclaration methodDeclaration,
- SourceInfo info, JDeclaredType enclosingType, JMethod newMethod) {
+ private void processNativeMethod(MethodDeclaration methodDeclaration, SourceInfo info,
+ JDeclaredType enclosingType, JMethod newMethod) {
// TODO: use existing parsed JSNI functions from CompilationState.
// Handle JSNI block
char[] source = methodDeclaration.compilationResult().getCompilationUnit().getContents();
String unitSource = String.valueOf(source);
- JsFunction jsFunction = JsniCollector.parseJsniFunction(
- methodDeclaration, unitSource, enclosingType.getName(), info,
- jsProgram.getScope());
+ JsFunction jsFunction =
+ JsniCollector.parseJsniFunction(methodDeclaration, unitSource, enclosingType.getName(),
+ info, jsProgram.getScope());
if (jsFunction != null) {
jsFunction.setFromJava(true);
((JsniMethodBody) newMethod.getBody()).setFunc(jsFunction);
@@ -358,8 +353,7 @@
}
}
- private InternalCompilerException translateException(
- AbstractMethodDeclaration amd, Throwable e) {
+ private InternalCompilerException translateException(AbstractMethodDeclaration amd, Throwable e) {
if (e instanceof VirtualMachineError) {
// Always rethrow VM errors (an attempt to wrap may fail).
throw (VirtualMachineError) e;
@@ -370,13 +364,11 @@
} else {
ice = new InternalCompilerException("Error building type map", e);
}
- ice.addNode(amd.getClass().getName(), amd.toString(), makeSourceInfo(amd,
- null));
+ ice.addNode(amd.getClass().getName(), amd.toString(), makeSourceInfo(amd, null));
return ice;
}
- private InternalCompilerException translateException(Statement stmt,
- Throwable e) {
+ private InternalCompilerException translateException(Statement stmt, Throwable e) {
if (e instanceof VirtualMachineError) {
// Always rethrow VM errors (an attempt to wrap may fail).
throw (VirtualMachineError) e;
@@ -387,8 +379,7 @@
} else {
ice = new InternalCompilerException("Error building type map", e);
}
- ice.addNode(stmt.getClass().getName(), stmt.toString(), makeSourceInfo(
- stmt, null));
+ ice.addNode(stmt.getClass().getName(), stmt.toString(), makeSourceInfo(stmt, null));
return ice;
}
}
@@ -407,14 +398,12 @@
}
@Override
- public boolean visit(TypeDeclaration typeDeclaration,
- CompilationUnitScope scope) {
+ public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
return process(typeDeclaration);
}
@Override
- public boolean visitValid(TypeDeclaration localTypeDeclaration,
- BlockScope scope) {
+ public boolean visitValid(TypeDeclaration localTypeDeclaration, BlockScope scope) {
assert (TypeDeclaration.kind(localTypeDeclaration.modifiers) != TypeDeclaration.INTERFACE_DECL);
return process(localTypeDeclaration);
}
@@ -423,10 +412,8 @@
CompilationResult compResult = typeDecl.compilationResult;
int[] indexes = compResult.lineSeparatorPositions;
String fileName = String.valueOf(compResult.fileName);
- int startLine = Util.getLineNumber(typeDecl.sourceStart, indexes, 0,
- indexes.length - 1);
- return program.createSourceInfo(typeDecl.sourceStart, typeDecl.bodyEnd,
- startLine, fileName);
+ int startLine = Util.getLineNumber(typeDecl.sourceStart, indexes, 0, indexes.length - 1);
+ return program.createSourceInfo(typeDecl.sourceStart, typeDecl.bodyEnd, startLine, fileName);
}
private boolean process(TypeDeclaration typeDeclaration) {
@@ -446,8 +433,7 @@
}
}
- private InternalCompilerException translateException(
- TypeDeclaration typeDecl, Throwable e) {
+ private InternalCompilerException translateException(TypeDeclaration typeDecl, Throwable e) {
if (e instanceof VirtualMachineError) {
// Always rethrow VM errors (an attempt to wrap may fail).
throw (VirtualMachineError) e;
@@ -458,12 +444,39 @@
} else {
ice = new InternalCompilerException("Error building type map", e);
}
- ice.addNode(typeDecl.getClass().getName(), typeDecl.toString(),
- makeSourceInfo(typeDecl));
+ ice.addNode(typeDecl.getClass().getName(), typeDecl.toString(), makeSourceInfo(typeDecl));
return ice;
}
}
+ private class ExternalTypeCreator implements ExternalTypeTask {
+
+ public void process(String klass, BinaryTypeBinding binding) {
+ if (program.getFromTypeMap(klass) == null) {
+ // NB(tobyr) There are a few cases where certain compiler intrinsic
+ // types are only needed if the program references them
+ // (e.g. boxed numeric types). If we don't have the binding for those
+ // types, we can safely ignore it.
+ createExternalType(klass, binding);
+ }
+ }
+ }
+
+ private class ExternalTypeResolver implements ExternalTypeTask {
+
+ public void process(String klass, BinaryTypeBinding binding) {
+ if (binding != null) {
+ JDeclaredType type = program.getFromTypeMap(klass);
+ resolve(type, binding);
+ }
+ }
+ }
+
+ private interface ExternalTypeTask {
+
+ void process(String klass, BinaryTypeBinding binding);
+ }
+
/**
* Resolves the scope of JS identifiers solely within the scope of a method.
*/
@@ -492,47 +505,11 @@
}
}
- private interface ExternalTypeTask {
-
- void process(String klass, BinaryTypeBinding binding);
- }
-
- private class ExternalTypeCreator implements ExternalTypeTask {
-
- public void process(String klass, BinaryTypeBinding binding) {
- if (program.getFromTypeMap(klass) == null) {
- // NB(tobyr) There are a few cases where certain compiler intrinsic
- // types are only needed if the program references them
- // (e.g. boxed numeric types). If we don't have the binding for those
- // types, we can safely ignore it.
- createExternalType(klass, binding);
- }
- }
- }
-
- private class ExternalTypeResolver implements ExternalTypeTask {
-
- public void process(String klass, BinaryTypeBinding binding) {
- if (binding != null) {
- JDeclaredType type = program.getFromTypeMap(klass);
- resolve(type, binding);
- }
- }
- }
-
// TODO: Remove this overload altogether at some point.
- public static TypeDeclaration[] exec(TypeMap typeMap,
- CompilationUnitDeclaration[] unitDecls, JsProgram jsProgram) {
- CompilationResults results = new CompilationResults(unitDecls,
- new HashMap<String, BinaryTypeBinding>(0));
- return exec(typeMap, results, jsProgram, TypeLinker.NULL_TYPE_LINKER);
- }
-
- public static TypeDeclaration[] exec(TypeMap typeMap,
- CompilationResults results, JsProgram jsProgram, TypeLinker linker) {
- BuildTypeMap btm = new BuildTypeMap(typeMap, jsProgram, linker,
- results.compiledUnits);
+ public static TypeDeclaration[] exec(TypeMap typeMap, CompilationResults results,
+ JsProgram jsProgram, TypeLinker linker) {
+ BuildTypeMap btm = new BuildTypeMap(typeMap, jsProgram, linker, results.compiledUnits);
Event buildTypeMapEvent = SpeedTracerLogger.start(CompilerEventType.BUILD_TYPE_MAP_FOR_AST);
btm.createPeersForUnits();
btm.resolveExternalTypes(results.binaryBindings);
@@ -541,6 +518,13 @@
return result;
}
+ public static TypeDeclaration[] exec(TypeMap typeMap, CompilationUnitDeclaration[] unitDecls,
+ JsProgram jsProgram) {
+ CompilationResults results =
+ new CompilationResults(unitDecls, new HashMap<String, BinaryTypeBinding>(0));
+ return exec(typeMap, results, jsProgram, TypeLinker.NULL_TYPE_LINKER);
+ }
+
static String dotify(char[][] name) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < name.length; ++i) {
@@ -568,8 +552,7 @@
this.unitDecls = unitDecls;
}
- private void addThrownExceptions(MethodBinding methodBinding,
- JMethod method) {
+ private void addThrownExceptions(MethodBinding methodBinding, JMethod method) {
for (ReferenceBinding thrownBinding : methodBinding.thrownExceptions) {
JClassType type = (JClassType) getType(thrownBinding.erasure());
method.addThrownException(type);
@@ -585,13 +568,12 @@
return type;
}
- private JField createField(SourceInfo info, FieldBinding binding,
- JDeclaredType enclosingType) {
+ private JField createField(SourceInfo info, FieldBinding binding, JDeclaredType enclosingType) {
JType type = getType(binding.type);
- boolean isCompileTimeConstant = binding.isStatic() && (binding.isFinal())
- && (binding.constant() != Constant.NotAConstant)
- && (binding.type.isBaseType());
+ boolean isCompileTimeConstant =
+ binding.isStatic() && (binding.isFinal()) && (binding.constant() != Constant.NotAConstant)
+ && (binding.type.isBaseType());
assert (type instanceof JPrimitiveType || !isCompileTimeConstant);
assert (!binding.isFinal() || !binding.isVolatile());
@@ -606,19 +588,21 @@
disposition = Disposition.NONE;
}
- JField field = program.createField(info, String.valueOf(binding.name),
- enclosingType, type, binding.isStatic(), disposition);
+ JField field =
+ program.createField(info, String.valueOf(binding.name), enclosingType, type, binding
+ .isStatic(), disposition);
typeMap.put(binding, field);
info.addCorrelation(info.getCorrelator().by(field));
return field;
}
- private JField createField(SyntheticArgumentBinding binding,
- JDeclaredType enclosingType, Disposition disposition) {
+ private JField createField(SyntheticArgumentBinding binding, JDeclaredType enclosingType,
+ Disposition disposition) {
JType type = getType(binding.type);
SourceInfo info = enclosingType.getSourceInfo().makeChild();
- JField field = program.createField(info, String.valueOf(binding.name),
- enclosingType, type, false, disposition);
+ JField field =
+ program.createField(info, String.valueOf(binding.name), enclosingType, type, false,
+ disposition);
info.addCorrelation(info.getCorrelator().by(field));
if (binding.matchingField != null) {
typeMap.put(binding.matchingField, field);
@@ -628,41 +612,40 @@
}
private void createMethod(MethodBinding binding, SourceInfo info) {
- JDeclaredType enclosingType = (JDeclaredType) getType(
- binding.declaringClass);
+ JDeclaredType enclosingType = (JDeclaredType) getType(binding.declaringClass);
JMethod newMethod = processMethodBinding(binding, enclosingType, info);
mapParameters(newMethod, binding, info);
}
- private JParameter createParameter(TypeBinding paramType,
- JMethod enclosingMethod, SourceInfo info, int argPosition) {
- JType type = getType(paramType);
- // TODO(tobyr) Get the actual param name if it's present in debug info
- // or otherwise.
- String syntheticParamName = "arg" + argPosition;
- JParameter param = JProgram.createParameter(info, syntheticParamName, type,
- true, false, enclosingMethod);
- // Don't need to put the parameter in the TypeMap as it won't be looked
- // up for binary types.
- return param;
- }
-
- private JParameter createParameter(LocalVariableBinding binding,
- JMethod enclosingMethod, SourceInfo info) {
+ private JParameter createParameter(LocalVariableBinding binding, JMethod enclosingMethod,
+ SourceInfo info) {
JType type = getType(binding.type);
- JParameter param = JProgram.createParameter(info,
- String.valueOf(binding.name), type, binding.isFinal(), false,
- enclosingMethod);
+ JParameter param =
+ JProgram.createParameter(info, String.valueOf(binding.name), type, binding.isFinal(),
+ false, enclosingMethod);
typeMap.put(binding, param);
return param;
}
- private JParameter createParameter(SyntheticArgumentBinding arg,
- String argName, JMethod enclosingMethod) {
+ private JParameter createParameter(SyntheticArgumentBinding arg, String argName,
+ JMethod enclosingMethod) {
JType type = getType(arg.type);
- JParameter param = JProgram.createParameter(
- enclosingMethod.getSourceInfo(), argName, type, true, false,
- enclosingMethod);
+ JParameter param =
+ JProgram.createParameter(enclosingMethod.getSourceInfo(), argName, type, true, false,
+ enclosingMethod);
+ return param;
+ }
+
+ private JParameter createParameter(TypeBinding paramType, JMethod enclosingMethod,
+ SourceInfo info, int argPosition) {
+ JType type = getType(paramType);
+ // TODO(tobyr) Get the actual param name if it's present in debug info
+ // or otherwise.
+ String syntheticParamName = "arg" + argPosition;
+ JParameter param =
+ JProgram.createParameter(info, syntheticParamName, type, true, false, enclosingMethod);
+ // Don't need to put the parameter in the TypeMap as it won't be looked
+ // up for binary types.
return param;
}
@@ -684,13 +667,11 @@
}
}
- private JDeclaredType createType(String name, SourceInfo info,
- ReferenceBinding binding) {
+ private JDeclaredType createType(String name, SourceInfo info, ReferenceBinding binding) {
JDeclaredType newType;
if (binding.isClass()) {
- newType = program.createClass(info, name, binding.isAbstract(),
- binding.isFinal());
+ newType = program.createClass(info, name, binding.isAbstract(), binding.isFinal());
} else if (binding.isInterface() || binding.isAnnotationType()) {
newType = program.createInterface(info, name);
} else if (binding.isEnum()) {
@@ -701,29 +682,30 @@
newType = program.createEnum(info, name, binding.isAbstract());
}
} else {
- throw new InternalCompilerException(
- "ReferenceBinding is not a class, interface, or enum.");
+ throw new InternalCompilerException("ReferenceBinding is not a class, interface, or enum.");
}
info.addCorrelation(info.getCorrelator().by(newType));
/**
- * We emulate static initializers and instance initializers as methods.
- * As in other cases, this gives us: simpler AST, easier to optimize,
- * more like output JavaScript. Clinit is always in slot 0, init (if it
- * exists) is always in slot 1.
+ * We emulate static initializers and instance initializers as methods. As
+ * in other cases, this gives us: simpler AST, easier to optimize, more like
+ * output JavaScript. Clinit is always in slot 0, init (if it exists) is
+ * always in slot 1.
*/
SourceInfo child = info.makeChild();
- JMethod clinit = program.createMethod(child, "$clinit", newType,
- program.getTypeVoid(), false, true, true, true, false);
+ JMethod clinit =
+ program.createMethod(child, "$clinit", newType, program.getTypeVoid(), false, true, true,
+ true, false);
clinit.freezeParamTypes();
clinit.setSynthetic();
child.addCorrelation(info.getCorrelator().by(clinit));
if (newType instanceof JClassType) {
child = info.makeChild();
- JMethod init = program.createMethod(child, "$init", newType,
- program.getTypeVoid(), false, false, true, true, false);
+ JMethod init =
+ program.createMethod(child, "$init", newType, program.getTypeVoid(), false, false, true,
+ true, false);
init.freezeParamTypes();
init.setSynthetic();
child.addCorrelation(info.getCorrelator().by(init));
@@ -733,8 +715,7 @@
return newType;
}
- private void forEachExternalType(Map<String, BinaryTypeBinding> bindings,
- ExternalTypeTask task) {
+ private void forEachExternalType(Map<String, BinaryTypeBinding> bindings, ExternalTypeTask task) {
for (Map.Entry<String, BinaryTypeBinding> entry : bindings.entrySet()) {
String klass = entry.getKey();
if (linker.isExternalType(klass)) {
@@ -758,8 +739,8 @@
}
if (!(binding instanceof ReferenceBinding)) {
- throw new InternalCompilerException(
- "Expected a ReferenceBinding but received a " + binding.getClass());
+ throw new InternalCompilerException("Expected a ReferenceBinding but received a "
+ + binding.getClass());
}
ReferenceBinding refBinding = (ReferenceBinding) binding;
@@ -774,8 +755,7 @@
return type;
}
- private void mapParameters(JMethod method, AbstractMethodDeclaration x,
- SourceInfo info) {
+ private void mapParameters(JMethod method, AbstractMethodDeclaration x, SourceInfo info) {
MethodBinding b = x.binding;
int paramCount = (b.parameters != null ? b.parameters.length : 0);
if (paramCount > 0) {
@@ -786,8 +766,7 @@
method.freezeParamTypes();
}
- private void mapParameters(JMethod method, MethodBinding binding,
- SourceInfo info) {
+ private void mapParameters(JMethod method, MethodBinding binding, SourceInfo info) {
int paramCount = binding.parameters != null ? binding.parameters.length : 0;
if (paramCount > 0) {
int counter = 0;
@@ -803,21 +782,19 @@
try {
// Create an override for getClass().
- if (type instanceof JClassType
- && type != program.getTypeJavaLangObject()) {
+ if (type instanceof JClassType && type != program.getTypeJavaLangObject()) {
SourceInfo info = type.getSourceInfo().makeChild();
- JMethod getClassMethod = program.createMethod(
- info, "getClass", type,
- program.getTypeJavaLangClass(), false, false, false, false, false);
+ JMethod getClassMethod =
+ program.createMethod(info, "getClass", type, program.getTypeJavaLangClass(), false,
+ false, false, false, false);
assert (type.getMethods().get(2) == getClassMethod);
getClassMethod.freezeParamTypes();
getClassMethod.setSynthetic();
info.addCorrelation(info.getCorrelator().by(getClassMethod));
}
- if (binding.isNestedType() && !binding.isStatic()
- && !(binding instanceof BinaryTypeBinding)) {
+ if (binding.isNestedType() && !binding.isStatic() && !(binding instanceof BinaryTypeBinding)) {
// TODO(tobyr) Do something here for binary types?
// add synthetic fields for outer this and locals
@@ -836,7 +813,8 @@
// See InnerClassTest.testOuterThisFromSuperCall().
boolean isReallyThisRef = false;
if (arg.actualOuterLocalVariable instanceof SyntheticArgumentBinding) {
- SyntheticArgumentBinding outer = (SyntheticArgumentBinding) arg.actualOuterLocalVariable;
+ SyntheticArgumentBinding outer =
+ (SyntheticArgumentBinding) arg.actualOuterLocalVariable;
if (outer.matchingField != null) {
JField field = (JField) typeMap.get(outer.matchingField);
if (field.isThisRef()) {
@@ -844,8 +822,7 @@
}
}
}
- createField(arg, type, isReallyThisRef ? Disposition.THIS_REF
- : Disposition.FINAL);
+ createField(arg, type, isReallyThisRef ? Disposition.THIS_REF : Disposition.FINAL);
}
}
}
@@ -853,8 +830,7 @@
ReferenceBinding superClassBinding = binding.superclass();
if (type instanceof JClassType && superClassBinding != null) {
// TODO: handle separately?
- assert (binding.superclass().isClass()
- || binding.superclass().isEnum());
+ assert (binding.superclass().isClass() || binding.superclass().isEnum());
JClassType superClass = (JClassType) getType(superClassBinding);
((JClassType) type).setSuperClass(superClass);
}
@@ -862,8 +838,7 @@
ReferenceBinding[] superInterfaces = binding.superInterfaces();
for (ReferenceBinding superInterfaceBinding : superInterfaces) {
assert (superInterfaceBinding.isInterface());
- JInterfaceType superInterface = (JInterfaceType) getType(
- superInterfaceBinding);
+ JInterfaceType superInterface = (JInterfaceType) getType(superInterfaceBinding);
type.addImplements(superInterface);
}
@@ -888,17 +863,17 @@
}
}
- private JConstructor processConstructor(MethodBinding b,
- ConstructorDeclaration decl, SourceInfo info) {
+ private JConstructor processConstructor(MethodBinding b, ConstructorDeclaration decl,
+ SourceInfo info) {
JClassType enclosingType = (JClassType) getType(b.declaringClass);
JConstructor newCtor = program.createConstructor(info, enclosingType);
// Enums have hidden arguments for name and value
if (enclosingType.isEnumOrSubclass() != null) {
- JProgram.createParameter(info, "enum$name",
- program.getTypeJavaLangString(), true, false, newCtor);
- JProgram.createParameter(info, "enum$ordinal",
- program.getTypePrimitiveInt(), true, false, newCtor);
+ JProgram.createParameter(info, "enum$name", program.getTypeJavaLangString(), true, false,
+ newCtor);
+ JProgram.createParameter(info, "enum$ordinal", program.getTypePrimitiveInt(), true, false,
+ newCtor);
}
ReferenceBinding declaringClass = b.declaringClass;
@@ -963,16 +938,15 @@
// Visit the synthetic values() and valueOf() methods.
for (MethodBinding methodBinding : binding.methods()) {
if (methodBinding instanceof SyntheticMethodBinding) {
- JMethod newMethod = processMethodBinding(methodBinding, type,
- type.getSourceInfo());
+ JMethod newMethod = processMethodBinding(methodBinding, type, type.getSourceInfo());
TypeBinding[] parameters = methodBinding.parameters;
if (parameters.length == 0) {
assert newMethod.getName().equals("values");
} else if (parameters.length == 1) {
assert newMethod.getName().equals("valueOf");
assert typeMap.get(parameters[0]) == program.getTypeJavaLangString();
- JProgram.createParameter(newMethod.getSourceInfo(), "name",
- program.getTypeJavaLangString(), true, false, newMethod);
+ JProgram.createParameter(newMethod.getSourceInfo(), "name", program
+ .getTypeJavaLangString(), true, false, newMethod);
} else {
assert false;
}
@@ -982,8 +956,8 @@
}
private void processExternalMethod(MethodBinding binding, JDeclaredType type) {
- if (binding.isPrivate() || (type.getName().startsWith("java.")
- && !binding.isPublic() && !binding.isProtected())) {
+ if (binding.isPrivate()
+ || (type.getName().startsWith("java.") && !binding.isPublic() && !binding.isProtected())) {
return;
}
if (binding.isConstructor()) {
@@ -993,12 +967,11 @@
}
}
- private JMethod processMethodBinding(MethodBinding b,
- JDeclaredType enclosingType, SourceInfo info) {
+ private JMethod processMethodBinding(MethodBinding b, JDeclaredType enclosingType, SourceInfo info) {
JType returnType = getType(b.returnType);
- JMethod newMethod = program.createMethod(info, String.valueOf(b.selector),
- enclosingType, returnType, b.isAbstract(), b.isStatic(), b.isFinal(),
- b.isPrivate(), b.isNative());
+ JMethod newMethod =
+ program.createMethod(info, String.valueOf(b.selector), enclosingType, returnType, b
+ .isAbstract(), b.isStatic(), b.isFinal(), b.isPrivate(), b.isNative());
addThrownExceptions(b, newMethod);
if (b.isSynthetic()) {
newMethod.setSynthetic();
@@ -1015,8 +988,9 @@
process(binding);
for (FieldBinding fieldBinding : binding.fields()) {
- if (fieldBinding.isPrivate() || (type.getName().startsWith("java.")
- && !fieldBinding.isPublic() && !fieldBinding.isProtected())) {
+ if (fieldBinding.isPrivate()
+ || (type.getName().startsWith("java.") && !fieldBinding.isPublic() && !fieldBinding
+ .isProtected())) {
continue;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/CastNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/CastNormalizer.java
index be297b4..7f8d3e1 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/CastNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/CastNormalizer.java
@@ -60,21 +60,21 @@
* where the 0 queryId means that anything can be stored into an Object[].
* </p>
* <p>
- * JavaScriptObject has a queryId of -1, which again is only used for array store
- * checking, to ensure that a non-JSO is not stored into a JavaScriptObject[].
+ * JavaScriptObject has a queryId of -1, which again is only used for array
+ * store checking, to ensure that a non-JSO is not stored into a
+ * JavaScriptObject[].
* </p>
*/
public class CastNormalizer {
private class AssignTypeCastabilityVisitor extends JVisitor {
Set<JReferenceType> alreadyRan = new HashSet<JReferenceType>();
- private IdentityHashMap<JReferenceType, JsonObject>
- castableTypeMaps = new IdentityHashMap<JReferenceType, JsonObject>();
- private final List<JArrayType> instantiatedArrayTypes =
- new ArrayList<JArrayType>();
+ private final IdentityHashMap<JReferenceType, JsonObject> castableTypeMaps =
+ new IdentityHashMap<JReferenceType, JsonObject>();
+ private final List<JArrayType> instantiatedArrayTypes = new ArrayList<JArrayType>();
private int nextQueryId = 0;
- private Map<JReferenceType, Set<JReferenceType>> queriedTypes =
- new IdentityHashMap<JReferenceType, Set<JReferenceType>>();
+ private final Map<JReferenceType, Set<JReferenceType>> queriedTypes =
+ new IdentityHashMap<JReferenceType, Set<JReferenceType>>();
{
JTypeOracle typeOracle = program.typeOracle;
@@ -85,14 +85,12 @@
}
// Reserve query id 0 for java.lang.Object (for array stores on JSOs).
- recordCastInternal(program.getTypeJavaLangObject(),
- program.getTypeJavaLangObject());
+ recordCastInternal(program.getTypeJavaLangObject(), program.getTypeJavaLangObject());
// Reserve query id 1 for java.lang.String to facilitate the mashup case.
// Also, facilitates detecting an object as a Java String (see Cast.java)
// Multiple GWT modules need to modify String's prototype the same way.
- recordCastInternal(program.getTypeJavaLangString(),
- program.getTypeJavaLangObject());
+ recordCastInternal(program.getTypeJavaLangString(), program.getTypeJavaLangObject());
}
public void computeTypeCastabilityMaps() {
@@ -191,8 +189,7 @@
recordCast(x.getTestType(), x.getExpr());
}
- private boolean canTriviallyCastJsoSemantics(JReferenceType type,
- JReferenceType qType) {
+ private boolean canTriviallyCastJsoSemantics(JReferenceType type, JReferenceType qType) {
type = type.getUnderlyingType();
qType = qType.getUnderlyingType();
@@ -200,15 +197,14 @@
JArrayType aType = (JArrayType) type;
JArrayType aqType = (JArrayType) qType;
return program.typeOracle.canTriviallyCast(type, qType)
- || (program.isJavaScriptObject(aType.getLeafType())
- && program.isJavaScriptObject(aqType.getLeafType()));
+ || (program.isJavaScriptObject(aType.getLeafType()) && program
+ .isJavaScriptObject(aqType.getLeafType()));
}
return program.typeOracle.canTriviallyCast(type, qType)
- || (program.isJavaScriptObject(type)
- && program.isJavaScriptObject(qType));
+ || (program.isJavaScriptObject(type) && program.isJavaScriptObject(qType));
}
-
+
/**
* Create the data for JSON table to capture the mapping from a class to its
* query types.
@@ -226,8 +222,7 @@
computeSourceType(((JClassType) type).getSuperClass());
}
- if (!program.typeOracle.isInstantiatedType(type)
- || program.isJavaScriptObject(type)) {
+ if (!program.typeOracle.isInstantiatedType(type) || program.isJavaScriptObject(type)) {
return;
}
@@ -247,8 +242,7 @@
for (JReferenceType argType : querySet) {
- if (canTriviallyCastJsoSemantics(type, argType) ||
- program.isJavaScriptObject(qType)) {
+ if (canTriviallyCastJsoSemantics(type, argType) || program.isJavaScriptObject(qType)) {
if (yesSet == null) {
yesSet = new HashSet<JReferenceType>();
}
@@ -269,15 +263,13 @@
// Create a sparse lookup object.
SourceInfo sourceInfo = program.createSourceInfoSynthetic(AssignTypeCastabilityVisitor.class);
- JsonObject jsonObject = new JsonObject(sourceInfo,
- program.getJavaScriptObject());
+ JsonObject jsonObject = new JsonObject(sourceInfo, program.getJavaScriptObject());
// Start at 1; 0 is Object and always true.
for (int i = 1; i < nextQueryId; ++i) {
if (yesArray[i] != null) {
JIntLiteral labelExpr = program.getLiteralInt(i);
JIntLiteral valueExpr = program.getLiteralInt(1);
- jsonObject.propInits.add(new JsonPropInit(sourceInfo, labelExpr,
- valueExpr));
+ jsonObject.propInits.add(new JsonPropInit(sourceInfo, labelExpr, valueExpr));
}
}
@@ -285,14 +277,13 @@
* Don't add an entry for empty answer sets, except for Object and String
* which require entries.
*/
- if (jsonObject.propInits.isEmpty()
- && type != program.getTypeJavaLangObject()
+ if (jsonObject.propInits.isEmpty() && type != program.getTypeJavaLangObject()
&& type != program.getTypeJavaLangString()) {
return;
}
// add an entry for me
- castableTypeMaps.put(type,jsonObject);
+ castableTypeMaps.put(type, jsonObject);
}
private void recordCast(JType targetType, JExpression rhs) {
@@ -301,8 +292,7 @@
// unconditional cast b/c it would've been a semantic error earlier
JReferenceType rhsType = ((JReferenceType) rhs.getType()).getUnderlyingType();
// don't record a type for trivial casts that won't generate code
- if (program.typeOracle.canTriviallyCast(rhsType,
- (JReferenceType) targetType)) {
+ if (program.typeOracle.canTriviallyCast(rhsType, (JReferenceType) targetType)) {
return;
}
@@ -315,8 +305,7 @@
}
}
- private void recordCastInternal(JReferenceType toType,
- JReferenceType rhsType) {
+ private void recordCastInternal(JReferenceType toType, JReferenceType rhsType) {
toType = toType.getUnderlyingType();
rhsType = rhsType.getUnderlyingType();
Set<JReferenceType> querySet = queriedTypes.get(toType);
@@ -342,17 +331,17 @@
JExpression newLhs = convertString(x.getLhs());
JExpression newRhs = convertString(x.getRhs());
if (newLhs != x.getLhs() || newRhs != x.getRhs()) {
- JBinaryOperation newExpr = new JBinaryOperation(x.getSourceInfo(),
- program.getTypeJavaLangString(), JBinaryOperator.CONCAT, newLhs,
- newRhs);
+ JBinaryOperation newExpr =
+ new JBinaryOperation(x.getSourceInfo(), program.getTypeJavaLangString(),
+ JBinaryOperator.CONCAT, newLhs, newRhs);
ctx.replaceMe(newExpr);
}
} else if (x.getOp() == JBinaryOperator.ASG_CONCAT) {
JExpression newRhs = convertString(x.getRhs());
if (newRhs != x.getRhs()) {
- JBinaryOperation newExpr = new JBinaryOperation(x.getSourceInfo(),
- program.getTypeJavaLangString(), JBinaryOperator.ASG_CONCAT,
- x.getLhs(), newRhs);
+ JBinaryOperation newExpr =
+ new JBinaryOperation(x.getSourceInfo(), program.getTypeJavaLangString(),
+ JBinaryOperator.ASG_CONCAT, x.getLhs(), newRhs);
ctx.replaceMe(newExpr);
}
}
@@ -363,19 +352,20 @@
if (expr.getType() == charType) {
if (expr instanceof JCharLiteral) {
JCharLiteral charLit = (JCharLiteral) expr;
- return program.getLiteralString(expr.getSourceInfo(),
- new char[] {charLit.getValue()});
+ return program.getLiteralString(expr.getSourceInfo(), new char[]{charLit.getValue()});
} else {
// Replace with Cast.charToString(c)
- JMethodCall call = new JMethodCall(expr.getSourceInfo(), null,
- program.getIndexedMethod("Cast.charToString"));
+ JMethodCall call =
+ new JMethodCall(expr.getSourceInfo(), null, program
+ .getIndexedMethod("Cast.charToString"));
call.addArg(expr);
return call;
}
} else if (expr.getType() == program.getTypePrimitiveLong()) {
// Replace with LongLib.toString(l)
- JMethodCall call = new JMethodCall(expr.getSourceInfo(), null,
- program.getIndexedMethod("LongLib.toString"));
+ JMethodCall call =
+ new JMethodCall(expr.getSourceInfo(), null, program
+ .getIndexedMethod("LongLib.toString"));
call.addArg(expr);
return call;
}
@@ -391,8 +381,7 @@
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
JType type = x.getType();
- if (x.getOp() == JBinaryOperator.DIV
- && type != program.getTypePrimitiveFloat()
+ if (x.getOp() == JBinaryOperator.DIV && type != program.getTypePrimitiveFloat()
&& type != program.getTypePrimitiveDouble()) {
/*
* If the numerator was already in range, we can assume the output is
@@ -401,8 +390,7 @@
*/
String methodName = "Cast.narrow_" + type.getName();
JMethod castMethod = program.getIndexedMethod(methodName);
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null, castMethod,
- type);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, castMethod, type);
x.setType(program.getTypePrimitiveDouble());
call.addArg(x);
ctx.replaceMe(call);
@@ -437,8 +425,7 @@
/*
* Override the type of the magic method with the null type.
*/
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method,
- program.getTypeNull());
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method, program.getTypeNull());
call.addArg(expr);
replaceExpr = call;
} else if (toType instanceof JReferenceType) {
@@ -446,15 +433,14 @@
JReferenceType refType = ((JReferenceType) toType).getUnderlyingType();
JReferenceType argType = (JReferenceType) expr.getType();
if (program.typeOracle.canTriviallyCast(argType, refType)
- || (program.typeOracle.isEffectivelyJavaScriptObject(argType)
- && program.typeOracle.isEffectivelyJavaScriptObject(refType))) {
+ || (program.typeOracle.isEffectivelyJavaScriptObject(argType) && program.typeOracle
+ .isEffectivelyJavaScriptObject(refType))) {
// just remove the cast
replaceExpr = curExpr;
} else {
JMethod method;
- boolean isJsoCast =
- program.typeOracle.isEffectivelyJavaScriptObject(refType);
+ boolean isJsoCast = program.typeOracle.isEffectivelyJavaScriptObject(refType);
if (isJsoCast) {
// A cast to a concrete JSO subtype
method = program.getIndexedMethod("Cast.dynamicCastJso");
@@ -466,8 +452,7 @@
method = program.getIndexedMethod("Cast.dynamicCast");
}
// override the type of the called method with the target cast type
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method,
- toType);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method, toType);
call.addArg(curExpr);
if (!isJsoCast) {
JIntLiteral qId = program.getLiteralInt(queryIds.get(refType));
@@ -500,8 +485,7 @@
* do the narrowing conversion.
*/
JMethod castMethod = program.getIndexedMethod("LongLib.toInt");
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null,
- castMethod);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, castMethod);
call.addArg(expr);
expr = call;
fromType = tInt;
@@ -514,8 +498,7 @@
if (toType == tLong && fromType != tLong) {
// Longs get special treatment.
- if (tByte == fromType || tShort == fromType || tChar == fromType
- || tInt == fromType) {
+ if (tByte == fromType || tShort == fromType || tChar == fromType || tInt == fromType) {
methodName = "LongLib.fromInt";
} else if (tFloat == fromType || tDouble == fromType) {
methodName = "LongLib.fromDouble";
@@ -537,16 +520,14 @@
methodName = "Cast.narrow_" + toType.getName();
}
} else if (tFloat == fromType || tDouble == fromType) {
- if (tByte == toType || tShort == toType || tChar == toType
- || tInt == toType) {
+ if (tByte == toType || tShort == toType || tChar == toType || tInt == toType) {
methodName = "Cast.round_" + toType.getName();
}
}
if (methodName != null) {
JMethod castMethod = program.getIndexedMethod(methodName);
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null,
- castMethod, toType);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, castMethod, toType);
call.addArg(expr);
replaceExpr = call;
} else {
@@ -564,14 +545,14 @@
// Only tests on run-time types are supported
assert (toType == toType.getUnderlyingType());
if (program.typeOracle.canTriviallyCast(argType, toType)
- // don't depend on type-tightener having run
- || (program.typeOracle.isEffectivelyJavaScriptObject(argType)
- && program.typeOracle.isEffectivelyJavaScriptObject(toType))) {
+ // don't depend on type-tightener having run
+ || (program.typeOracle.isEffectivelyJavaScriptObject(argType) && program.typeOracle
+ .isEffectivelyJavaScriptObject(toType))) {
// trivially true if non-null; replace with a null test
JNullLiteral nullLit = program.getLiteralNull();
- JBinaryOperation eq = new JBinaryOperation(x.getSourceInfo(),
- program.getTypePrimitiveBoolean(), JBinaryOperator.NEQ,
- x.getExpr(), nullLit);
+ JBinaryOperation eq =
+ new JBinaryOperation(x.getSourceInfo(), program.getTypePrimitiveBoolean(),
+ JBinaryOperator.NEQ, x.getExpr(), nullLit);
ctx.replaceMe(eq);
} else {
JMethod method;
@@ -603,7 +584,8 @@
private final JProgram program;
- private Map<JReferenceType, Integer> queryIds = new IdentityHashMap<JReferenceType, Integer>();
+ private final Map<JReferenceType, Integer> queryIds =
+ new IdentityHashMap<JReferenceType, Integer>();
private CastNormalizer(JProgram program, boolean disableCastChecking) {
this.program = program;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/CatchBlockNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/CatchBlockNormalizer.java
index 8aa8ec0..c055674 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/CatchBlockNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/CatchBlockNormalizer.java
@@ -71,8 +71,8 @@
JMethod caughtMethod = program.getIndexedMethod("Exceptions.caught");
JMethodCall call = new JMethodCall(catchInfo, null, caughtMethod);
call.addArg(new JLocalRef(catchInfo, exVar));
- newCatchBlock.addStmt(JProgram.createAssignmentStmt(catchInfo,
- new JLocalRef(catchInfo, exVar), call));
+ newCatchBlock.addStmt(JProgram.createAssignmentStmt(catchInfo, new JLocalRef(catchInfo,
+ exVar), call));
}
/*
@@ -82,18 +82,16 @@
* Go backwards so we can nest the else statements in the correct order!
*/
// rethrow the current exception if no one caught it
- JStatement cur = new JThrowStatement(catchInfo, new JLocalRef(catchInfo,
- exVar));
+ JStatement cur = new JThrowStatement(catchInfo, new JLocalRef(catchInfo, exVar));
for (int i = x.getCatchBlocks().size() - 1; i >= 0; --i) {
JBlock block = x.getCatchBlocks().get(i);
JLocalRef arg = x.getCatchArgs().get(i);
catchInfo = block.getSourceInfo();
JReferenceType argType = (JReferenceType) arg.getType();
// if ($e instanceof ArgType) { var userVar = $e; <user code> }
- JExpression ifTest = new JInstanceOf(catchInfo, argType, new JLocalRef(
- catchInfo, exVar));
- JDeclarationStatement declaration = new JDeclarationStatement(
- catchInfo, arg, new JLocalRef(catchInfo, exVar));
+ JExpression ifTest = new JInstanceOf(catchInfo, argType, new JLocalRef(catchInfo, exVar));
+ JDeclarationStatement declaration =
+ new JDeclarationStatement(catchInfo, arg, new JLocalRef(catchInfo, exVar));
block.addStmt(0, declaration);
// nest the previous as an else for me
cur = new JIfStatement(catchInfo, ifTest, block, cur);
@@ -153,8 +151,9 @@
private void pushTempLocal(SourceInfo sourceInfo) {
if (localIndex == tempLocals.size()) {
- JLocal newTemp = JProgram.createLocal(sourceInfo, "$e" + localIndex,
- program.getTypeJavaLangObject(), false, currentMethodBody);
+ JLocal newTemp =
+ JProgram.createLocal(sourceInfo, "$e" + localIndex, program.getTypeJavaLangObject(),
+ false, currentMethodBody);
tempLocals.add(newTemp);
}
++localIndex;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/CloneExpressionVisitor.java b/dev/core/src/com/google/gwt/dev/jjs/impl/CloneExpressionVisitor.java
index 30eb6ee..510b28b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/CloneExpressionVisitor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/CloneExpressionVisitor.java
@@ -74,8 +74,7 @@
this.accept(expr);
if (expression == null) {
- throw new InternalCompilerException(expr, "Unable to clone expression",
- null);
+ throw new InternalCompilerException(expr, "Unable to clone expression", null);
}
Class<T> originalClass = (Class<T>) expr.getClass();
@@ -101,22 +100,23 @@
@Override
public boolean visit(JArrayLength x, Context ctx) {
- expression = new JArrayLength(x.getSourceInfo(), cloneExpression(
- x.getInstance()));
+ expression = new JArrayLength(x.getSourceInfo(), cloneExpression(x.getInstance()));
return false;
}
@Override
public boolean visit(JArrayRef x, Context ctx) {
- expression = new JArrayRef(x.getSourceInfo(),
- cloneExpression(x.getInstance()), cloneExpression(x.getIndexExpr()));
+ expression =
+ new JArrayRef(x.getSourceInfo(), cloneExpression(x.getInstance()), cloneExpression(x
+ .getIndexExpr()));
return false;
}
@Override
public boolean visit(JBinaryOperation x, Context ctx) {
- expression = new JBinaryOperation(x.getSourceInfo(), x.getType(),
- x.getOp(), cloneExpression(x.getLhs()), cloneExpression(x.getRhs()));
+ expression =
+ new JBinaryOperation(x.getSourceInfo(), x.getType(), x.getOp(),
+ cloneExpression(x.getLhs()), cloneExpression(x.getRhs()));
return false;
}
@@ -128,8 +128,8 @@
@Override
public boolean visit(JCastOperation x, Context ctx) {
- expression = new JCastOperation(x.getSourceInfo(), x.getCastType(),
- cloneExpression(x.getExpr()));
+ expression =
+ new JCastOperation(x.getSourceInfo(), x.getCastType(), cloneExpression(x.getExpr()));
return false;
}
@@ -147,9 +147,9 @@
@Override
public boolean visit(JConditional x, Context ctx) {
- expression = new JConditional(x.getSourceInfo(), x.getType(),
- cloneExpression(x.getIfTest()), cloneExpression(x.getThenExpr()),
- cloneExpression(x.getElseExpr()));
+ expression =
+ new JConditional(x.getSourceInfo(), x.getType(), cloneExpression(x.getIfTest()),
+ cloneExpression(x.getThenExpr()), cloneExpression(x.getElseExpr()));
return false;
}
@@ -161,8 +161,9 @@
@Override
public boolean visit(JFieldRef x, Context ctx) {
- expression = new JFieldRef(x.getSourceInfo(),
- cloneExpression(x.getInstance()), x.getField(), x.getEnclosingType());
+ expression =
+ new JFieldRef(x.getSourceInfo(), cloneExpression(x.getInstance()), x.getField(), x
+ .getEnclosingType());
return false;
}
@@ -181,9 +182,9 @@
}
// Use the clone constructor.
- JGwtCreate gwtCreate = new JGwtCreate(x.getSourceInfo(), x.getSourceType(),
- x.getResultTypes(), x.getType(),
- cloneExpressions(x.getInstantiationExpressions()));
+ JGwtCreate gwtCreate =
+ new JGwtCreate(x.getSourceInfo(), x.getSourceType(), x.getResultTypes(), x.getType(),
+ cloneExpressions(x.getInstantiationExpressions()));
expression = gwtCreate;
return false;
@@ -191,8 +192,7 @@
@Override
public boolean visit(JInstanceOf x, Context ctx) {
- expression = new JInstanceOf(x.getSourceInfo(), x.getTestType(),
- cloneExpression(x.getExpr()));
+ expression = new JInstanceOf(x.getSourceInfo(), x.getTestType(), cloneExpression(x.getExpr()));
return false;
}
@@ -216,8 +216,7 @@
@Override
public boolean visit(JMethodCall x, Context ctx) {
- JMethodCall newMethodCall = new JMethodCall(x,
- cloneExpression(x.getInstance()));
+ JMethodCall newMethodCall = new JMethodCall(x, cloneExpression(x.getInstance()));
newMethodCall.addArgs(cloneExpressions(x.getArgs()));
expression = newMethodCall;
return false;
@@ -239,9 +238,9 @@
@Override
public boolean visit(JNewArray x, Context ctx) {
- expression = new JNewArray(x.getSourceInfo(), x.getType(),
- cloneExpressions(x.dims), cloneExpressions(x.initializers),
- x.getClassLiterals());
+ expression =
+ new JNewArray(x.getSourceInfo(), x.getType(), cloneExpressions(x.dims),
+ cloneExpressions(x.initializers), x.getClassLiterals());
return false;
}
@@ -267,15 +266,13 @@
@Override
public boolean visit(JPostfixOperation x, Context ctx) {
- expression = new JPostfixOperation(x.getSourceInfo(), x.getOp(),
- cloneExpression(x.getArg()));
+ expression = new JPostfixOperation(x.getSourceInfo(), x.getOp(), cloneExpression(x.getArg()));
return false;
}
@Override
public boolean visit(JPrefixOperation x, Context ctx) {
- expression = new JPrefixOperation(x.getSourceInfo(), x.getOp(),
- cloneExpression(x.getArg()));
+ expression = new JPrefixOperation(x.getSourceInfo(), x.getOp(), cloneExpression(x.getArg()));
return false;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/CodeSplitter.java b/dev/core/src/com/google/gwt/dev/jjs/impl/CodeSplitter.java
index 54871d6..a44cb47 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/CodeSplitter.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/CodeSplitter.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -74,7 +74,7 @@
* GWT.runAsync()}. The remaining code should be downloadable via
* {@link com.google.gwt.core.client.impl.AsyncFragmentLoader#inject(int)}.
* </p>
- *
+ *
* <p>
* The precise way the program is fragmented is an implementation detail that is
* subject to change. Whenever the fragment strategy changes,
@@ -85,7 +85,7 @@
* sequence are reached before any call not in the sequence. Further, any call
* in the sequence is reached before any call later in the sequence.
* </p>
- *
+ *
* <p>
* The fragment for a split point contains different things depending on whether
* it is in the initial load sequence or not. If it's in the initial load
@@ -173,13 +173,11 @@
/**
* A liveness predicate that is based on an exclusivity map.
*/
- private static class ExclusivityMapLivenessPredicate implements
- LivenessPredicate {
+ private static class ExclusivityMapLivenessPredicate implements LivenessPredicate {
private final int fragment;
private final ExclusivityMap fragmentMap;
- public ExclusivityMapLivenessPredicate(ExclusivityMap fragmentMap,
- int fragment) {
+ public ExclusivityMapLivenessPredicate(ExclusivityMap fragmentMap, int fragment) {
this.fragmentMap = fragmentMap;
this.fragment = fragment;
}
@@ -218,23 +216,23 @@
/**
* A {@link MultipleDependencyGraphRecorder} that does nothing.
*/
- public static final MultipleDependencyGraphRecorder NULL_RECORDER = new MultipleDependencyGraphRecorder() {
- public void close() {
- }
+ public static final MultipleDependencyGraphRecorder NULL_RECORDER =
+ new MultipleDependencyGraphRecorder() {
+ public void close() {
+ }
- public void endDependencyGraph() {
- }
+ public void endDependencyGraph() {
+ }
- public void methodIsLiveBecause(JMethod liveMethod,
- ArrayList<JMethod> dependencyChain) {
- }
+ public void methodIsLiveBecause(JMethod liveMethod, ArrayList<JMethod> dependencyChain) {
+ }
- public void open() {
- }
+ public void open() {
+ }
- public void startDependencyGraph(String name, String extnds) {
- }
- };
+ public void startDependencyGraph(String name, String extnds) {
+ }
+ };
private static final String PROP_INITIAL_SEQUENCE = "compiler.splitpoint.initial.sequence";
@@ -247,9 +245,8 @@
return computeInitiallyLive(jprogram, NULL_RECORDER);
}
- public static void exec(TreeLogger logger, JProgram jprogram,
- JsProgram jsprogram, JavaToJavaScriptMap map,
- MultipleDependencyGraphRecorder dependencyRecorder) {
+ public static void exec(TreeLogger logger, JProgram jprogram, JsProgram jsprogram,
+ JavaToJavaScriptMap map, MultipleDependencyGraphRecorder dependencyRecorder) {
if (jprogram.entryMethods.size() == 1) {
// Don't do anything if there is no call to runAsync
return;
@@ -265,30 +262,31 @@
* Find a split point as designated in the {@link #PROP_INITIAL_SEQUENCE}
* configuration property.
*/
- public static int findSplitPoint(String refString, JProgram program,
- TreeLogger branch) throws UnableToCompleteException {
+ public static int findSplitPoint(String refString, JProgram program, TreeLogger branch)
+ throws UnableToCompleteException {
Event codeSplitterEvent =
SpeedTracerLogger.start(CompilerEventType.CODE_SPLITTER, "phase", "findSplitPoint");
- Map<JMethod, List<Integer>> methodToSplitPoint = reverseByEnclosingMethod(program.getRunAsyncReplacements());
+ Map<JMethod, List<Integer>> methodToSplitPoint =
+ reverseByEnclosingMethod(program.getRunAsyncReplacements());
Map<String, List<Integer>> nameToSplitPoint = reverseByName(program.getRunAsyncReplacements());
if (refString.startsWith("@")) {
JsniRef jsniRef = JsniRef.parse(refString);
if (jsniRef == null) {
- branch.log(TreeLogger.ERROR, "Badly formatted JSNI reference in "
- + PROP_INITIAL_SEQUENCE + ": " + refString);
+ branch.log(TreeLogger.ERROR, "Badly formatted JSNI reference in " + PROP_INITIAL_SEQUENCE
+ + ": " + refString);
throw new UnableToCompleteException();
}
final String lookupErrorHolder[] = new String[1];
- JNode referent = JsniRefLookup.findJsniRefTarget(jsniRef, program,
- new JsniRefLookup.ErrorReporter() {
+ JNode referent =
+ JsniRefLookup.findJsniRefTarget(jsniRef, program, new JsniRefLookup.ErrorReporter() {
public void reportError(String error) {
lookupErrorHolder[0] = error;
}
});
if (referent == null) {
- TreeLogger resolveLogger = branch.branch(TreeLogger.ERROR,
- "Could not resolve JSNI reference: " + jsniRef);
+ TreeLogger resolveLogger =
+ branch.branch(TreeLogger.ERROR, "Could not resolve JSNI reference: " + jsniRef);
resolveLogger.log(TreeLogger.ERROR, lookupErrorHolder[0]);
throw new UnableToCompleteException();
}
@@ -301,14 +299,12 @@
JMethod method = (JMethod) referent;
List<Integer> splitPoints = methodToSplitPoint.get(method);
if (splitPoints == null) {
- branch.log(TreeLogger.ERROR,
- "Method does not enclose a runAsync call: " + jsniRef);
+ branch.log(TreeLogger.ERROR, "Method does not enclose a runAsync call: " + jsniRef);
throw new UnableToCompleteException();
}
if (splitPoints.size() > 1) {
- branch.log(TreeLogger.ERROR,
- "Method includes multiple runAsync calls, "
- + "so it's ambiguous which one is meant: " + jsniRef);
+ branch.log(TreeLogger.ERROR, "Method includes multiple runAsync calls, "
+ + "so it's ambiguous which one is meant: " + jsniRef);
throw new UnableToCompleteException();
}
@@ -318,13 +314,12 @@
// Assume it's a raw class name
List<Integer> splitPoints = nameToSplitPoint.get(refString);
if (splitPoints == null || splitPoints.size() == 0) {
- branch.log(TreeLogger.ERROR, "No runAsync call is labelled with class "
- + refString);
+ branch.log(TreeLogger.ERROR, "No runAsync call is labelled with class " + refString);
throw new UnableToCompleteException();
}
if (splitPoints.size() > 1) {
- branch.log(TreeLogger.ERROR,
- "More than one runAsync call is labelled with class " + refString);
+ branch.log(TreeLogger.ERROR, "More than one runAsync call is labelled with class "
+ + refString);
throw new UnableToCompleteException();
}
int result = splitPoints.get(0);
@@ -332,11 +327,7 @@
return result;
}
- /**
- * @param numSplitPoints the total number of split points
- */
- public static int getExclusiveFragmentNumber(int splitPoint,
- int numSplitPoints) {
+ public static int getExclusiveFragmentNumber(int splitPoint) {
return splitPoint;
}
@@ -363,23 +354,24 @@
* other split points. As a side effect, modifies
* {@link com.google.gwt.core.client.impl.AsyncFragmentLoader#initialLoadSequence}
* in the program being compiled.
- *
+ *
* @throws UnableToCompleteException If the module specifies a bad load order
*/
- public static void pickInitialLoadSequence(TreeLogger logger,
- JProgram program, Properties properties) throws UnableToCompleteException {
- Event codeSplitterEvent = SpeedTracerLogger.start(
- CompilerEventType.CODE_SPLITTER, "phase", "pickInitialLoadSequence");
- TreeLogger branch = logger.branch(TreeLogger.TRACE,
- "Looking up initial load sequence for split points");
+ public static void pickInitialLoadSequence(TreeLogger logger, JProgram program,
+ Properties properties) throws UnableToCompleteException {
+ Event codeSplitterEvent =
+ SpeedTracerLogger
+ .start(CompilerEventType.CODE_SPLITTER, "phase", "pickInitialLoadSequence");
+ TreeLogger branch =
+ logger.branch(TreeLogger.TRACE, "Looking up initial load sequence for split points");
LinkedHashSet<Integer> initialLoadSequence = new LinkedHashSet<Integer>();
ConfigurationProperty prop;
{
Property p = properties.find(PROP_INITIAL_SEQUENCE);
if (p == null) {
- throw new InternalCompilerException(
- "Could not find configuration property " + PROP_INITIAL_SEQUENCE);
+ throw new InternalCompilerException("Could not find configuration property "
+ + PROP_INITIAL_SEQUENCE);
}
if (!(p instanceof ConfigurationProperty)) {
throw new InternalCompilerException(PROP_INITIAL_SEQUENCE
@@ -391,16 +383,14 @@
for (String refString : prop.getValues()) {
int splitPoint = findSplitPoint(refString, program, branch);
if (initialLoadSequence.contains(splitPoint)) {
- branch.log(TreeLogger.ERROR, "Split point specified more than once: "
- + refString);
+ branch.log(TreeLogger.ERROR, "Split point specified more than once: " + refString);
}
initialLoadSequence.add(splitPoint);
}
logInitialLoadSequence(logger, initialLoadSequence);
installInitialLoadSequenceField(program, initialLoadSequence);
- program.setSplitPointInitialSequence(new ArrayList<Integer>(
- initialLoadSequence));
+ program.setSplitPointInitialSequence(new ArrayList<Integer>(initialLoadSequence));
codeSplitterEvent.end();
}
@@ -411,7 +401,7 @@
* scripts that are downloaded for that sequence. The maximum total script
* size is the maximum such size for all possible sequences of split points.
* </p>
- *
+ *
* @param jsLengths The lengths of the fragments for the compilation of one
* permutation
*/
@@ -429,7 +419,7 @@
// Add up the initial and exclusive fragments
maxTotalSize = jsLengths[0];
for (int sp = 1; sp <= numSplitPoints; sp++) {
- int excl = getExclusiveFragmentNumber(sp, numSplitPoints);
+ int excl = getExclusiveFragmentNumber(sp);
maxTotalSize += jsLengths[excl];
}
@@ -439,8 +429,7 @@
return maxTotalSize;
}
- private static Map<JField, JClassLiteral> buildFieldToClassLiteralMap(
- JProgram jprogram) {
+ private static Map<JField, JClassLiteral> buildFieldToClassLiteralMap(JProgram jprogram) {
final Map<JField, JClassLiteral> map = new HashMap<JField, JClassLiteral>();
class BuildFieldToLiteralVisitor extends JVisitor {
@Override
@@ -487,8 +476,7 @@
}
private static String fullNameString(JMethod method) {
- return method.getEnclosingType().getName() + "."
- + JProgram.getJsniSig(method);
+ return method.getEnclosingType().getName() + "." + JProgram.getJsniSig(method);
}
private static <T> int getOrZero(Map<T, Integer> map, T key) {
@@ -499,18 +487,18 @@
/**
* Installs the initial load sequence into the
* AsyncFragmentLoader.BROWSER_LOADER. The initializer looks like this:
- *
+ *
* <pre>
public static AsyncFragmentLoader BROWSER_LOADER = new AsyncFragmentLoader(1,
new int[] {}, new StandardLoadingStrategy(), new StandardLogger());
</pre>
- *
+ *
* The second argument (<code>new int[]</code>) gets replaced by an array
* corresponding to <code>initialLoadSequence</code>.
*/
private static void installInitialLoadSequenceField(JProgram program,
LinkedHashSet<Integer> initialLoadSequence) {
- // Arg 1 is initialized in the source as "new int[]{}".
+ // Arg 1 is initialized in the source as "new int[]{}".
JMethodCall constructorCall = ReplaceRunAsyncs.getBrowserLoaderConstructor(program);
JNewArray newArray = (JNewArray) constructorCall.getArgs().get(1);
assert newArray.getArrayType().getElementType() == JPrimitiveType.INT;
@@ -588,8 +576,7 @@
* first time class Array is touched, and any methods added later won't be
* part of the copy.
*/
- private static void traverseClassArray(JProgram jprogram,
- ControlFlowAnalyzer cfa) {
+ private static void traverseClassArray(JProgram jprogram, ControlFlowAnalyzer cfa) {
JDeclaredType typeArray = jprogram.getFromTypeMap("com.google.gwt.lang.Array");
if (typeArray == null) {
// It was pruned; nothing to do
@@ -608,8 +595,7 @@
* Traverse all code in the program that is reachable via split point
* <code>splitPoint</code>.
*/
- private static void traverseEntry(JProgram jprogram, ControlFlowAnalyzer cfa,
- int splitPoint) {
+ private static void traverseEntry(JProgram jprogram, ControlFlowAnalyzer cfa, int splitPoint) {
for (JMethod entryMethod : jprogram.entryMethods.get(splitPoint)) {
cfa.traverseFrom(entryMethod);
}
@@ -622,8 +608,8 @@
return union;
}
- private static <T> void updateMap(int entry, Map<T, Integer> map,
- Set<?> liveWithoutEntry, Iterable<T> all) {
+ private static <T> void updateMap(int entry, Map<T, Integer> map, Set<?> liveWithoutEntry,
+ Iterable<T> all) {
for (T each : all) {
if (!liveWithoutEntry.contains(each)) {
/*
@@ -647,8 +633,8 @@
* Code that is initially live when the program first downloads.
*/
private final ControlFlowAnalyzer initiallyLive;
- private JProgram jprogram;
- private JsProgram jsprogram;
+ private final JProgram jprogram;
+ private final JsProgram jsprogram;
/**
* Computed during {@link #execImpl()}, so that intermediate steps of it can
@@ -657,21 +643,18 @@
private ControlFlowAnalyzer liveAfterInitialSequence;
private final TreeLogger logger;
private final boolean logging;
- private JavaToJavaScriptMap map;
+ private final JavaToJavaScriptMap map;
private final Set<JMethod> methodsInJavaScript;
private final int numEntries;
- private CodeSplitter(TreeLogger logger, JProgram jprogram,
- JsProgram jsprogram, JavaToJavaScriptMap map,
- MultipleDependencyGraphRecorder dependencyRecorder) {
- this.logger = logger.branch(TreeLogger.TRACE,
- "Splitting JavaScript for incremental download");
+ private CodeSplitter(TreeLogger logger, JProgram jprogram, JsProgram jsprogram,
+ JavaToJavaScriptMap map, MultipleDependencyGraphRecorder dependencyRecorder) {
+ this.logger = logger.branch(TreeLogger.TRACE, "Splitting JavaScript for incremental download");
this.jprogram = jprogram;
this.jsprogram = jsprogram;
this.map = map;
this.dependencyRecorder = dependencyRecorder;
- this.initialLoadSequence = new LinkedHashSet<Integer>(
- jprogram.getSplitPointInitialSequence());
+ this.initialLoadSequence = new LinkedHashSet<Integer>(jprogram.getSplitPointInitialSequence());
numEntries = jprogram.entryMethods.size();
logging = Boolean.getBoolean(PROP_LOG_FRAGMENT_MAP);
@@ -685,7 +668,7 @@
/**
* Create a new fragment and add it to the table of fragments.
- *
+ *
* @param splitPoint The split point to associate this code with
* @param alreadyLoaded The code that should be assumed to have already been
* loaded
@@ -704,8 +687,7 @@
System.out.println("==== Fragment " + fragmentStats.size() + " ====");
fragmentExtractor.setStatementLogger(new EchoStatementLogger());
}
- List<JsStatement> stats = fragmentExtractor.extractStatements(liveNow,
- alreadyLoaded);
+ List<JsStatement> stats = fragmentExtractor.extractStatements(liveNow, alreadyLoaded);
stats.addAll(stmtsToAppend);
fragmentStats.put(splitPoint, stats);
}
@@ -718,18 +700,16 @@
private List<ControlFlowAnalyzer> computeAllButOneCfas() {
String dependencyGraphNameAfterInitialSequence = dependencyGraphNameAfterInitialSequence();
- List<ControlFlowAnalyzer> allButOnes = new ArrayList<ControlFlowAnalyzer>(
- numEntries - 1);
+ List<ControlFlowAnalyzer> allButOnes = new ArrayList<ControlFlowAnalyzer>(numEntries - 1);
for (int entry = 1; entry < numEntries; entry++) {
if (isInitial(entry)) {
allButOnes.add(null);
continue;
}
- dependencyRecorder.startDependencyGraph("sp" + entry,
- dependencyGraphNameAfterInitialSequence);
- ControlFlowAnalyzer cfa = new ControlFlowAnalyzer(
- liveAfterInitialSequence);
+ dependencyRecorder
+ .startDependencyGraph("sp" + entry, dependencyGraphNameAfterInitialSequence);
+ ControlFlowAnalyzer cfa = new ControlFlowAnalyzer(liveAfterInitialSequence);
cfa.setDependencyRecorder(dependencyRecorder);
traverseAllButEntry(cfa, entry);
// Traverse leftoversFragmentHasLoaded, because it should not
@@ -804,14 +784,12 @@
liveAfterInitialSequence = new ControlFlowAnalyzer(initiallyLive);
String extendsCfa = "initial";
for (int sp : initialLoadSequence) {
- LivenessPredicate alreadyLoaded = new CfaLivenessPredicate(
- liveAfterInitialSequence);
+ LivenessPredicate alreadyLoaded = new CfaLivenessPredicate(liveAfterInitialSequence);
String depGraphName = "sp" + sp;
dependencyRecorder.startDependencyGraph(depGraphName, extendsCfa);
extendsCfa = depGraphName;
- ControlFlowAnalyzer liveAfterSp = new ControlFlowAnalyzer(
- liveAfterInitialSequence);
+ ControlFlowAnalyzer liveAfterSp = new ControlFlowAnalyzer(liveAfterInitialSequence);
traverseEntry(liveAfterSp, sp);
dependencyRecorder.endDependencyGraph();
@@ -834,10 +812,8 @@
if (isInitial(i)) {
continue;
}
- LivenessPredicate alreadyLoaded = new ExclusivityMapLivenessPredicate(
- fragmentMap, 0);
- LivenessPredicate liveNow = new ExclusivityMapLivenessPredicate(
- fragmentMap, i);
+ LivenessPredicate alreadyLoaded = new ExclusivityMapLivenessPredicate(fragmentMap, 0);
+ LivenessPredicate liveNow = new ExclusivityMapLivenessPredicate(fragmentMap, i);
List<JsStatement> statsToAppend = fragmentExtractor.createCallsToEntryMethods(i);
addFragment(i, alreadyLoaded, liveNow, statsToAppend, fragmentStats);
}
@@ -846,13 +822,10 @@
* Compute the leftovers fragment.
*/
{
- LivenessPredicate alreadyLoaded = new CfaLivenessPredicate(
- liveAfterInitialSequence);
- LivenessPredicate liveNow = new ExclusivityMapLivenessPredicate(
- fragmentMap, 0);
+ LivenessPredicate alreadyLoaded = new CfaLivenessPredicate(liveAfterInitialSequence);
+ LivenessPredicate liveNow = new ExclusivityMapLivenessPredicate(fragmentMap, 0);
List<JsStatement> statsToAppend = fragmentExtractor.createCallToLeftoversFragmentHasLoaded();
- addFragment(numEntries, alreadyLoaded, liveNow, statsToAppend,
- fragmentStats);
+ addFragment(numEntries, alreadyLoaded, liveNow, statsToAppend, fragmentStats);
}
// now install the new statements in the program fragments
@@ -871,7 +844,7 @@
* violated when an atom is mapped to 0 as a leftover, but it has some
* load-order dependency on an atom that was put in an exclusive fragment.
* </p>
- *
+ *
* <p>
* In general, it might be possible to split things better by considering load
* order dependencies when building the fragment map. However, fixing them
@@ -887,8 +860,7 @@
fixUpLoadOrderDependenciesForFieldsInitializedToStrings(fragmentMap);
}
- private void fixUpLoadOrderDependenciesForClassLiterals(
- ExclusivityMap fragmentMap) {
+ private void fixUpLoadOrderDependenciesForClassLiterals(ExclusivityMap fragmentMap) {
int numClassLitStrings = 0;
int numFixups = 0;
for (JField field : fragmentMap.fields.keySet()) {
@@ -905,14 +877,11 @@
}
}
}
- logger.log(TreeLogger.DEBUG, "Fixed up load-order dependencies by moving "
- + numFixups
- + " strings in class literal constructors to fragment 0, out of "
- + numClassLitStrings);
+ logger.log(TreeLogger.DEBUG, "Fixed up load-order dependencies by moving " + numFixups
+ + " strings in class literal constructors to fragment 0, out of " + numClassLitStrings);
}
- private void fixUpLoadOrderDependenciesForFieldsInitializedToStrings(
- ExclusivityMap fragmentMap) {
+ private void fixUpLoadOrderDependenciesForFieldsInitializedToStrings(ExclusivityMap fragmentMap) {
int numFixups = 0;
int numFieldStrings = 0;
@@ -930,10 +899,8 @@
}
}
- logger.log(TreeLogger.DEBUG, "Fixed up load-order dependencies by moving "
- + numFixups
- + " strings used to initialize fields to fragment 0, out of "
- + +numFieldStrings);
+ logger.log(TreeLogger.DEBUG, "Fixed up load-order dependencies by moving " + numFixups
+ + " strings used to initialize fields to fragment 0, out of " + +numFieldStrings);
}
private void fixUpLoadOrderDependenciesForMethods(ExclusivityMap fragmentMap) {
@@ -960,16 +927,14 @@
}
}
- logger.log(TreeLogger.DEBUG,
- "Fixed up load-order dependencies for instance methods by moving "
- + numFixups + " types to fragment 0, out of "
- + jprogram.getDeclaredTypes().size());
+ logger.log(TreeLogger.DEBUG, "Fixed up load-order dependencies for instance methods by moving "
+ + numFixups + " types to fragment 0, out of " + jprogram.getDeclaredTypes().size());
}
private void fixUpLoadOrderDependenciesForTypes(ExclusivityMap fragmentMap) {
int numFixups = 0;
- Queue<JDeclaredType> typesToCheck = new ArrayBlockingQueue<JDeclaredType>(
- jprogram.getDeclaredTypes().size());
+ Queue<JDeclaredType> typesToCheck =
+ new ArrayBlockingQueue<JDeclaredType>(jprogram.getDeclaredTypes().size());
typesToCheck.addAll(jprogram.getDeclaredTypes());
while (!typesToCheck.isEmpty()) {
@@ -985,10 +950,8 @@
}
}
- logger.log(TreeLogger.DEBUG,
- "Fixed up load-order dependencies on supertypes by moving " + numFixups
- + " types to fragment 0, out of "
- + jprogram.getDeclaredTypes().size());
+ logger.log(TreeLogger.DEBUG, "Fixed up load-order dependencies on supertypes by moving "
+ + numFixups + " types to fragment 0, out of " + jprogram.getDeclaredTypes().size());
}
private boolean isInitial(int entry) {
@@ -1023,15 +986,12 @@
continue;
}
ControlFlowAnalyzer allButOne = allButOnes.get(entry - 1);
- Set<JNode> allLiveNodes = union(allButOne.getLiveFieldsAndMethods(),
- allButOne.getFieldsWritten());
+ Set<JNode> allLiveNodes =
+ union(allButOne.getLiveFieldsAndMethods(), allButOne.getFieldsWritten());
updateMap(entry, fragmentMap.fields, allLiveNodes, allFields);
- updateMap(entry, fragmentMap.methods,
- allButOne.getLiveFieldsAndMethods(), allMethods);
- updateMap(entry, fragmentMap.strings, allButOne.getLiveStrings(),
- everything.getLiveStrings());
- updateMap(entry, fragmentMap.types,
- declaredTypesIn(allButOne.getInstantiatedTypes()),
+ updateMap(entry, fragmentMap.methods, allButOne.getLiveFieldsAndMethods(), allMethods);
+ updateMap(entry, fragmentMap.strings, allButOne.getLiveStrings(), everything.getLiveStrings());
+ updateMap(entry, fragmentMap.types, declaredTypesIn(allButOne.getInstantiatedTypes()),
declaredTypesIn(everything.getInstantiatedTypes()));
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/CompoundAssignmentNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/CompoundAssignmentNormalizer.java
index 2f61d58..133dce9 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/CompoundAssignmentNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/CompoundAssignmentNormalizer.java
@@ -88,8 +88,7 @@
JExpression newInstance = possiblyReplace(x.getInstance());
JExpression newIndexExpr = possiblyReplace(x.getIndexExpr());
if (newInstance != x.getInstance() || newIndexExpr != x.getIndexExpr()) {
- JArrayRef newExpr = new JArrayRef(x.getSourceInfo(), newInstance,
- newIndexExpr);
+ JArrayRef newExpr = new JArrayRef(x.getSourceInfo(), newInstance, newIndexExpr);
ctx.replaceMe(newExpr);
}
return false;
@@ -100,8 +99,8 @@
if (x.getInstance() != null) {
JExpression newInstance = possiblyReplace(x.getInstance());
if (newInstance != x.getInstance()) {
- JFieldRef newExpr = new JFieldRef(x.getSourceInfo(), newInstance,
- x.getField(), x.getEnclosingType());
+ JFieldRef newExpr =
+ new JFieldRef(x.getSourceInfo(), newInstance, x.getField(), x.getEnclosingType());
ctx.replaceMe(newExpr);
}
}
@@ -133,8 +132,8 @@
// Create an assignment for this temp and add it to multi.
JLocalRef tempRef = new JLocalRef(x.getSourceInfo(), tempLocal);
- JBinaryOperation asg = new JBinaryOperation(x.getSourceInfo(),
- x.getType(), JBinaryOperator.ASG, tempRef, x);
+ JBinaryOperation asg =
+ new JBinaryOperation(x.getSourceInfo(), x.getType(), JBinaryOperator.ASG, tempRef, x);
multi.exprs.add(asg);
// Update me with the temp
return cloner.cloneExpression(tempRef);
@@ -157,18 +156,19 @@
* expressions that could have side effects with temporaries, so that they
* are only run once.
*/
- ReplaceSideEffectsInLvalue replacer = new ReplaceSideEffectsInLvalue(
- new JMultiExpression(x.getSourceInfo()));
+ ReplaceSideEffectsInLvalue replacer =
+ new ReplaceSideEffectsInLvalue(new JMultiExpression(x.getSourceInfo()));
JExpression newLhs = replacer.accept(x.getLhs());
- JExpression operation = new JBinaryOperation(x.getSourceInfo(),
- newLhs.getType(), op.getNonAssignmentOf(), newLhs, x.getRhs());
+ JExpression operation =
+ new JBinaryOperation(x.getSourceInfo(), newLhs.getType(), op.getNonAssignmentOf(),
+ newLhs, x.getRhs());
operation = modifyResultOperation((JBinaryOperation) operation);
-
+
// newLhs is cloned below because it was used in operation
- JBinaryOperation asg = new JBinaryOperation(x.getSourceInfo(), newLhs.getType(),
- JBinaryOperator.ASG, cloner.cloneExpression(newLhs),
- operation);
+ JBinaryOperation asg =
+ new JBinaryOperation(x.getSourceInfo(), newLhs.getType(), JBinaryOperator.ASG, cloner
+ .cloneExpression(newLhs), operation);
JMultiExpression multiExpr = replacer.getMultiExpr();
if (multiExpr.exprs.isEmpty()) {
@@ -196,20 +196,19 @@
// First, replace the arg with a non-side-effect causing one.
JMultiExpression multi = new JMultiExpression(x.getSourceInfo());
- ReplaceSideEffectsInLvalue replacer = new ReplaceSideEffectsInLvalue(
- multi);
+ ReplaceSideEffectsInLvalue replacer = new ReplaceSideEffectsInLvalue(multi);
JExpression newArg = replacer.accept(x.getArg());
JExpression expressionReturn = expressionToReturn(newArg);
// Now generate the appropriate expressions.
- JLocal tempLocal = createTempLocal(x.getSourceInfo(),
- expressionReturn.getType());
+ JLocal tempLocal = createTempLocal(x.getSourceInfo(), expressionReturn.getType());
// t = x
JLocalRef tempRef = new JLocalRef(x.getSourceInfo(), tempLocal);
- JBinaryOperation asg = new JBinaryOperation(x.getSourceInfo(), x.getType(),
- JBinaryOperator.ASG, tempRef, expressionReturn);
+ JBinaryOperation asg =
+ new JBinaryOperation(x.getSourceInfo(), x.getType(), JBinaryOperator.ASG, tempRef,
+ expressionReturn);
multi.exprs.add(asg);
// x += 1
@@ -242,17 +241,15 @@
ctx.replaceMe(accept(asg));
}
- private JBinaryOperation createAsgOpFromUnary(JExpression arg,
- JUnaryOperator op) {
+ private JBinaryOperation createAsgOpFromUnary(JExpression arg, JUnaryOperator op) {
JBinaryOperator newOp;
if (op == JUnaryOperator.INC) {
newOp = JBinaryOperator.ASG_ADD;
} else if (op == JUnaryOperator.DEC) {
newOp = JBinaryOperator.ASG_SUB;
} else {
- throw new InternalCompilerException(
- "Unexpected modifying unary operator: "
- + String.valueOf(op.getSymbol()));
+ throw new InternalCompilerException("Unexpected modifying unary operator: "
+ + String.valueOf(op.getSymbol()));
}
JExpression one;
@@ -265,8 +262,9 @@
one = JIntLiteral.get(1);
}
// arg is cloned below because the caller is allowed to use it somewhere
- JBinaryOperation asg = new JBinaryOperation(arg.getSourceInfo(), arg.getType(),
- newOp, cloner.cloneExpression(arg), one);
+ JBinaryOperation asg =
+ new JBinaryOperation(arg.getSourceInfo(), arg.getType(), newOp, cloner
+ .cloneExpression(arg), one);
return asg;
}
}
@@ -289,14 +287,14 @@
/**
* Decide what expression to return when breaking up a compound assignment of
- * the form <code>lhs op= rhs</code>. The breakup creates an expression of
- * the form <code>lhs = lhs op rhs</code>, and the right hand side of the
- * newly created expression is passed to this method.
+ * the form <code>lhs op= rhs</code>. The breakup creates an expression of the
+ * form <code>lhs = lhs op rhs</code>, and the right hand side of the newly
+ * created expression is passed to this method.
*/
protected JExpression modifyResultOperation(JBinaryOperation op) {
return op;
}
-
+
protected abstract boolean shouldBreakUp(JBinaryOperation x);
protected abstract boolean shouldBreakUp(JPostfixOperation x);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ControlFlowAnalyzer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ControlFlowAnalyzer.java
index d66ca40..8097e60 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ControlFlowAnalyzer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ControlFlowAnalyzer.java
@@ -76,8 +76,7 @@
/**
* Used to record the dependencies of a specific method.
*/
- void methodIsLiveBecause(JMethod liveMethod,
- ArrayList<JMethod> dependencyChain);
+ void methodIsLiveBecause(JMethod liveMethod, ArrayList<JMethod> dependencyChain);
}
/**
@@ -88,7 +87,7 @@
* TODO(later): make RescueVisitor use less stack?
*/
private class RescueVisitor extends JVisitor {
- private ArrayList<JMethod> curMethodStack = new ArrayList<JMethod>();
+ private final ArrayList<JMethod> curMethodStack = new ArrayList<JMethod>();
@Override
public boolean visit(JArrayType type, Context ctx) {
@@ -111,9 +110,8 @@
if (!didSuperType) {
if (dims > 1) {
// anything[][] -> Object[]
- rescue(
- program.getTypeArray(program.getTypeJavaLangObject(), dims - 1),
- true, isInstantiated);
+ rescue(program.getTypeArray(program.getTypeJavaLangObject(), dims - 1), true,
+ isInstantiated);
} else {
// anything[] -> Object
// But instead of Object, rescue the base Array implementation type.
@@ -187,11 +185,11 @@
JType exprType = x.getExpr().getType();
if (program.typeOracle.isSingleJsoImpl(targetType)) {
/*
- * It's a JSO interface, check if the source expr can be a live JSO
- * 1) source is java.lang.Object (JSO could have been assigned to it)
- * 2) source is JSO
- * 3) source is SingleJSO interface whose implementor is live
- */
+ * It's a JSO interface, check if the source expr can be a live JSO 1)
+ * source is java.lang.Object (JSO could have been assigned to it) 2)
+ * source is JSO 3) source is SingleJSO interface whose implementor is
+ * live
+ */
if (program.getTypeJavaLangObject() == exprType
|| program.typeOracle.canBeJavaScriptObject(exprType)) {
// source is JSO or SingleJso interface whose implementor is live
@@ -359,8 +357,7 @@
@Override
public boolean visit(JMethodCall call, Context ctx) {
JMethod method = call.getTarget();
- if (method.isStatic()
- || program.isJavaScriptObject(method.getEnclosingType())
+ if (method.isStatic() || program.isJavaScriptObject(method.getEnclosingType())
|| instantiatedTypes.contains(method.getEnclosingType())) {
rescue(method);
} else {
@@ -500,8 +497,7 @@
*/
private void maybeRescueJavaScriptObjectPassingIntoJava(JType type) {
boolean doIt = false;
- if (program.typeOracle.canBeJavaScriptObject(type)
- || program.isJavaLangString(type)) {
+ if (program.typeOracle.canBeJavaScriptObject(type) || program.isJavaLangString(type)) {
doIt = true;
} else if (type instanceof JArrayType) {
/*
@@ -510,8 +506,7 @@
*/
JArrayType arrayType = (JArrayType) type;
JType elementType = arrayType.getElementType();
- if (elementType instanceof JPrimitiveType
- || program.isJavaLangString(elementType)
+ if (elementType instanceof JPrimitiveType || program.isJavaLangString(elementType)
|| program.typeOracle.canBeJavaScriptObject(elementType)) {
doIt = true;
}
@@ -520,8 +515,7 @@
rescue((JReferenceType) type, true, true);
if (program.typeOracle.isSingleJsoImpl(type)) {
// Cast of JSO into SingleJso interface, rescue the implementor
- rescue(program.typeOracle.getSingleJsoImpl((JReferenceType) type),
- true, true);
+ rescue(program.typeOracle.getSingleJsoImpl((JReferenceType) type), true, true);
}
}
}
@@ -566,8 +560,7 @@
return false;
}
- private void rescue(JReferenceType type, boolean isReferenced,
- boolean isInstantiated) {
+ private void rescue(JReferenceType type, boolean isReferenced, boolean isInstantiated) {
if (type == null) {
return;
}
@@ -638,8 +631,7 @@
JField field = (JField) var;
accept(field.getInitializer());
referencedTypes.add(field.getEnclosingType());
- liveFieldsAndMethods.add(field.getEnclosingType().getMethods().get(
- 0));
+ liveFieldsAndMethods.add(field.getEnclosingType().getMethods().get(0));
}
}
}
@@ -656,8 +648,8 @@
JPrimitiveType charType = program.getTypePrimitiveChar();
JClassType stringType = program.getTypeJavaLangString();
if (type instanceof JReferenceType
- && !program.typeOracle.canTriviallyCast((JReferenceType) type,
- stringType) && type != program.getTypeNull()) {
+ && !program.typeOracle.canTriviallyCast((JReferenceType) type, stringType)
+ && type != program.getTypeNull()) {
/*
* Any reference types (except String, which works by default) that take
* part in a concat must rescue java.lang.Object.toString().
@@ -732,7 +724,7 @@
}
}
- private JDeclaredType baseArrayType;
+ private final JDeclaredType baseArrayType;
private DependencyRecorder dependencyRecorder;
private Set<JField> fieldsWritten = new HashSet<JField>();
@@ -769,8 +761,8 @@
referencedTypes = new HashSet<JReferenceType>(cfa.referencedTypes);
stringValueOfChar = cfa.stringValueOfChar;
liveStrings = new HashSet<String>(cfa.liveStrings);
- methodsLiveExceptForInstantiability = new HashSet<JMethod>(
- cfa.methodsLiveExceptForInstantiability);
+ methodsLiveExceptForInstantiability =
+ new HashSet<JMethod>(cfa.methodsLiveExceptForInstantiability);
methodsThatOverrideMe = cfa.methodsThatOverrideMe;
}
@@ -819,8 +811,7 @@
*/
public void setDependencyRecorder(DependencyRecorder dr) {
if (dependencyRecorder != null && dr != null) {
- throw new IllegalArgumentException(
- "Attempting to set multiple dependency recorders");
+ throw new IllegalArgumentException("Attempting to set multiple dependency recorders");
}
this.dependencyRecorder = dr;
}
@@ -849,7 +840,8 @@
public void traverseFromLeftoversFragmentHasLoaded() {
if (program.entryMethods.size() > 1) {
- traverseFrom(program.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded"));
+ traverseFrom(program
+ .getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded"));
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/DeadCodeElimination.java b/dev/core/src/com/google/gwt/dev/jjs/impl/DeadCodeElimination.java
index 9b7acd3..0111884 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/DeadCodeElimination.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/DeadCodeElimination.java
@@ -152,8 +152,8 @@
break;
case EQ:
// simplify: null == null -> true
- if (lhs.getType() == program.getTypeNull()
- && rhs.getType() == program.getTypeNull() && !x.hasSideEffects()) {
+ if (lhs.getType() == program.getTypeNull() && rhs.getType() == program.getTypeNull()
+ && !x.hasSideEffects()) {
ctx.replaceMe(program.getLiteralBoolean(true));
return;
}
@@ -161,8 +161,8 @@
break;
case NEQ:
// simplify: null != null -> false
- if (lhs.getType() == program.getTypeNull()
- && rhs.getType() == program.getTypeNull() && !x.hasSideEffects()) {
+ if (lhs.getType() == program.getTypeNull() && rhs.getType() == program.getTypeNull()
+ && !x.hasSideEffects()) {
ctx.replaceMe(program.getLiteralBoolean(false));
return;
}
@@ -262,14 +262,13 @@
@Override
public void endVisit(JCastOperation x, Context ctx) {
- maybeReplaceMe(x, simplifier.cast(x, x.getSourceInfo(), x.getCastType(),
- x.getExpr()), ctx);
+ maybeReplaceMe(x, simplifier.cast(x, x.getSourceInfo(), x.getCastType(), x.getExpr()), ctx);
}
@Override
public void endVisit(JConditional x, Context ctx) {
- maybeReplaceMe(x, simplifier.conditional(x, x.getSourceInfo(),
- x.getType(), x.getIfTest(), x.getThenExpr(), x.getElseExpr()), ctx);
+ maybeReplaceMe(x, simplifier.conditional(x, x.getSourceInfo(), x.getType(), x.getIfTest(), x
+ .getThenExpr(), x.getElseExpr()), ctx);
}
@Override
@@ -331,8 +330,7 @@
}
if (x.hasClinit()) {
- multi.exprs.add(createClinitCall(x.getSourceInfo(),
- x.getField().getEnclosingType()));
+ multi.exprs.add(createClinitCall(x.getSourceInfo(), x.getField().getEnclosingType()));
}
if (literal != null) {
@@ -365,8 +363,8 @@
*/
@Override
public void endVisit(JIfStatement x, Context ctx) {
- maybeReplaceMe(x, simplifier.ifStatement(x, x.getSourceInfo(),
- x.getIfExpr(), x.getThenStmt(), x.getElseStmt(), currentMethod), ctx);
+ maybeReplaceMe(x, simplifier.ifStatement(x, x.getSourceInfo(), x.getIfExpr(),
+ x.getThenStmt(), x.getElseStmt(), currentMethod), ctx);
}
@Override
@@ -414,8 +412,7 @@
ctx.replaceMe(program.getLiteralNull());
} else if (targetType != targetType.getClinitTarget()) {
// Tighten the target.
- ctx.replaceMe(createClinitCall(x.getSourceInfo(),
- targetType.getClinitTarget()));
+ ctx.replaceMe(createClinitCall(x.getSourceInfo(), targetType.getClinitTarget()));
}
}
}
@@ -432,8 +429,7 @@
ignoringExpressionOutput.removeAll(exprs);
} else {
// Remove the non-final children we previously added.
- List<JExpression> nonFinalChildren = exprs.subList(0,
- exprs.size() - 1);
+ List<JExpression> nonFinalChildren = exprs.subList(0, exprs.size() - 1);
ignoringExpressionOutput.removeAll(nonFinalChildren);
}
}
@@ -476,8 +472,7 @@
JMultiExpression multi = new JMultiExpression(x.getSourceInfo());
multi.exprs.addAll(x.getArgs());
if (x.hasClinit()) {
- multi.exprs.add(createClinitCall(x.getSourceInfo(),
- x.getTarget().getEnclosingType()));
+ multi.exprs.add(createClinitCall(x.getSourceInfo(), x.getTarget().getEnclosingType()));
}
ignoringExpressionOutput.add(multi);
ctx.replaceMe(this.accept(multi));
@@ -503,8 +498,7 @@
lvalues.remove(x.getArg());
}
if (ignoringExpressionOutput.contains(x)) {
- JPrefixOperation newOp = new JPrefixOperation(x.getSourceInfo(),
- x.getOp(), x.getArg());
+ JPrefixOperation newOp = new JPrefixOperation(x.getSourceInfo(), x.getOp(), x.getArg());
ctx.replaceMe(newOp);
}
}
@@ -560,8 +554,7 @@
JLocalRef localRef = itA.next();
itB.next();
JReferenceType type = (JReferenceType) localRef.getType();
- if (!program.typeOracle.isInstantiatedType(type)
- || type == program.getTypeNull()) {
+ if (!program.typeOracle.isInstantiatedType(type) || type == program.getTypeNull()) {
itA.remove();
itB.remove();
madeChanges();
@@ -645,8 +638,7 @@
ignoringExpressionOutput.add(x.getInstance());
}
List<JExpression> args = x.getArgs();
- List<JExpression> ignoredArgs = args.subList(target.getParams().size(),
- args.size());
+ List<JExpression> ignoredArgs = args.subList(target.getParams().size(), args.size());
ignoringExpressionOutput.addAll(ignoredArgs);
return true;
}
@@ -660,8 +652,7 @@
ignoringExpressionOutput.addAll(exprs);
} else {
// Only my final child matters.
- List<JExpression> nonFinalChildren = exprs.subList(0,
- exprs.size() - 1);
+ List<JExpression> nonFinalChildren = exprs.subList(0, exprs.size() - 1);
ignoringExpressionOutput.addAll(nonFinalChildren);
}
}
@@ -706,15 +697,13 @@
return true;
}
- private JMethodCall createClinitCall(SourceInfo sourceInfo,
- JDeclaredType targetType) {
+ private JMethodCall createClinitCall(SourceInfo sourceInfo, JDeclaredType targetType) {
JMethod clinit = targetType.getClinitTarget().getMethods().get(0);
assert (JProgram.isClinit(clinit));
return new JMethodCall(sourceInfo, null, clinit);
}
- private void evalConcat(SourceInfo info, JExpression lhs, JExpression rhs,
- Context ctx) {
+ private void evalConcat(SourceInfo info, JExpression lhs, JExpression rhs, Context ctx) {
if (lhs instanceof JValueLiteral && rhs instanceof JValueLiteral) {
Object lhsObj = ((JValueLiteral) lhs).getValueObj();
Object rhsObj = ((JValueLiteral) rhs).getValueObj();
@@ -752,8 +741,7 @@
*
* @return Whether a change was made
*/
- private boolean evalOpOnLiteral(JUnaryOperator op, JValueLiteral exp,
- Context ctx) {
+ private boolean evalOpOnLiteral(JUnaryOperator op, JValueLiteral exp, Context ctx) {
switch (op) {
case BIT_NOT: {
long value = toLong(exp);
@@ -801,10 +789,9 @@
*
* @return Whether a change was made
*/
- private boolean evalOpOnLiterals(JBinaryOperator op, JValueLiteral lhs,
- JValueLiteral rhs, Context ctx) {
- if (isTypeString(lhs) || isTypeString(rhs) || isTypeNull(lhs)
- || isTypeNull(rhs)) {
+ private boolean evalOpOnLiterals(JBinaryOperator op, JValueLiteral lhs, JValueLiteral rhs,
+ Context ctx) {
+ if (isTypeString(lhs) || isTypeString(rhs) || isTypeNull(lhs) || isTypeNull(rhs)) {
// String simplifications are handled elsewhere.
// Null can only be used with String append, and with
// comparison with EQ and NEQ, and those simplifications
@@ -827,8 +814,7 @@
case MUL:
case DIV:
case MOD: {
- if (isTypeDouble(lhs) || isTypeFloat(lhs) || isTypeDouble(rhs)
- || isTypeFloat(rhs)) {
+ if (isTypeDouble(lhs) || isTypeFloat(lhs) || isTypeDouble(rhs) || isTypeFloat(rhs)) {
// do the op on doubles and cast back
double left = toDouble(lhs);
double right = toDouble(rhs);
@@ -907,8 +893,7 @@
case LTE:
case GT:
case GTE: {
- if (isTypeDouble(lhs) || isTypeDouble(rhs) || isTypeFloat(lhs)
- || isTypeFloat(rhs)) {
+ if (isTypeDouble(lhs) || isTypeDouble(rhs) || isTypeFloat(lhs) || isTypeFloat(rhs)) {
// operate on doubles
double left = toDouble(lhs);
double right = toDouble(rhs);
@@ -1169,7 +1154,8 @@
}
private boolean isTypeFloatOrDouble(JType type) {
- return ((type == program.getTypePrimitiveDouble()) || (type == program.getTypePrimitiveFloat()));
+ return ((type == program.getTypePrimitiveDouble()) || (type == program
+ .getTypePrimitiveFloat()));
}
/**
@@ -1181,10 +1167,9 @@
}
private boolean isTypeIntegral(JType type) {
- return ((type == program.getTypePrimitiveInt())
- || (type == program.getTypePrimitiveLong())
- || (type == program.getTypePrimitiveChar())
- || (type == program.getTypePrimitiveByte()) || (type == program.getTypePrimitiveShort()));
+ return ((type == program.getTypePrimitiveInt()) || (type == program.getTypePrimitiveLong())
+ || (type == program.getTypePrimitiveChar()) || (type == program.getTypePrimitiveByte()) || (type == program
+ .getTypePrimitiveShort()));
}
private boolean isTypeLong(JExpression exp) {
@@ -1334,8 +1319,7 @@
}
}
- private boolean simplifyAdd(JExpression lhs, JExpression rhs, Context ctx,
- JType type) {
+ private boolean simplifyAdd(JExpression lhs, JExpression rhs, Context ctx, JType type) {
if (isLiteralZero(rhs)) {
ctx.replaceMe(simplifier.cast(type, lhs));
return true;
@@ -1356,8 +1340,7 @@
if (bool) {
ctx.replaceMe(exp);
} else {
- ctx.replaceMe(new JPrefixOperation(exp.getSourceInfo(),
- JUnaryOperator.NOT, exp));
+ ctx.replaceMe(new JPrefixOperation(exp.getSourceInfo(), JUnaryOperator.NOT, exp));
}
}
@@ -1368,8 +1351,7 @@
* <code>lhs == rhs</code>. Assumes that the case where both sides are
* literals has already been checked.
*/
- private void simplifyBooleanEq(JExpression lhs, JExpression rhs,
- Context ctx, boolean negate) {
+ private void simplifyBooleanEq(JExpression lhs, JExpression rhs, Context ctx, boolean negate) {
if (lhs instanceof JBooleanLiteral) {
boolean left = ((JBooleanLiteral) lhs).getValue();
simplifyBooleanEq(rhs, left ^ negate, ctx);
@@ -1382,8 +1364,7 @@
}
}
- private boolean simplifyDiv(JExpression lhs, JExpression rhs, Context ctx,
- JType type) {
+ private boolean simplifyDiv(JExpression lhs, JExpression rhs, Context ctx, JType type) {
if (isLiteralOne(rhs)) {
ctx.replaceMe(simplifier.cast(type, lhs));
return true;
@@ -1400,16 +1381,14 @@
* Simplify <code>lhs == rhs</code>. If <code>negate</code> is true, then
* it's actually static evaluation of <code>lhs != rhs</code>.
*/
- private void simplifyEq(JExpression lhs, JExpression rhs, Context ctx,
- boolean negated) {
+ private void simplifyEq(JExpression lhs, JExpression rhs, Context ctx, boolean negated) {
if (isTypeBoolean(lhs) && isTypeBoolean(rhs)) {
simplifyBooleanEq(lhs, rhs, ctx, negated);
return;
}
}
- private boolean simplifyMul(JExpression lhs, JExpression rhs, Context ctx,
- JType type) {
+ private boolean simplifyMul(JExpression lhs, JExpression rhs, Context ctx, JType type) {
if (isLiteralOne(rhs)) {
ctx.replaceMe(simplifier.cast(type, lhs));
return true;
@@ -1465,8 +1444,7 @@
return new JPrefixOperation(exp.getSourceInfo(), JUnaryOperator.NEG, exp);
}
- private boolean simplifySub(JExpression lhs, JExpression rhs, Context ctx,
- JType type) {
+ private boolean simplifySub(JExpression lhs, JExpression rhs, Context ctx, JType type) {
if (isLiteralZero(rhs)) {
ctx.replaceMe(simplifier.cast(type, lhs));
return true;
@@ -1480,8 +1458,7 @@
private void simplifyXor(JExpression lhs, JBooleanLiteral rhs, Context ctx) {
if (rhs.getValue()) {
- ctx.replaceMe(new JPrefixOperation(lhs.getSourceInfo(),
- JUnaryOperator.NOT, lhs));
+ ctx.replaceMe(new JPrefixOperation(lhs.getSourceInfo(), JUnaryOperator.NOT, lhs));
} else {
ctx.replaceMe(lhs);
}
@@ -1560,8 +1537,7 @@
* this value is not changed.
*/
// TODO(spoon): use simplifier.cast to shorten this
- if ((x.getType() instanceof JPrimitiveType)
- && (lit instanceof JValueLiteral)) {
+ if ((x.getType() instanceof JPrimitiveType) && (lit instanceof JValueLiteral)) {
JPrimitiveType xTypePrim = (JPrimitiveType) x.getType();
lit = xTypePrim.coerceLiteral((JValueLiteral) lit);
}
@@ -1574,8 +1550,7 @@
/**
* Replace String methods having literal args with the static result.
*/
- private void tryOptimizeStringCall(JMethodCall x, Context ctx,
- JMethod method) {
+ private void tryOptimizeStringCall(JMethodCall x, Context ctx, JMethod method) {
if (method.getType() == program.getTypeVoid()) {
return;
@@ -1631,8 +1606,7 @@
}
Object result = actual.invoke(instance, paramValues);
if (result instanceof String) {
- ctx.replaceMe(program.getLiteralString(x.getSourceInfo(),
- (String) result));
+ ctx.replaceMe(program.getLiteralString(x.getSourceInfo(), (String) result));
} else if (result instanceof Boolean) {
ctx.replaceMe(program.getLiteralBoolean(((Boolean) result).booleanValue()));
} else if (result instanceof Character) {
@@ -1673,8 +1647,7 @@
*
* becomes if (i == 1) { a(); b(); } else { c(); d(); }
*/
- JCaseStatement caseStatement = (JCaseStatement) body.getStatements().get(
- 0);
+ JCaseStatement caseStatement = (JCaseStatement) body.getStatements().get(0);
JStatement statement = body.getStatements().get(1);
FindBreakContinueStatementsVisitor visitor = new FindBreakContinueStatementsVisitor();
@@ -1686,13 +1659,13 @@
if (caseStatement.getExpr() != null) {
// Create an if statement equivalent to the single-case switch.
- JBinaryOperation compareOperation = new JBinaryOperation(
- x.getSourceInfo(), program.getTypePrimitiveBoolean(),
- JBinaryOperator.EQ, x.getExpr(), caseStatement.getExpr());
+ JBinaryOperation compareOperation =
+ new JBinaryOperation(x.getSourceInfo(), program.getTypePrimitiveBoolean(),
+ JBinaryOperator.EQ, x.getExpr(), caseStatement.getExpr());
JBlock block = new JBlock(x.getSourceInfo());
block.addStmt(statement);
- JIfStatement ifStatement = new JIfStatement(x.getSourceInfo(),
- compareOperation, block, null);
+ JIfStatement ifStatement =
+ new JIfStatement(x.getSourceInfo(), compareOperation, block, null);
replaceMe(ifStatement, ctx);
} else {
// All we have is a default case; convert to a JBlock.
@@ -1796,8 +1769,7 @@
private OptimizerStats execImpl(JNode node) {
OptimizerStats stats = new OptimizerStats(NAME);
- Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
DeadCodeVisitor deadCodeVisitor = new DeadCodeVisitor();
deadCodeVisitor.accept(node);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/EnumOrdinalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/EnumOrdinalizer.java
index fbca937..a1f35fd 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/EnumOrdinalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/EnumOrdinalizer.java
@@ -59,834 +59,57 @@
/**
* This optimizer replaces enum constants with their ordinal value (a simple
- * int) when possible. We call this process "ordinalization".
+ * int) when possible. We call this process "ordinalization".
*
- * Generally, this can be done for enums that are only ever referred to by
- * reference, or by their ordinal value. For the specific set of conditions
- * under which ordinalization can proceed, see the notes for the nested class
+ * Generally, this can be done for enums that are only ever referred to by
+ * reference, or by their ordinal value. For the specific set of conditions
+ * under which ordinalization can proceed, see the notes for the nested class
* {@link EnumOrdinalizer.CannotBeOrdinalAnalyzer} below.
- *
+ *
* This optimizer modifies enum classes to change their field constants to ints,
- * and to remove initialization of those constants in the clinit method. An
+ * and to remove initialization of those constants in the clinit method. An
* ordinalized enum class will not be removed from the AST by this optimizer,
- * but as long as all references to it are replaced (which is one of the
- * requirements for ordinalization), then the enum class itself will be pruned
+ * but as long as all references to it are replaced (which is one of the
+ * requirements for ordinalization), then the enum class itself will be pruned
* by subsequent optimizer passes.
- *
+ *
* Regardless of whether an ordinalized enum class ends up being completely
- * pruned away, the AST is expected to be in a coherent and usable state after
- * any pass of this optimizer. Thus, this optimizer should be considered to be
+ * pruned away, the AST is expected to be in a coherent and usable state after
+ * any pass of this optimizer. Thus, this optimizer should be considered to be
* stateless.
*
* The process is broken up into 3 separate passes over the AST, each
- * implemented as a separate visitor class. The first visitor,
- * {@link EnumOrdinalizer.CannotBeOrdinalAnalyzer} compiles information
- * about each enum class in the AST, and looks for reasons not to ordinalize
- * each enum. Thus, it prepares a "black-list" of enum classes that cannot be
- * ordinalized (and it follows that all enums that don't get entered in the
- * black-list, will be allowed to be ordinalized. The set of conditions which
+ * implemented as a separate visitor class. The first visitor,
+ * {@link EnumOrdinalizer.CannotBeOrdinalAnalyzer} compiles information about
+ * each enum class in the AST, and looks for reasons not to ordinalize each
+ * enum. Thus, it prepares a "black-list" of enum classes that cannot be
+ * ordinalized (and it follows that all enums that don't get entered in the
+ * black-list, will be allowed to be ordinalized. The set of conditions which
* cause an enum to be black-listed are outlined below.
*
* If there are enum classes that didn't get black-listed remaining, the
- * subsequent passes of the optimizer will be invoked. The first,
+ * subsequent passes of the optimizer will be invoked. The first,
* {@link EnumOrdinalizer.ReplaceEnumTypesWithInteger}, replaces the type info
* for each field or expression involved with a target enum constant with an
- * integer. The final visitor, descriptively named
+ * integer. The final visitor, descriptively named
* {@link EnumOrdinalizer.ReplaceOrdinalFieldAndMethodRefsWithOrdinal}, will do
* the job of replacing the value for references to the Enum ordinal field or
* method of an enum constant that has been ordinalized.
*/
public class EnumOrdinalizer {
- public static final String NAME = EnumOrdinalizer.class.getSimpleName();
-
- private static Tracker tracker = null;
- private static boolean trackerEnabled =
- (System.getProperty("gwt.enableEnumOrdinalizerTracking") != null);
-
- public static void enableTracker() {
- trackerEnabled = true;
- }
-
- public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(
- CompilerEventType.OPTIMIZE, "optimizer", NAME);
-
- startTracker();
- OptimizerStats stats = new EnumOrdinalizer(program).execImpl();
- optimizeEvent.end("didChange", "" + stats.didChange());
- return stats;
- }
-
- public static Tracker getTracker() {
- return tracker;
- }
-
- public static void resetTracker() {
- if (tracker != null) {
- tracker = null;
- startTracker();
- }
- }
-
- private static void startTracker() {
- if (trackerEnabled && tracker == null) {
- tracker = new Tracker();
- }
- }
-
- private final JProgram program;
- private final JType classLiteralHolderType;
- private final JType nullType;
- private final JType javaScriptObjectType;
- private final JType enumType;
- private final JField enumOrdinalField;
- private final JMethod classCreateForEnumMethod;
- private final JMethod enumCreateValueOfMapMethod;
- private final JMethod enumSuperConstructor;
- private final JMethod enumOrdinalMethod;
- private final Set<JEnumType> ordinalizationBlackList = new HashSet<JEnumType>();
- private final Map<String, JEnumType> enumsVisited = new HashMap<String, JEnumType>();
-
- public EnumOrdinalizer(JProgram program) {
- this.program = program;
- this.classLiteralHolderType = program.getIndexedType("ClassLiteralHolder");
- this.nullType = program.getTypeNull();
- this.javaScriptObjectType = program.getJavaScriptObject();
- this.enumType = program.getIndexedType("Enum");
- this.enumOrdinalField = program.getIndexedField("Enum.ordinal");
- this.classCreateForEnumMethod = program.getIndexedMethod("Class.createForEnum");
- this.enumCreateValueOfMapMethod = program.getIndexedMethod("Enum.createValueOfMap");
- this.enumOrdinalMethod = program.getIndexedMethod("Enum.ordinal");
- this.enumSuperConstructor = program.getIndexedMethod("Enum.Enum");
- }
-
- /**
- * A visitor which keeps track of the enums which cannot be ordinalized. It
- * does this by keeping track of a "black-list" for ordinals which violate the
- * conditions for ordinalization, below.
- *
- * An enum cannot be ordinalized, if it:
- * is implicitly upcast.
- * is implicitly cast to from a nullType.
- * is implicitly cast to or from a javaScriptObject type.
- * is explicitly cast to another type (or vice-versa).
- * it's class literal is used explicitly.
- * it has an artificial rescue recorded for it.
- * has any field referenced, except for:
- * one of it's enum constants
- * Enum.ordinal
- * has any method called, except for:
- * ordinal()
- * Enum.ordinal()
- * Enum() super constructor
- * Enum.createValueOfMap()
- *
- * This visitor extends the ImplicitUpcastAnalyzer, which encapsulates all
- * the conditions where implicit upcasting can occur in an AST. The rest of
- * the logic for checking ordinalizability is encapsulated in this sub-class.
- *
- * It also keeps track of all enums encountered, so we can know if we need to
- * continue with the other visitors of the optimizer after this visitor runs.
- *
- * We make special allowances not to check any code statements that appear
- * within the ClassLiteralHolder class, which can contain a reference to all
- * enum class literals in the program, even after ordinalization occurs.
- *
- * Also, we ignore visiting the getClass() method for any enum subclass, since
- * it will also cause a visit to the enum's class literal, and we don't
- * necessarily want to prevent ordinalization in that case.
- *
- * Special checking is needed to detect a class literal reference that occurs
- * within a JSNI method body. We don't get a visit to JClassLiteral in that
- * case, so we need to inspect visits to JsniFieldRef for the possibility it
- * might be a reference to a class literal.
- *
- * We also skip any checking in a method call to Enum.createValueOfMap(),
- * since this is generated for any enum class initially within the extra
- * enumClass$Map class, and this call contains an implicit upcast in the
- * method call args (as well as a reference to the static enumClass$VALUES
- * field), which we want to ignore. The enumClass$Map class will not get
- * pruned as long as the enumClass is not ordinalized, and so we need to
- * ignore it's presence in the consideration for whether an enum class is
- * ordinalizable.
- */
- private class CannotBeOrdinalAnalyzer extends ImplicitUpcastAnalyzer {
-
- private final Map<String, SourceInfo> jsniClassLiteralsInfo = new HashMap<String, SourceInfo>();
- private final Stack<JCastOperation> castOpsToIgnore =
- new Stack<JCastOperation>();
-
- public CannotBeOrdinalAnalyzer(JProgram program) {
- super(program);
- }
-
- /*
- * After program is visited, post-process remaining tasks from accumulated data.
- */
- public void afterVisitor() {
- // black-list any Jsni enum ClassLiteralsVisited
- for (String classLiteralName : jsniClassLiteralsInfo.keySet()) {
- JEnumType enumFromLiteral = enumsVisited.get(classLiteralName);
- if (enumFromLiteral != null) {
- addToBlackList(enumFromLiteral, jsniClassLiteralsInfo.get(classLiteralName));
- }
- }
- }
-
- @Override
- public void endVisit(JCastOperation x, Context ctx) {
- // see if we've previously marked this castOp to be exempted
- if (!castOpsToIgnore.empty() &&
- castOpsToIgnore.peek() == x) {
- castOpsToIgnore.pop();
- return;
- }
-
- // check for explicit cast (check both directions)
- blackListIfEnumCast(x.getExpr().getType(), x.getCastType(), x.getSourceInfo());
- blackListIfEnumCast(x.getCastType(), x.getExpr().getType(), x.getSourceInfo());
- }
-
- @Override
- public void endVisit(JClassLiteral x, Context ctx) {
- /*
- * Check for references to an enum's class literal. We need to
- * black-list classes in this case, since there could be a call
- * to Enum.valueOf(someEnum.class,"name"), etc.
- *
- * Note: we won't get here for class literals that occur in the
- * ClassLiteralHolder class, or within the getClass method of an
- * enum class (see comments above).
- */
- JEnumType type = getEnumType(x.getRefType());
- if (type != null) {
- blackListIfEnum(type, x.getSourceInfo());
- }
- }
-
- @Override
- public void endVisit(JClassType x, Context ctx) {
- // black-list any artificially rescued classes recorded for this class
- List<JNode> rescues = x.getArtificialRescues();
- if (rescues != null && rescues.size() > 0) {
- for (JNode rescueNode : rescues) {
- if (rescueNode instanceof JType) {
- blackListIfEnum((JType) rescueNode, x.getSourceInfo());
- }
- }
- }
-
- // keep track of all enum classes visited
- JEnumType maybeEnum = x.isEnumOrSubclass();
- if (maybeEnum != null) {
- enumsVisited.put(program.getClassLiteralName(maybeEnum), maybeEnum);
- }
- }
-
- @Override
- public void endVisit(JFieldRef x, Context ctx) {
- // don't need to check Enum.ordinal
- if (x.getField() == enumOrdinalField) {
- return;
- }
-
- if (x.getInstance() != null) {
- // check any instance field reference other than ordinal
- blackListIfEnumExpression(x.getInstance());
- } else if (x.getField().isStatic()) {
- // check static field references
-
- /*
- * Need to exempt static fieldRefs to the special $VALUES array that
- * gets generated for all enum classes, if the reference occurs
- * within the enum class itself (such as happens in the clinit() or
- * values() method for all enums).
- */
- if (x.getField().getName().equals("$VALUES") &&
- this.currentMethod.getEnclosingType() ==
- x.getField().getEnclosingType()) {
- if (getEnumType(x.getField().getEnclosingType()) != null) {
- return;
- }
- }
-
- /*
- * Need to exempt static fieldRefs for enum constants themselves.
- * Detect these as final fields, that have the same enum type as
- * their enclosing type.
- */
- if (x.getField().isFinal() &&
- (x.getField().getEnclosingType() ==
- getEnumType(x.getField().getType()))) {
- return;
- }
-
- /*
- * Check any other refs to static fields of an enum class. This
- * includes references to $VALUES that might occur outside of the enum
- * class itself. This can occur when a call to the values() method gets
- * inlined, etc. Also check here for any user defined static fields.
- */
- blackListIfEnum(x.getField().getEnclosingType(), x.getSourceInfo());
- }
- }
-
- @Override
- public void endVisit(JsniFieldRef x, Context ctx) {
- /*
- * Can't do the same thing as for JFieldRef,
- * all JsniFieldRefs are cast to JavaScriptObjects.
- * Need to check both the field type and the type of the instance
- * or enclosing class referencing the field.
- */
-
- // check the field type
- blackListIfEnum(x.getField().getType(), x.getSourceInfo());
-
- // check the referrer
- if (x.getInstance() != null) {
- blackListIfEnumExpression(x.getInstance());
- } else {
- blackListIfEnum(x.getField().getEnclosingType(), x.getSourceInfo());
- }
-
- /*
- * need to also check JsniFieldRef's for a possible reference to a
- * class literal, since we don't get a visit to JClassLiteral when
- * it occurs within Jsni (shouldn't it?).
- */
- if (x.getField().getEnclosingType() == classLiteralHolderType) {
- // see if it has an initializer with a method call to "createForEnum"
- JExpression initializer = x.getField().getInitializer();
- if (initializer instanceof JMethodCall) {
- if (((JMethodCall) initializer).getTarget() == classCreateForEnumMethod) {
- jsniClassLiteralsInfo.put(x.getField().getName(), x.getSourceInfo());
- }
- }
- }
- }
-
- @Override
- public void endVisit(JMethodCall x, Context ctx) {
- // exempt calls to certain methods on the Enum super class
- if (x.getTarget() == enumCreateValueOfMapMethod ||
- x.getTarget() == enumSuperConstructor ||
- x.getTarget() == enumOrdinalMethod) {
- return;
- }
-
- // any other method on an enum class should cause it to be black-listed
- if (x.getInstance() != null) {
- blackListIfEnumExpression(x.getInstance());
- } else if (x.getTarget().isStatic()) {
- /*
- * need to exempt static methodCalls for an enum class if it occurs
- * within the enum class itself (such as in $clinit() or values())
- */
- if (this.currentMethod.getEnclosingType() !=
- x.getTarget().getEnclosingType()) {
- blackListIfEnum(x.getTarget().getEnclosingType(), x.getSourceInfo());
- }
- }
-
- // defer to ImplicitUpcastAnalyzer to check method call args & params
- super.endVisit(x, ctx);
- }
-
- @Override
- public void endVisit(JsniMethodRef x, Context ctx) {
- // no enum methods are exempted if occur within a JsniMethodRef
- if (x.getInstance() != null) {
- blackListIfEnumExpression(x.getInstance());
- } else if (x.getTarget().isStatic()) {
- /*
- * need to exempt static methodCalls for an enum class if it occurs
- * within the enum class itself (such as in $clinit() or values())
- */
- if (this.currentMethod.getEnclosingType() !=
- x.getTarget().getEnclosingType()) {
- blackListIfEnum(x.getTarget().getEnclosingType(), x.getSourceInfo());
- }
- }
-
- // defer to ImplicitUpcastAnalyzer to check method call args & params
- super.endVisit(x, ctx);
- }
-
- @Override
- public boolean visit(JClassType x, Context ctx) {
- /*
- * Don't want to visit the large ClassLiteralHolder class, it doesn't
- * contain references to actual usage of enum class literals. It's also
- * a time savings to not traverse this class.
- */
- if (x == classLiteralHolderType) {
- return false;
- }
- return true;
- }
-
- @Override
- public boolean visit(JFieldRef x, Context ctx) {
- /*
- * If we have a field ref of Enum.ordinal, then we want to allow a
- * cast operation from enum subclass to Enum on the instance. Other
- * optimizers have a tendency to convert things like:
- *
- * 'switch(enumObj)' to
- * 'switch((Enum)enumObj).ordinal'
- *
- * We don't want to blacklist enumObj in that case, so we push this castOp
- * on a stack and check it in the subsequent call to endVisit for
- * JCastOperation. We can't simply return false and prevent
- * the visit of the JCastOperation altogether, since we do need to visit
- * the JCastOperation's sub-expression. Since the sub-expression could
- * potentially also contain similar cast operations, we use a stack to
- * keep track of 'castOpsToIgnore'.
- */
- if (x.getField() == enumOrdinalField) {
- if (x.getInstance() != null &&
- x.getInstance() instanceof JCastOperation) {
- JCastOperation castOp = (JCastOperation) x.getInstance();
- if (getPossiblyUnderlyingType(castOp.getCastType()) == enumType) {
- JEnumType fromType = getEnumType(castOp.getExpr().getType());
- if (fromType != null) {
- castOpsToIgnore.push(castOp);
- }
- }
- }
- }
- return true;
- }
-
- @Override
- public boolean visit(JMethod x, Context ctx) {
- /*
- * Don't want to visit the generated getClass() method on an enum, since
- * it contains a reference to an enum's class literal that we don't want
- * to consider. Make sure this is not a user overloaded version
- * (i.e. check that it has no params).
- */
- if (getEnumType(x.getEnclosingType()) != null &&
- x.getName().equals("getClass") &&
- (x.getOriginalParamTypes() == null || x.getOriginalParamTypes().size() == 0)) {
- return false;
- }
-
- // defer to parent method on ImplicitCastAnalyzer
- return super.visit(x, ctx);
- }
-
- @Override
- public boolean visit(JMethodCall x, Context ctx) {
- /*
- * skip all calls to Enum.createValueOfMap, since they'd get falsely
- * flagged for referencing $VALUES and for implicitly upcasting an
- * array of an enum class, in the arg passing. This method is only
- * used by the enumClass$Map class that gets generated for every enum
- * class. Once ordinalization proceeds, this $Map class should be pruned.
- */
- if (x.getTarget() == enumCreateValueOfMapMethod) {
- return false;
- }
-
- /*
- * If we have a method call of Enum.ordinal(), then we want to allow a
- * cast operation from enum subclass to Enum on the instance. Other
- * optimizers have a tendency to convert things like:
- *
- * 'switch(enumObj.ordinal())' to
- * 'switch((Enum)enumObj).ordinal'
- *
- * We don't want to blacklist enumObj in that case, so we push this castOp
- * on a stack and and check it in the subsequent call to endVisit for
- * JCastOperation (above). We can't simply return false and prevent
- * the visit of the JCastOperation altogether, since we do need to visit
- * the castOperation's sub-expression.
- */
- if (x.getTarget() == enumOrdinalMethod) {
- if (x.getInstance() != null &&
- x.getInstance() instanceof JCastOperation) {
- JCastOperation castOp = (JCastOperation) x.getInstance();
- if (getPossiblyUnderlyingType(castOp.getCastType()) == enumType) {
- JEnumType fromType = getEnumType(castOp.getExpr().getType());
- if (fromType != null) {
- castOpsToIgnore.push(castOp);
- }
- }
- }
- }
-
- // ok to visit
- return true;
- }
-
- /*
- * Override for the method called from ImplicitUpcastAnalyzer,
- * which will be called for any implicit upcast.
- */
- @Override
- protected void processImplicitUpcast(JType fromType, JType destType, SourceInfo info) {
- if (fromType == nullType) {
- // handle case where a nullType is cast to an enum
- blackListIfEnum(destType, info);
- } else if (fromType == javaScriptObjectType) {
- // handle case where a javaScriptObject is cast to an enum
- blackListIfEnum(destType, info);
- } else {
- blackListIfEnumCast(fromType, destType, info);
- }
- }
-
- private void addToBlackList(JEnumType enumType, SourceInfo info) {
- ordinalizationBlackList.add(enumType);
-
- if (tracker != null) {
- tracker.addEnumNotOrdinalizedInfo(enumType.getName(), info);
- }
- }
-
- private void blackListIfEnum(JType maybeEnum, SourceInfo info) {
- JEnumType actualEnum = getEnumType(maybeEnum);
- if (actualEnum != null) {
- addToBlackList(actualEnum, info);
- }
- }
-
- private void blackListIfEnumCast(JType maybeEnum, JType destType, SourceInfo info) {
- JEnumType actualEnum = getEnumType(maybeEnum);
- JEnumType actualDestType = getEnumType(destType);
- if (actualEnum != null) {
- if (actualDestType != actualEnum) {
- addToBlackList(actualEnum, info);
- }
- return;
- }
-
- // check JArrayTypes of enums
- actualEnum = getEnumTypeFromArrayLeafType(maybeEnum);
- actualDestType = getEnumTypeFromArrayLeafType(destType);
- if (actualEnum != null) {
- if (actualDestType != actualEnum) {
- addToBlackList(actualEnum, info);
- }
- }
- }
-
- private void blackListIfEnumExpression(JExpression instance) {
- if (instance != null) {
- blackListIfEnum(instance.getType(), instance.getSourceInfo());
- }
- }
- }
-
- /**
- * A visitor which replaces enum types with an integer.
- *
- * It sub-classes TypeRemapper, which encapsulates all the locations for a
- * settable type. The overridden remap() method will be called in each
- * instance, and it will test whether the type is a candidate for replacement,
- * and if so, return the new type to set (JPrimitiveType.INT).
- *
- * Any reference to an enum field constant in an expression is replaced
- * with integer.
- *
- * This will also explicitly replace an enum's field constants with its
- * ordinal int values, and remove initialization of enum constants and the
- * $VALUES array in the clinit method for the enum.
- */
- private class ReplaceEnumTypesWithInteger extends TypeRemapper {
-
- @Override
- public boolean visit(JClassType x, Context ctx) {
- // don't waste time visiting the large ClassLiteralHolder class
- if (x == classLiteralHolderType) {
- return false;
- }
-
- // cleanup clinit method for ordinalizable enums
- if (canBeOrdinal(x)) {
- // method 0 is always the clinit
- updateClinit(x.getMethods().get(0));
- }
- return true;
- }
-
- @Override
- public boolean visit(JField x, Context ctx) {
- /*
- * Replace an enum field constant, with it's integer valued ordinal.
- */
- if (x instanceof JEnumField && canBeOrdinal(x.getEnclosingType())) {
- int ordinal = ((JEnumField) x).ordinal();
- x.setInitializer(new JDeclarationStatement(x.getSourceInfo(),
- new JFieldRef(x.getSourceInfo(), null, x,
- x.getEnclosingType()), program.getLiteralInt(ordinal)));
- }
- return true;
- }
-
- @Override
- public boolean visit(JFieldRef x, Context ctx) {
- /*
- * Replace an enum field ref with it's integer valued ordinal.
- */
- JField field = x.getField();
- if (field instanceof JEnumField && canBeOrdinal(field.getEnclosingType())) {
- int ordinal = ((JEnumField) field).ordinal();
- ctx.replaceMe(program.getLiteralInt(ordinal));
- }
- return true;
- }
-
- /*
- * Remap enum types with JPrimitiveType.INT.
- * Also handle case for arrays, replace enum leaftype with JPrimitive.INT.
- * This is an override implementation called from TypeRemapper.
- */
- @Override
- protected JType remap(JType type) {
- JType remappedType = getOrdinalizedType(type);
- if (remappedType != null) {
- return remappedType;
- } else {
- return type;
- }
- }
-
- private boolean canBeOrdinal(JType type) {
- JType uType = getPossiblyUnderlyingType(type);
- return uType instanceof JEnumType &&
- !ordinalizationBlackList.contains(uType);
- }
-
- private JType getOrdinalizedType(JType type) {
- if (canBeOrdinal(type)) {
- return JPrimitiveType.INT;
- }
-
- JType uType = getPossiblyUnderlyingType(type);
- if (uType instanceof JArrayType) {
- JArrayType aType = (JArrayType) uType;
- JType leafType = aType.getLeafType();
- if (canBeOrdinal(leafType)) {
- JArrayType newAType = program.getTypeArray(
- JPrimitiveType.INT, aType.getDims());
- return newAType.getNonNull();
- }
- }
-
- return null;
- }
-
- /*
- * Remove initialization of enum constants, and the $VALUES array, in the
- * clinit for an ordinalizable enum.
- */
- private void updateClinit(JMethod method) {
- List<JStatement> stmts = ((JMethodBody) method.getBody()).getStatements();
- Iterator<JStatement> it = stmts.iterator();
- // look for statements of the form EnumValueField = ...
- while (it.hasNext()) {
- JStatement stmt = it.next();
- if (stmt instanceof JDeclarationStatement) {
- JVariableRef ref = ((JDeclarationStatement) stmt).getVariableRef();
- if (ref instanceof JFieldRef) {
- JFieldRef enumRef = (JFieldRef) ref;
- if (enumRef.getField().getEnclosingType() == method.getEnclosingType()) {
- // see if LHS is a field ref that corresponds to the class of this method
- if (enumRef.getField() instanceof JEnumField) {
- it.remove();
- } else if (enumRef.getField().getName().equals("$VALUES")) {
- it.remove();
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * A visitor which will replace references to the ordinal field and
- * ordinal method refs with the appropropriate ordinal integer value.
- *
- * Note, this visitor must run after the ReplaceEnumTypesWithInteger visitor,
- * since it depends on detecting the locations where the enumOrdinalField or
- * enumOrdinalMethod have had their types changed to integer.
- */
- private class ReplaceOrdinalFieldAndMethodRefsWithOrdinal extends JModVisitor {
- @Override
- public boolean visit(JClassType x, Context ctx) {
- // don't waste time visiting the large ClassLiteralHolder class
- if (x == classLiteralHolderType) {
- return false;
- }
- return true;
- }
-
- @Override
- public boolean visit(JFieldRef x, Context ctx) {
- /*
- * Check field refs that refer to Enum.ordinal, but which have already
- * been ordinalized by the previous pass. This is implemented with visit
- * instead of endVisit since, in the case of an underlying cast operation,
- * we don't want to traverse the instance expression before we replace it.
- */
- if (x.getField() == enumOrdinalField) {
- if (x.getInstance() != null) {
- JType type = x.getInstance().getType();
- if (type == JPrimitiveType.INT) {
- /*
- * See if this fieldRef was converted to JPrimitiveType.INT, but
- * still points to the Enum.ordinal field. If so, replace the field
- * ref with the ordinalized int itself.
- */
- ctx.replaceMe(x.getInstance());
- } else if (x.getInstance() instanceof JCastOperation) {
- /*
- * See if this reference to Enum.ordinal is via a cast from an enum
- * sub-class, that we've already ordinalized to JPrimitiveType.INT.
- * If so, replace the whole cast operation.
- * (see JFieldRef visit method in CannotBeOrdinalAnalyzer above).
- */
- JCastOperation castOp = (JCastOperation) x.getInstance();
- if (getPossiblyUnderlyingType(castOp.getType()) == enumType) {
- if (castOp.getExpr().getType() == JPrimitiveType.INT) {
- ctx.replaceMe(castOp.getExpr());
- }
- }
- }
- }
- }
- return true;
- }
-
- @Override
- public boolean visit(JMethodCall x, Context ctx) {
- /*
- * See if this methodCall was converted to JPrimitiveType.INT, but still
- * points to the Enum.ordinal() method. If so, replace the method call with
- * the ordinal expression itself. Implement with visit (and not endVisit),
- * so we don't traverse the method call itself unnecessarily.
- */
- if (x.getTarget() == enumOrdinalMethod) {
- if (x.getInstance() != null) {
- JType type = x.getInstance().getType();
- if (type == JPrimitiveType.INT) {
- /*
- * See if this instance was converted to JPrimitiveType.INT, but still
- * points to the Enum.ordinal() method. If so, replace the method call
- * with the ordinalized int itself.
- */
- ctx.replaceMe(x.getInstance());
- } else if (x.getInstance() instanceof JCastOperation) {
- /*
- * See if this reference to Enum.ordinal() is via a cast from an enum
- * sub-class, that we've already ordinalized to JPrimitiveType.INT.
- * If so, replace the whole cast operation.
- * (see JMethodCall visit method in CannotBeOrdinalAnalyzer above).
- */
- JCastOperation castOp = (JCastOperation) x.getInstance();
- if (getPossiblyUnderlyingType(castOp.getType()) == enumType) {
- if (castOp.getExpr().getType() == JPrimitiveType.INT) {
- ctx.replaceMe(castOp.getExpr());
- }
- }
- }
- }
- }
- return true;
- }
- }
-
- private OptimizerStats execImpl() {
- OptimizerStats stats = new OptimizerStats(NAME);
-
- if (tracker != null) {
- tracker.incrementRunCount();
- tracker.maybeDumpAST(program, 0);
- }
-
- // Create black list of enum refs which can't be converted to an ordinal ref
- CannotBeOrdinalAnalyzer ordinalAnalyzer = new CannotBeOrdinalAnalyzer(program);
- ordinalAnalyzer.accept(program);
- ordinalAnalyzer.afterVisitor();
-
- if (tracker != null) {
- for (JEnumType type : enumsVisited.values()) {
- tracker.addVisited(type.getName());
- if (!ordinalizationBlackList.contains(type)) {
- tracker.addOrdinalized(type.getName());
- }
- }
- }
-
- // Bail if we don't need to do any ordinalization
- if (enumsVisited.size() == ordinalizationBlackList.size()) {
- return stats;
- }
-
- // Replace enum type refs
- ReplaceEnumTypesWithInteger replaceEnums =
- new ReplaceEnumTypesWithInteger();
- replaceEnums.accept(program);
- stats.recordModified(replaceEnums.getNumMods());
-
- if (tracker != null) {
- tracker.maybeDumpAST(program, 1);
- }
-
- // Replace enum field and method refs
- ReplaceOrdinalFieldAndMethodRefsWithOrdinal replaceOrdinalRefs =
- new ReplaceOrdinalFieldAndMethodRefsWithOrdinal();
- replaceOrdinalRefs.accept(program);
- stats.recordModified(replaceOrdinalRefs.getNumMods());
-
- if (tracker != null) {
- tracker.maybeDumpAST(program, 2);
- }
-
- return stats;
- }
-
- private JEnumType getEnumType(JType type) {
- type = getPossiblyUnderlyingType(type);
- if (type instanceof JClassType) {
- return ((JClassType) type).isEnumOrSubclass();
- }
- return null;
- }
-
- private JEnumType getEnumTypeFromArrayLeafType(JType type) {
- type = getPossiblyUnderlyingType(type);
- if (type instanceof JArrayType) {
- type = ((JArrayType) type).getLeafType();
- return getEnumType(type);
- }
- return null;
- }
-
- private JType getPossiblyUnderlyingType(JType type) {
- if (type instanceof JReferenceType) {
- return ((JReferenceType) type).getUnderlyingType();
- }
- return type;
- }
-
/**
* A simple Tracker class for compiling lists of enum classes processed by
- * this optimizer. If enabled, the results can be logged as debug output, and
+ * this optimizer. If enabled, the results can be logged as debug output, and
* the results can be tested after running with a given input.
*/
public static class Tracker {
- private final Set<String> allEnumsVisited;
private final Set<String> allEnumsOrdinalized;
- private final List<Set<String>> enumsVisitedPerPass;
- private final List<Set<String>> enumsOrdinalizedPerPass;
+ private final Set<String> allEnumsVisited;
private final Map<String, List<SourceInfo>> enumInfoMap;
+ private final List<Set<String>> enumsOrdinalizedPerPass;
+ private final List<Set<String>> enumsVisitedPerPass;
private int runCount = -1;
-
+
// use TreeSets, for nice sorted iteration for output
public Tracker() {
allEnumsVisited = new TreeSet<String>();
@@ -894,12 +117,12 @@
enumsVisitedPerPass = new ArrayList<Set<String>>();
enumsOrdinalizedPerPass = new ArrayList<Set<String>>();
enumInfoMap = new HashMap<String, List<SourceInfo>>();
-
+
// add entry for initial pass
enumsVisitedPerPass.add(new TreeSet<String>());
enumsOrdinalizedPerPass.add(new TreeSet<String>());
}
-
+
public void addEnumNotOrdinalizedInfo(String enumName, SourceInfo info) {
List<SourceInfo> infos = enumInfoMap.get(enumName);
if (infos == null) {
@@ -910,46 +133,46 @@
infos.add(info);
}
}
-
+
public void addOrdinalized(String ordinalized) {
enumsOrdinalizedPerPass.get(runCount).add(ordinalized);
allEnumsOrdinalized.add(ordinalized);
}
-
+
public void addVisited(String visited) {
enumsVisitedPerPass.get(runCount).add(visited);
allEnumsVisited.add(visited);
}
-
+
public String getInfoString(SourceInfo info) {
if (info != null) {
return info.getFileName() + ": Line " + info.getStartLine();
}
return null;
}
-
+
public int getNumOrdinalized() {
return allEnumsOrdinalized.size();
}
-
+
public int getNumVisited() {
return allEnumsVisited.size();
}
-
+
public void incrementRunCount() {
runCount++;
enumsVisitedPerPass.add(new TreeSet<String>());
enumsOrdinalizedPerPass.add(new TreeSet<String>());
}
-
+
public boolean isOrdinalized(String className) {
return allEnumsOrdinalized.contains(className);
}
-
+
public boolean isVisited(String className) {
return allEnumsVisited.contains(className);
}
-
+
public void logEnumsNotOrdinalized(TreeLogger logger, TreeLogger.Type logType) {
if (logger != null) {
boolean initialMessageLogged = false;
@@ -987,7 +210,7 @@
}
}
}
-
+
public void logEnumsOrdinalized(TreeLogger logger, TreeLogger.Type logType) {
if (logger != null && allEnumsOrdinalized.size() > 0) {
logger = logger.branch(logType, "Enums Ordinalized:");
@@ -996,7 +219,7 @@
}
}
}
-
+
public void logEnumsOrdinalizedPerPass(TreeLogger logger, TreeLogger.Type logType) {
if (logger != null) {
if (allEnumsOrdinalized.size() == 0) {
@@ -1006,8 +229,9 @@
for (Set<String> enumsOrdinalized : enumsOrdinalizedPerPass) {
pass++;
if (enumsOrdinalized.size() > 0) {
- TreeLogger subLogger = logger.branch(logType, "Pass " + pass + ": " +
- enumsOrdinalized.size() + " ordinalized");
+ TreeLogger subLogger =
+ logger.branch(logType, "Pass " + pass + ": " + enumsOrdinalized.size()
+ + " ordinalized");
for (String enumOrdinalized : enumsOrdinalized) {
subLogger.branch(logType, enumOrdinalized);
}
@@ -1015,7 +239,7 @@
}
}
}
-
+
public void logEnumsVisitedPerPass(TreeLogger logger, TreeLogger.Type logType) {
if (logger != null) {
if (allEnumsVisited.size() == 0) {
@@ -1025,8 +249,8 @@
for (Set<String> enumsVisited : enumsVisitedPerPass) {
pass++;
if (enumsVisited.size() > 0) {
- TreeLogger subLogger = logger.branch(logType, "Pass " + pass + ": " +
- enumsVisited.size() + " visited");
+ TreeLogger subLogger =
+ logger.branch(logType, "Pass " + pass + ": " + enumsVisited.size() + " visited");
for (String enumVisited : enumsVisited) {
subLogger.branch(logType, enumVisited);
}
@@ -1034,33 +258,790 @@
}
}
}
-
+
public void logResults(TreeLogger logger, TreeLogger.Type logType) {
logger = logResultsSummary(logger, logType);
logEnumsOrdinalized(logger, logType);
logEnumsNotOrdinalized(logger, logType);
}
-
+
public void logResultsDetailed(TreeLogger logger, TreeLogger.Type logType) {
logger = logResultsSummary(logger, logType);
logEnumsOrdinalizedPerPass(logger, logType);
// logEnumsVisitedPerPass(logger, logType);
logEnumsNotOrdinalized(logger, logType);
}
-
+
public TreeLogger logResultsSummary(TreeLogger logger, TreeLogger.Type logType) {
if (logger != null) {
logger = logger.branch(logType, "EnumOrdinalizer Results:");
logger.branch(logType, (runCount + 1) + " ordinalization passes completed");
- logger.branch(logType, allEnumsOrdinalized.size() + " of " +
- allEnumsVisited.size() + " ordinalized");
+ logger.branch(logType, allEnumsOrdinalized.size() + " of " + allEnumsVisited.size()
+ + " ordinalized");
return logger;
}
return null;
}
-
+
public void maybeDumpAST(JProgram program, int stage) {
AstDumper.maybeDumpAST(program, NAME + "_" + (runCount + 1) + "_" + stage);
}
- }
+ }
+
+ /**
+ * A visitor which keeps track of the enums which cannot be ordinalized. It
+ * does this by keeping track of a "black-list" for ordinals which violate the
+ * conditions for ordinalization, below.
+ *
+ * An enum cannot be ordinalized, if it: is implicitly upcast. is implicitly
+ * cast to from a nullType. is implicitly cast to or from a javaScriptObject
+ * type. is explicitly cast to another type (or vice-versa). it's class
+ * literal is used explicitly. it has an artificial rescue recorded for it.
+ * has any field referenced, except for: one of it's enum constants
+ * Enum.ordinal has any method called, except for: ordinal() Enum.ordinal()
+ * Enum() super constructor Enum.createValueOfMap()
+ *
+ * This visitor extends the ImplicitUpcastAnalyzer, which encapsulates all the
+ * conditions where implicit upcasting can occur in an AST. The rest of the
+ * logic for checking ordinalizability is encapsulated in this sub-class.
+ *
+ * It also keeps track of all enums encountered, so we can know if we need to
+ * continue with the other visitors of the optimizer after this visitor runs.
+ *
+ * We make special allowances not to check any code statements that appear
+ * within the ClassLiteralHolder class, which can contain a reference to all
+ * enum class literals in the program, even after ordinalization occurs.
+ *
+ * Also, we ignore visiting the getClass() method for any enum subclass, since
+ * it will also cause a visit to the enum's class literal, and we don't
+ * necessarily want to prevent ordinalization in that case.
+ *
+ * Special checking is needed to detect a class literal reference that occurs
+ * within a JSNI method body. We don't get a visit to JClassLiteral in that
+ * case, so we need to inspect visits to JsniFieldRef for the possibility it
+ * might be a reference to a class literal.
+ *
+ * We also skip any checking in a method call to Enum.createValueOfMap(),
+ * since this is generated for any enum class initially within the extra
+ * enumClass$Map class, and this call contains an implicit upcast in the
+ * method call args (as well as a reference to the static enumClass$VALUES
+ * field), which we want to ignore. The enumClass$Map class will not get
+ * pruned as long as the enumClass is not ordinalized, and so we need to
+ * ignore it's presence in the consideration for whether an enum class is
+ * ordinalizable.
+ */
+ private class CannotBeOrdinalAnalyzer extends ImplicitUpcastAnalyzer {
+
+ private final Stack<JCastOperation> castOpsToIgnore = new Stack<JCastOperation>();
+ private final Map<String, SourceInfo> jsniClassLiteralsInfo = new HashMap<String, SourceInfo>();
+
+ public CannotBeOrdinalAnalyzer(JProgram program) {
+ super(program);
+ }
+
+ /*
+ * After program is visited, post-process remaining tasks from accumulated
+ * data.
+ */
+ public void afterVisitor() {
+ // black-list any Jsni enum ClassLiteralsVisited
+ for (String classLiteralName : jsniClassLiteralsInfo.keySet()) {
+ JEnumType enumFromLiteral = enumsVisited.get(classLiteralName);
+ if (enumFromLiteral != null) {
+ addToBlackList(enumFromLiteral, jsniClassLiteralsInfo.get(classLiteralName));
+ }
+ }
+ }
+
+ @Override
+ public void endVisit(JCastOperation x, Context ctx) {
+ // see if we've previously marked this castOp to be exempted
+ if (!castOpsToIgnore.empty() && castOpsToIgnore.peek() == x) {
+ castOpsToIgnore.pop();
+ return;
+ }
+
+ // check for explicit cast (check both directions)
+ blackListIfEnumCast(x.getExpr().getType(), x.getCastType(), x.getSourceInfo());
+ blackListIfEnumCast(x.getCastType(), x.getExpr().getType(), x.getSourceInfo());
+ }
+
+ @Override
+ public void endVisit(JClassLiteral x, Context ctx) {
+ /*
+ * Check for references to an enum's class literal. We need to black-list
+ * classes in this case, since there could be a call to
+ * Enum.valueOf(someEnum.class,"name"), etc.
+ *
+ * Note: we won't get here for class literals that occur in the
+ * ClassLiteralHolder class, or within the getClass method of an enum
+ * class (see comments above).
+ */
+ JEnumType type = getEnumType(x.getRefType());
+ if (type != null) {
+ blackListIfEnum(type, x.getSourceInfo());
+ }
+ }
+
+ @Override
+ public void endVisit(JClassType x, Context ctx) {
+ // black-list any artificially rescued classes recorded for this class
+ List<JNode> rescues = x.getArtificialRescues();
+ if (rescues != null && rescues.size() > 0) {
+ for (JNode rescueNode : rescues) {
+ if (rescueNode instanceof JType) {
+ blackListIfEnum((JType) rescueNode, x.getSourceInfo());
+ }
+ }
+ }
+
+ // keep track of all enum classes visited
+ JEnumType maybeEnum = x.isEnumOrSubclass();
+ if (maybeEnum != null) {
+ enumsVisited.put(program.getClassLiteralName(maybeEnum), maybeEnum);
+ }
+ }
+
+ @Override
+ public void endVisit(JFieldRef x, Context ctx) {
+ // don't need to check Enum.ordinal
+ if (x.getField() == enumOrdinalField) {
+ return;
+ }
+
+ if (x.getInstance() != null) {
+ // check any instance field reference other than ordinal
+ blackListIfEnumExpression(x.getInstance());
+ } else if (x.getField().isStatic()) {
+ // check static field references
+
+ /*
+ * Need to exempt static fieldRefs to the special $VALUES array that
+ * gets generated for all enum classes, if the reference occurs within
+ * the enum class itself (such as happens in the clinit() or values()
+ * method for all enums).
+ */
+ if (x.getField().getName().equals("$VALUES")
+ && this.currentMethod.getEnclosingType() == x.getField().getEnclosingType()) {
+ if (getEnumType(x.getField().getEnclosingType()) != null) {
+ return;
+ }
+ }
+
+ /*
+ * Need to exempt static fieldRefs for enum constants themselves. Detect
+ * these as final fields, that have the same enum type as their
+ * enclosing type.
+ */
+ if (x.getField().isFinal()
+ && (x.getField().getEnclosingType() == getEnumType(x.getField().getType()))) {
+ return;
+ }
+
+ /*
+ * Check any other refs to static fields of an enum class. This includes
+ * references to $VALUES that might occur outside of the enum class
+ * itself. This can occur when a call to the values() method gets
+ * inlined, etc. Also check here for any user defined static fields.
+ */
+ blackListIfEnum(x.getField().getEnclosingType(), x.getSourceInfo());
+ }
+ }
+
+ @Override
+ public void endVisit(JMethodCall x, Context ctx) {
+ // exempt calls to certain methods on the Enum super class
+ if (x.getTarget() == enumCreateValueOfMapMethod || x.getTarget() == enumSuperConstructor
+ || x.getTarget() == enumOrdinalMethod) {
+ return;
+ }
+
+ // any other method on an enum class should cause it to be black-listed
+ if (x.getInstance() != null) {
+ blackListIfEnumExpression(x.getInstance());
+ } else if (x.getTarget().isStatic()) {
+ /*
+ * need to exempt static methodCalls for an enum class if it occurs
+ * within the enum class itself (such as in $clinit() or values())
+ */
+ if (this.currentMethod.getEnclosingType() != x.getTarget().getEnclosingType()) {
+ blackListIfEnum(x.getTarget().getEnclosingType(), x.getSourceInfo());
+ }
+ }
+
+ // defer to ImplicitUpcastAnalyzer to check method call args & params
+ super.endVisit(x, ctx);
+ }
+
+ @Override
+ public void endVisit(JsniFieldRef x, Context ctx) {
+ /*
+ * Can't do the same thing as for JFieldRef, all JsniFieldRefs are cast to
+ * JavaScriptObjects. Need to check both the field type and the type of
+ * the instance or enclosing class referencing the field.
+ */
+
+ // check the field type
+ blackListIfEnum(x.getField().getType(), x.getSourceInfo());
+
+ // check the referrer
+ if (x.getInstance() != null) {
+ blackListIfEnumExpression(x.getInstance());
+ } else {
+ blackListIfEnum(x.getField().getEnclosingType(), x.getSourceInfo());
+ }
+
+ /*
+ * need to also check JsniFieldRef's for a possible reference to a class
+ * literal, since we don't get a visit to JClassLiteral when it occurs
+ * within Jsni (shouldn't it?).
+ */
+ if (x.getField().getEnclosingType() == classLiteralHolderType) {
+ // see if it has an initializer with a method call to "createForEnum"
+ JExpression initializer = x.getField().getInitializer();
+ if (initializer instanceof JMethodCall) {
+ if (((JMethodCall) initializer).getTarget() == classCreateForEnumMethod) {
+ jsniClassLiteralsInfo.put(x.getField().getName(), x.getSourceInfo());
+ }
+ }
+ }
+ }
+
+ @Override
+ public void endVisit(JsniMethodRef x, Context ctx) {
+ // no enum methods are exempted if occur within a JsniMethodRef
+ if (x.getInstance() != null) {
+ blackListIfEnumExpression(x.getInstance());
+ } else if (x.getTarget().isStatic()) {
+ /*
+ * need to exempt static methodCalls for an enum class if it occurs
+ * within the enum class itself (such as in $clinit() or values())
+ */
+ if (this.currentMethod.getEnclosingType() != x.getTarget().getEnclosingType()) {
+ blackListIfEnum(x.getTarget().getEnclosingType(), x.getSourceInfo());
+ }
+ }
+
+ // defer to ImplicitUpcastAnalyzer to check method call args & params
+ super.endVisit(x, ctx);
+ }
+
+ @Override
+ public boolean visit(JClassType x, Context ctx) {
+ /*
+ * Don't want to visit the large ClassLiteralHolder class, it doesn't
+ * contain references to actual usage of enum class literals. It's also a
+ * time savings to not traverse this class.
+ */
+ if (x == classLiteralHolderType) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(JFieldRef x, Context ctx) {
+ /*
+ * If we have a field ref of Enum.ordinal, then we want to allow a cast
+ * operation from enum subclass to Enum on the instance. Other optimizers
+ * have a tendency to convert things like:
+ *
+ * 'switch(enumObj)' to 'switch((Enum)enumObj).ordinal'
+ *
+ * We don't want to blacklist enumObj in that case, so we push this castOp
+ * on a stack and check it in the subsequent call to endVisit for
+ * JCastOperation. We can't simply return false and prevent the visit of
+ * the JCastOperation altogether, since we do need to visit the
+ * JCastOperation's sub-expression. Since the sub-expression could
+ * potentially also contain similar cast operations, we use a stack to
+ * keep track of 'castOpsToIgnore'.
+ */
+ if (x.getField() == enumOrdinalField) {
+ if (x.getInstance() != null && x.getInstance() instanceof JCastOperation) {
+ JCastOperation castOp = (JCastOperation) x.getInstance();
+ if (getPossiblyUnderlyingType(castOp.getCastType()) == enumType) {
+ JEnumType fromType = getEnumType(castOp.getExpr().getType());
+ if (fromType != null) {
+ castOpsToIgnore.push(castOp);
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(JMethod x, Context ctx) {
+ /*
+ * Don't want to visit the generated getClass() method on an enum, since
+ * it contains a reference to an enum's class literal that we don't want
+ * to consider. Make sure this is not a user overloaded version (i.e.
+ * check that it has no params).
+ */
+ if (getEnumType(x.getEnclosingType()) != null && x.getName().equals("getClass")
+ && (x.getOriginalParamTypes() == null || x.getOriginalParamTypes().size() == 0)) {
+ return false;
+ }
+
+ // defer to parent method on ImplicitCastAnalyzer
+ return super.visit(x, ctx);
+ }
+
+ @Override
+ public boolean visit(JMethodCall x, Context ctx) {
+ /*
+ * skip all calls to Enum.createValueOfMap, since they'd get falsely
+ * flagged for referencing $VALUES and for implicitly upcasting an array
+ * of an enum class, in the arg passing. This method is only used by the
+ * enumClass$Map class that gets generated for every enum class. Once
+ * ordinalization proceeds, this $Map class should be pruned.
+ */
+ if (x.getTarget() == enumCreateValueOfMapMethod) {
+ return false;
+ }
+
+ /*
+ * If we have a method call of Enum.ordinal(), then we want to allow a
+ * cast operation from enum subclass to Enum on the instance. Other
+ * optimizers have a tendency to convert things like:
+ *
+ * 'switch(enumObj.ordinal())' to 'switch((Enum)enumObj).ordinal'
+ *
+ * We don't want to blacklist enumObj in that case, so we push this castOp
+ * on a stack and and check it in the subsequent call to endVisit for
+ * JCastOperation (above). We can't simply return false and prevent the
+ * visit of the JCastOperation altogether, since we do need to visit the
+ * castOperation's sub-expression.
+ */
+ if (x.getTarget() == enumOrdinalMethod) {
+ if (x.getInstance() != null && x.getInstance() instanceof JCastOperation) {
+ JCastOperation castOp = (JCastOperation) x.getInstance();
+ if (getPossiblyUnderlyingType(castOp.getCastType()) == enumType) {
+ JEnumType fromType = getEnumType(castOp.getExpr().getType());
+ if (fromType != null) {
+ castOpsToIgnore.push(castOp);
+ }
+ }
+ }
+ }
+
+ // ok to visit
+ return true;
+ }
+
+ /*
+ * Override for the method called from ImplicitUpcastAnalyzer, which will be
+ * called for any implicit upcast.
+ */
+ @Override
+ protected void processImplicitUpcast(JType fromType, JType destType, SourceInfo info) {
+ if (fromType == nullType) {
+ // handle case where a nullType is cast to an enum
+ blackListIfEnum(destType, info);
+ } else if (fromType == javaScriptObjectType) {
+ // handle case where a javaScriptObject is cast to an enum
+ blackListIfEnum(destType, info);
+ } else {
+ blackListIfEnumCast(fromType, destType, info);
+ }
+ }
+
+ private void addToBlackList(JEnumType enumType, SourceInfo info) {
+ ordinalizationBlackList.add(enumType);
+
+ if (tracker != null) {
+ tracker.addEnumNotOrdinalizedInfo(enumType.getName(), info);
+ }
+ }
+
+ private void blackListIfEnum(JType maybeEnum, SourceInfo info) {
+ JEnumType actualEnum = getEnumType(maybeEnum);
+ if (actualEnum != null) {
+ addToBlackList(actualEnum, info);
+ }
+ }
+
+ private void blackListIfEnumCast(JType maybeEnum, JType destType, SourceInfo info) {
+ JEnumType actualEnum = getEnumType(maybeEnum);
+ JEnumType actualDestType = getEnumType(destType);
+ if (actualEnum != null) {
+ if (actualDestType != actualEnum) {
+ addToBlackList(actualEnum, info);
+ }
+ return;
+ }
+
+ // check JArrayTypes of enums
+ actualEnum = getEnumTypeFromArrayLeafType(maybeEnum);
+ actualDestType = getEnumTypeFromArrayLeafType(destType);
+ if (actualEnum != null) {
+ if (actualDestType != actualEnum) {
+ addToBlackList(actualEnum, info);
+ }
+ }
+ }
+
+ private void blackListIfEnumExpression(JExpression instance) {
+ if (instance != null) {
+ blackListIfEnum(instance.getType(), instance.getSourceInfo());
+ }
+ }
+ }
+ /**
+ * A visitor which replaces enum types with an integer.
+ *
+ * It sub-classes TypeRemapper, which encapsulates all the locations for a
+ * settable type. The overridden remap() method will be called in each
+ * instance, and it will test whether the type is a candidate for replacement,
+ * and if so, return the new type to set (JPrimitiveType.INT).
+ *
+ * Any reference to an enum field constant in an expression is replaced with
+ * integer.
+ *
+ * This will also explicitly replace an enum's field constants with its
+ * ordinal int values, and remove initialization of enum constants and the
+ * $VALUES array in the clinit method for the enum.
+ */
+ private class ReplaceEnumTypesWithInteger extends TypeRemapper {
+
+ @Override
+ public boolean visit(JClassType x, Context ctx) {
+ // don't waste time visiting the large ClassLiteralHolder class
+ if (x == classLiteralHolderType) {
+ return false;
+ }
+
+ // cleanup clinit method for ordinalizable enums
+ if (canBeOrdinal(x)) {
+ // method 0 is always the clinit
+ updateClinit(x.getMethods().get(0));
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(JField x, Context ctx) {
+ /*
+ * Replace an enum field constant, with it's integer valued ordinal.
+ */
+ if (x instanceof JEnumField && canBeOrdinal(x.getEnclosingType())) {
+ int ordinal = ((JEnumField) x).ordinal();
+ x.setInitializer(new JDeclarationStatement(x.getSourceInfo(), new JFieldRef(x
+ .getSourceInfo(), null, x, x.getEnclosingType()), program.getLiteralInt(ordinal)));
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(JFieldRef x, Context ctx) {
+ /*
+ * Replace an enum field ref with it's integer valued ordinal.
+ */
+ JField field = x.getField();
+ if (field instanceof JEnumField && canBeOrdinal(field.getEnclosingType())) {
+ int ordinal = ((JEnumField) field).ordinal();
+ ctx.replaceMe(program.getLiteralInt(ordinal));
+ }
+ return true;
+ }
+
+ /*
+ * Remap enum types with JPrimitiveType.INT. Also handle case for arrays,
+ * replace enum leaftype with JPrimitive.INT. This is an override
+ * implementation called from TypeRemapper.
+ */
+ @Override
+ protected JType remap(JType type) {
+ JType remappedType = getOrdinalizedType(type);
+ if (remappedType != null) {
+ return remappedType;
+ } else {
+ return type;
+ }
+ }
+
+ private boolean canBeOrdinal(JType type) {
+ JType uType = getPossiblyUnderlyingType(type);
+ return uType instanceof JEnumType && !ordinalizationBlackList.contains(uType);
+ }
+
+ private JType getOrdinalizedType(JType type) {
+ if (canBeOrdinal(type)) {
+ return JPrimitiveType.INT;
+ }
+
+ JType uType = getPossiblyUnderlyingType(type);
+ if (uType instanceof JArrayType) {
+ JArrayType aType = (JArrayType) uType;
+ JType leafType = aType.getLeafType();
+ if (canBeOrdinal(leafType)) {
+ JArrayType newAType = program.getTypeArray(JPrimitiveType.INT, aType.getDims());
+ return newAType.getNonNull();
+ }
+ }
+
+ return null;
+ }
+
+ /*
+ * Remove initialization of enum constants, and the $VALUES array, in the
+ * clinit for an ordinalizable enum.
+ */
+ private void updateClinit(JMethod method) {
+ List<JStatement> stmts = ((JMethodBody) method.getBody()).getStatements();
+ Iterator<JStatement> it = stmts.iterator();
+ // look for statements of the form EnumValueField = ...
+ while (it.hasNext()) {
+ JStatement stmt = it.next();
+ if (stmt instanceof JDeclarationStatement) {
+ JVariableRef ref = ((JDeclarationStatement) stmt).getVariableRef();
+ if (ref instanceof JFieldRef) {
+ JFieldRef enumRef = (JFieldRef) ref;
+ if (enumRef.getField().getEnclosingType() == method.getEnclosingType()) {
+ // see if LHS is a field ref that corresponds to the class of this
+ // method
+ if (enumRef.getField() instanceof JEnumField) {
+ it.remove();
+ } else if (enumRef.getField().getName().equals("$VALUES")) {
+ it.remove();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * A visitor which will replace references to the ordinal field and ordinal
+ * method refs with the appropropriate ordinal integer value.
+ *
+ * Note, this visitor must run after the ReplaceEnumTypesWithInteger visitor,
+ * since it depends on detecting the locations where the enumOrdinalField or
+ * enumOrdinalMethod have had their types changed to integer.
+ */
+ private class ReplaceOrdinalFieldAndMethodRefsWithOrdinal extends JModVisitor {
+ @Override
+ public boolean visit(JClassType x, Context ctx) {
+ // don't waste time visiting the large ClassLiteralHolder class
+ if (x == classLiteralHolderType) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(JFieldRef x, Context ctx) {
+ /*
+ * Check field refs that refer to Enum.ordinal, but which have already
+ * been ordinalized by the previous pass. This is implemented with visit
+ * instead of endVisit since, in the case of an underlying cast operation,
+ * we don't want to traverse the instance expression before we replace it.
+ */
+ if (x.getField() == enumOrdinalField) {
+ if (x.getInstance() != null) {
+ JType type = x.getInstance().getType();
+ if (type == JPrimitiveType.INT) {
+ /*
+ * See if this fieldRef was converted to JPrimitiveType.INT, but
+ * still points to the Enum.ordinal field. If so, replace the field
+ * ref with the ordinalized int itself.
+ */
+ ctx.replaceMe(x.getInstance());
+ } else if (x.getInstance() instanceof JCastOperation) {
+ /*
+ * See if this reference to Enum.ordinal is via a cast from an enum
+ * sub-class, that we've already ordinalized to JPrimitiveType.INT.
+ * If so, replace the whole cast operation. (see JFieldRef visit
+ * method in CannotBeOrdinalAnalyzer above).
+ */
+ JCastOperation castOp = (JCastOperation) x.getInstance();
+ if (getPossiblyUnderlyingType(castOp.getType()) == enumType) {
+ if (castOp.getExpr().getType() == JPrimitiveType.INT) {
+ ctx.replaceMe(castOp.getExpr());
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(JMethodCall x, Context ctx) {
+ /*
+ * See if this methodCall was converted to JPrimitiveType.INT, but still
+ * points to the Enum.ordinal() method. If so, replace the method call
+ * with the ordinal expression itself. Implement with visit (and not
+ * endVisit), so we don't traverse the method call itself unnecessarily.
+ */
+ if (x.getTarget() == enumOrdinalMethod) {
+ if (x.getInstance() != null) {
+ JType type = x.getInstance().getType();
+ if (type == JPrimitiveType.INT) {
+ /*
+ * See if this instance was converted to JPrimitiveType.INT, but
+ * still points to the Enum.ordinal() method. If so, replace the
+ * method call with the ordinalized int itself.
+ */
+ ctx.replaceMe(x.getInstance());
+ } else if (x.getInstance() instanceof JCastOperation) {
+ /*
+ * See if this reference to Enum.ordinal() is via a cast from an
+ * enum sub-class, that we've already ordinalized to
+ * JPrimitiveType.INT. If so, replace the whole cast operation. (see
+ * JMethodCall visit method in CannotBeOrdinalAnalyzer above).
+ */
+ JCastOperation castOp = (JCastOperation) x.getInstance();
+ if (getPossiblyUnderlyingType(castOp.getType()) == enumType) {
+ if (castOp.getExpr().getType() == JPrimitiveType.INT) {
+ ctx.replaceMe(castOp.getExpr());
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+ }
+
+ public static final String NAME = EnumOrdinalizer.class.getSimpleName();
+
+ private static Tracker tracker = null;
+
+ private static boolean trackerEnabled =
+ (System.getProperty("gwt.enableEnumOrdinalizerTracking") != null);
+
+ public static void enableTracker() {
+ trackerEnabled = true;
+ }
+
+ public static OptimizerStats exec(JProgram program) {
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
+
+ startTracker();
+ OptimizerStats stats = new EnumOrdinalizer(program).execImpl();
+ optimizeEvent.end("didChange", "" + stats.didChange());
+ return stats;
+ }
+
+ public static Tracker getTracker() {
+ return tracker;
+ }
+
+ public static void resetTracker() {
+ if (tracker != null) {
+ tracker = null;
+ startTracker();
+ }
+ }
+
+ private static void startTracker() {
+ if (trackerEnabled && tracker == null) {
+ tracker = new Tracker();
+ }
+ }
+
+ private final JMethod classCreateForEnumMethod;
+ private final JType classLiteralHolderType;
+ private final JMethod enumCreateValueOfMapMethod;
+ private final JField enumOrdinalField;
+ private final JMethod enumOrdinalMethod;
+ private final JMethod enumSuperConstructor;
+ private final Map<String, JEnumType> enumsVisited = new HashMap<String, JEnumType>();
+ private final JType enumType;
+
+ private final JType javaScriptObjectType;
+
+ private final JType nullType;
+
+ private final Set<JEnumType> ordinalizationBlackList = new HashSet<JEnumType>();
+
+ private final JProgram program;
+
+ public EnumOrdinalizer(JProgram program) {
+ this.program = program;
+ this.classLiteralHolderType = program.getIndexedType("ClassLiteralHolder");
+ this.nullType = program.getTypeNull();
+ this.javaScriptObjectType = program.getJavaScriptObject();
+ this.enumType = program.getIndexedType("Enum");
+ this.enumOrdinalField = program.getIndexedField("Enum.ordinal");
+ this.classCreateForEnumMethod = program.getIndexedMethod("Class.createForEnum");
+ this.enumCreateValueOfMapMethod = program.getIndexedMethod("Enum.createValueOfMap");
+ this.enumOrdinalMethod = program.getIndexedMethod("Enum.ordinal");
+ this.enumSuperConstructor = program.getIndexedMethod("Enum.Enum");
+ }
+
+ private OptimizerStats execImpl() {
+ OptimizerStats stats = new OptimizerStats(NAME);
+
+ if (tracker != null) {
+ tracker.incrementRunCount();
+ tracker.maybeDumpAST(program, 0);
+ }
+
+ // Create black list of enum refs which can't be converted to an ordinal ref
+ CannotBeOrdinalAnalyzer ordinalAnalyzer = new CannotBeOrdinalAnalyzer(program);
+ ordinalAnalyzer.accept(program);
+ ordinalAnalyzer.afterVisitor();
+
+ if (tracker != null) {
+ for (JEnumType type : enumsVisited.values()) {
+ tracker.addVisited(type.getName());
+ if (!ordinalizationBlackList.contains(type)) {
+ tracker.addOrdinalized(type.getName());
+ }
+ }
+ }
+
+ // Bail if we don't need to do any ordinalization
+ if (enumsVisited.size() == ordinalizationBlackList.size()) {
+ return stats;
+ }
+
+ // Replace enum type refs
+ ReplaceEnumTypesWithInteger replaceEnums = new ReplaceEnumTypesWithInteger();
+ replaceEnums.accept(program);
+ stats.recordModified(replaceEnums.getNumMods());
+
+ if (tracker != null) {
+ tracker.maybeDumpAST(program, 1);
+ }
+
+ // Replace enum field and method refs
+ ReplaceOrdinalFieldAndMethodRefsWithOrdinal replaceOrdinalRefs =
+ new ReplaceOrdinalFieldAndMethodRefsWithOrdinal();
+ replaceOrdinalRefs.accept(program);
+ stats.recordModified(replaceOrdinalRefs.getNumMods());
+
+ if (tracker != null) {
+ tracker.maybeDumpAST(program, 2);
+ }
+
+ return stats;
+ }
+
+ private JEnumType getEnumType(JType type) {
+ type = getPossiblyUnderlyingType(type);
+ if (type instanceof JClassType) {
+ return ((JClassType) type).isEnumOrSubclass();
+ }
+ return null;
+ }
+
+ private JEnumType getEnumTypeFromArrayLeafType(JType type) {
+ type = getPossiblyUnderlyingType(type);
+ if (type instanceof JArrayType) {
+ type = ((JArrayType) type).getLeafType();
+ return getEnumType(type);
+ }
+ return null;
+ }
+
+ private JType getPossiblyUnderlyingType(JType type) {
+ if (type instanceof JReferenceType) {
+ return ((JReferenceType) type).getUnderlyingType();
+ }
+ return type;
+ }
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/EqualityNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/EqualityNormalizer.java
index fdff227..366e2fe 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/EqualityNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/EqualityNormalizer.java
@@ -32,8 +32,8 @@
* Rewrite Java <code>==</code> so that it will execute correctly in JavaScript.
* After this pass, Java's <code>==</code> is considered equivalent to
* JavaScript's <code>===</code>.
- *</p>
- *<p>
+ * </p>
+ * <p>
* Whenever possible, a Java <code>==</code> is replaced by a JavaScript
* <code>==</code>. This is shorter than <code>===</code>, and it avoids any
* complication due to GWT treating both <code>null</code> and
@@ -96,8 +96,8 @@
rhs = maskUndefined(rhs);
}
- JBinaryOperation binOp = new JBinaryOperation(x.getSourceInfo(),
- x.getType(), x.getOp(), lhs, rhs);
+ JBinaryOperation binOp =
+ new JBinaryOperation(x.getSourceInfo(), x.getType(), x.getOp(), lhs, rhs);
ctx.replaceMe(binOp);
break;
}
@@ -118,8 +118,7 @@
methodName = "Cast.isNotNull";
}
JMethod isNullMethod = program.getIndexedMethod(methodName);
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null,
- isNullMethod);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, isNullMethod);
call.addArg(lhsNullLit ? rhs : lhs);
ctx.replaceMe(call);
} else {
@@ -131,8 +130,7 @@
methodName = "Cast.jsNotEquals";
}
JMethod eqMethod = program.getIndexedMethod(methodName);
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null,
- eqMethod);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, eqMethod);
call.addArgs(lhs, rhs);
ctx.replaceMe(call);
}
@@ -158,8 +156,7 @@
assert ((JReferenceType) lhs.getType()).canBeNull();
JMethod maskMethod = program.getIndexedMethod("Cast.maskUndefined");
- JMethodCall lhsCall = new JMethodCall(lhs.getSourceInfo(), null,
- maskMethod, lhs.getType());
+ JMethodCall lhsCall = new JMethodCall(lhs.getSourceInfo(), null, maskMethod, lhs.getType());
lhsCall.addArg(lhs);
return lhsCall;
}
@@ -187,7 +184,7 @@
* A map of the combinations where each comparison strategy should be used.
*/
private static int[][] COMPARISON_STRAT = {
- // ..U..S.!S..N
+ // ..U..S.!S..N
{1, 1, 1, 0,}, // UNKNOWN
{1, 0, 1, 0,}, // STRING
{1, 1, 0, 0,}, // NOTSTRING
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ExpressionAnalyzer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ExpressionAnalyzer.java
index f849c57..2b17399 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ExpressionAnalyzer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ExpressionAnalyzer.java
@@ -100,7 +100,7 @@
accessesField = true;
// Can throw an NPE when the array instance is null at runtime.
JReferenceType refType = (JReferenceType) x.getInstance().getType();
- canThrowException = refType.canBeNull();
+ canThrowException = refType.canBeNull();
}
@Override
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/Finalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/Finalizer.java
index a8e8087..715e5a5 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/Finalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/Finalizer.java
@@ -1,12 +1,12 @@
/*
* Copyright 2007 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -49,12 +49,10 @@
* optimize.
*/
public class Finalizer {
- private static final String NAME = Finalizer.class.getSimpleName();
-
/**
* Any items that weren't marked during MarkVisitor can be set final.
- *
- * Open question: What does it mean if an interface/abstract method becomes
+ *
+ * Open question: What does it mean if an interface/abstract method becomes
* final? Is this possible after Pruning? I guess it means that someone tried
* to make a call to method that wasn't actually implemented anywhere in the
* program. But if it wasn't implemented, then the enclosing class should have
@@ -125,6 +123,7 @@
madeChanges();
}
}
+
/**
* Find all items that ARE overriden/subclassed/reassigned.
*/
@@ -198,9 +197,10 @@
}
}
+ private static final String NAME = Finalizer.class.getSimpleName();
+
public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(
- CompilerEventType.OPTIMIZE, "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new Finalizer().execImpl(program);
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
@@ -218,11 +218,10 @@
private OptimizerStats execImpl(JProgram program) {
MarkVisitor marker = new MarkVisitor();
marker.accept(program);
-
+
FinalizeVisitor finalizer = new FinalizeVisitor();
finalizer.accept(program);
- return new OptimizerStats(NAME).recordModified(
- finalizer.getNumMods());
+ return new OptimizerStats(NAME).recordModified(finalizer.getNumMods());
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/FixAssignmentToUnbox.java b/dev/core/src/com/google/gwt/dev/jjs/impl/FixAssignmentToUnbox.java
index d784956..82f7018 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/FixAssignmentToUnbox.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/FixAssignmentToUnbox.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -30,15 +30,15 @@
import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event;
/**
- * Most autoboxing is handled by {@link GenerateJavaAST}. The only cases it
- * does not handle are <code>++</code>, <code>--</code>, and compound
- * assignment operations (<code>+=</code>, etc.) when applied to a boxed
- * type. This class fixes such cases in two steps. First, an internal subclass
- * of {@link CompoundAssignmentNormalizer} simplifies such expressions to a
- * simple assignment expression. Second, this visitor replaces an assignment to
- * an unboxing method (<code>unbox(x) = unbox(x) + 1</code>) with an
- * assignment to the underlying box (<code>x = box(unbox(x) + 1)</code>).
- *
+ * Most autoboxing is handled by {@link GenerateJavaAST}. The only cases it does
+ * not handle are <code>++</code>, <code>--</code>, and compound assignment
+ * operations (<code>+=</code>, etc.) when applied to a boxed type. This class
+ * fixes such cases in two steps. First, an internal subclass of
+ * {@link CompoundAssignmentNormalizer} simplifies such expressions to a simple
+ * assignment expression. Second, this visitor replaces an assignment to an
+ * unboxing method (<code>unbox(x) = unbox(x) + 1</code>) with an assignment to
+ * the underlying box (<code>x = box(unbox(x) + 1)</code>).
+ *
* <p>
* Update: GenerateJavaAST can also leave invalid AST structures of the form
* <code>(Foo) x = foo</code> due to the way generics are handled. This can
@@ -50,8 +50,7 @@
/**
* Normalize compound assignments where the lhs is an unbox operation.
*/
- private static class CompoundAssignmentToUnboxNormalizer extends
- CompoundAssignmentNormalizer {
+ private static class CompoundAssignmentToUnboxNormalizer extends CompoundAssignmentNormalizer {
private final AutoboxUtils autoboxUtils;
protected CompoundAssignmentToUnboxNormalizer(JProgram program) {
@@ -118,8 +117,8 @@
// unbox(x) = foo -> x = box(foo)
JClassType boxedType = (JClassType) boxed.getType();
- ctx.replaceMe(new JBinaryOperation(x.getSourceInfo(), boxedType,
- JBinaryOperator.ASG, boxed, autoboxUtils.box(x.getRhs(), boxedType)));
+ ctx.replaceMe(new JBinaryOperation(x.getSourceInfo(), boxedType, JBinaryOperator.ASG, boxed,
+ autoboxUtils.box(x.getRhs(), boxedType)));
return;
}
@@ -127,8 +126,9 @@
// Assignment-to-cast-operation, e.g.
// (Foo) x = foo -> x = foo
JCastOperation cast = (JCastOperation) lhs;
- JBinaryOperation newAsg = new JBinaryOperation(x.getSourceInfo(),
- x.getType(), JBinaryOperator.ASG, cast.getExpr(), x.getRhs());
+ JBinaryOperation newAsg =
+ new JBinaryOperation(x.getSourceInfo(), x.getType(), JBinaryOperator.ASG, cast.getExpr(),
+ x.getRhs());
ctx.replaceMe(newAsg);
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentExtractor.java b/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentExtractor.java
index bcc62f0..72cbd99 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentExtractor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentExtractor.java
@@ -62,6 +62,10 @@
this.cfa = cfa;
}
+ public boolean isLive(JDeclaredType type) {
+ return cfa.getInstantiatedTypes().contains(type);
+ }
+
public boolean isLive(JField field) {
return cfa.getLiveFieldsAndMethods().contains(field)
|| cfa.getFieldsWritten().contains(field);
@@ -71,10 +75,6 @@
return cfa.getLiveFieldsAndMethods().contains(method);
}
- public boolean isLive(JDeclaredType type) {
- return cfa.getInstantiatedTypes().contains(type);
- }
-
public boolean isLive(String string) {
return cfa.getLiveStrings().contains(string);
}
@@ -109,12 +109,12 @@
* </ul>
*/
public static interface LivenessPredicate {
+ boolean isLive(JDeclaredType type);
+
boolean isLive(JField field);
boolean isLive(JMethod method);
- boolean isLive(JDeclaredType type);
-
boolean isLive(String literal);
/**
@@ -131,6 +131,10 @@
* A {@link LivenessPredicate} where nothing is alive.
*/
public static class NothingAlivePredicate implements LivenessPredicate {
+ public boolean isLive(JDeclaredType type) {
+ return false;
+ }
+
public boolean isLive(JField field) {
return false;
}
@@ -139,10 +143,6 @@
return false;
}
- public boolean isLive(JDeclaredType type) {
- return false;
- }
-
public boolean isLive(String string) {
return false;
}
@@ -201,12 +201,10 @@
private StatementLogger statementLogger = new NullStatementLogger();
public FragmentExtractor(JavaAndJavaScript javaAndJavaScript) {
- this(javaAndJavaScript.jprogram, javaAndJavaScript.jsprogram,
- javaAndJavaScript.map);
+ this(javaAndJavaScript.jprogram, javaAndJavaScript.jsprogram, javaAndJavaScript.map);
}
- public FragmentExtractor(JProgram jprogram, JsProgram jsprogram,
- JavaToJavaScriptMap map) {
+ public FragmentExtractor(JProgram jprogram, JsProgram jsprogram, JavaToJavaScriptMap map) {
this.jprogram = jprogram;
this.jsprogram = jsprogram;
this.map = map;
@@ -218,8 +216,7 @@
* Add direct calls to the entry methods of the specified entry number.
*/
public List<JsStatement> createCallsToEntryMethods(int splitPoint) {
- List<JsStatement> callStats = new ArrayList<JsStatement>(
- jprogram.entryMethods.size());
+ List<JsStatement> callStats = new ArrayList<JsStatement>(jprogram.entryMethods.size());
for (JMethod entryMethod : jprogram.entryMethods.get(splitPoint)) {
JsName name = map.nameForMethod(entryMethod);
assert name != null;
@@ -237,7 +234,8 @@
* .
*/
public List<JsStatement> createCallToLeftoversFragmentHasLoaded() {
- JMethod loadedMethod = jprogram.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded");
+ JMethod loadedMethod =
+ jprogram.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded");
JsName loadedMethodName = map.nameForMethod(loadedMethod);
SourceInfo sourceInfo = jsprogram.getSourceInfo();
JsInvocation call = new JsInvocation(sourceInfo);
@@ -253,8 +251,7 @@
* ensure that <code>livenessPredicate</code> includes strictly more live code
* than <code>alreadyLoadedPredicate</code>.
*/
- public List<JsStatement> extractStatements(
- LivenessPredicate livenessPredicate,
+ public List<JsStatement> extractStatements(LivenessPredicate livenessPredicate,
LivenessPredicate alreadyLoadedPredicate) {
List<JsStatement> extractedStats = new ArrayList<JsStatement>();
@@ -272,10 +269,10 @@
boolean keepIt;
JClassType vtableTypeAssigned = vtableTypeAssigned(stat);
- if (vtableTypeAssigned != null
- && livenessPredicate.isLive(vtableTypeAssigned)) {
- JsExprStmt result = extractPrototypeSetup(livenessPredicate,
- alreadyLoadedPredicate, stat, vtableTypeAssigned);
+ if (vtableTypeAssigned != null && livenessPredicate.isLive(vtableTypeAssigned)) {
+ JsExprStmt result =
+ extractPrototypeSetup(livenessPredicate, alreadyLoadedPredicate, stat,
+ vtableTypeAssigned);
if (result != null) {
stat = result;
keepIt = true;
@@ -283,12 +280,10 @@
keepIt = false;
}
} else if (containsRemovableVars(stat)) {
- stat = removeSomeVars((JsVars) stat, livenessPredicate,
- alreadyLoadedPredicate);
+ stat = removeSomeVars((JsVars) stat, livenessPredicate, alreadyLoadedPredicate);
keepIt = !(stat instanceof JsEmpty);
} else {
- keepIt = isLive(stat, livenessPredicate)
- && !isLive(stat, alreadyLoadedPredicate);
+ keepIt = isLive(stat, livenessPredicate) && !isLive(stat, alreadyLoadedPredicate);
}
statementLogger.logStatement(stat, keepIt);
@@ -340,7 +335,8 @@
entryMethodNames.add(name);
}
- JMethod leftoverFragmentLoaded = jprogram.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded");
+ JMethod leftoverFragmentLoaded =
+ jprogram.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded");
if (leftoverFragmentLoaded != null) {
JsName name = map.nameForMethod(leftoverFragmentLoaded);
assert name != null;
@@ -375,8 +371,7 @@
* subset of the type's liveness. We essentially have to break up the
* prototype chain according to exactly what's newly live.
*/
- private JsExprStmt extractPrototypeSetup(
- final LivenessPredicate livenessPredicate,
+ private JsExprStmt extractPrototypeSetup(final LivenessPredicate livenessPredicate,
final LivenessPredicate alreadyLoadedPredicate, JsStatement stat,
final JClassType vtableTypeAssigned) {
final boolean[] anyLiveCode = new boolean[1];
@@ -402,8 +397,7 @@
JsNameRef ctorRef = (JsNameRef) lhs.getQualifier();
JConstructor ctor = (JConstructor) map.nameToMethod(ctorRef.getName());
assert ctor != null;
- if (livenessPredicate.isLive(ctor)
- && !alreadyLoadedPredicate.isLive(ctor)) {
+ if (livenessPredicate.isLive(ctor) && !alreadyLoadedPredicate.isLive(ctor)) {
anyLiveCode[0] = true;
} else {
stack.push(rhs);
@@ -411,8 +405,7 @@
}
}
- JsBinaryOperation toReturn = new JsBinaryOperation(x.getSourceInfo(),
- x.getOperator());
+ JsBinaryOperation toReturn = new JsBinaryOperation(x.getSourceInfo(), x.getOperator());
toReturn.setArg2(rhs);
toReturn.setArg1(lhs);
stack.push(toReturn);
@@ -433,8 +426,7 @@
JsExpression expr = ((JsExprStmt) stat).getExpression();
if (expr instanceof JsInvocation) {
JsInvocation inv = (JsInvocation) expr;
- if (inv.getArguments().isEmpty()
- && (inv.getQualifier() instanceof JsNameRef)) {
+ if (inv.getArguments().isEmpty() && (inv.getQualifier() instanceof JsNameRef)) {
JsNameRef calleeRef = (JsNameRef) inv.getQualifier();
if (calleeRef.getQualifier() == null) {
return entryMethodNames.contains(calleeRef.getName());
@@ -464,8 +456,7 @@
}
// The method is live. Check that its enclosing type is instantiable.
// TODO(spoon): this check should not be needed once the CFA is updated
- return !meth.needsVtable()
- || livenessPredicate.isLive(meth.getEnclosingType());
+ return !meth.needsVtable() || livenessPredicate.isLive(meth.getEnclosingType());
}
return livenessPredicate.miscellaneousStatementsAreLive();
@@ -507,14 +498,12 @@
* <code>currentLivenessPredicate</code> but not by
* <code>alreadyLoadedPredicate</code>.
*/
- private JsStatement removeSomeVars(JsVars stat,
- LivenessPredicate currentLivenessPredicate,
+ private JsStatement removeSomeVars(JsVars stat, LivenessPredicate currentLivenessPredicate,
LivenessPredicate alreadyLoadedPredicate) {
JsVars newVars = new JsVars(stat.getSourceInfo());
for (JsVar var : stat) {
- if (isLive(var, currentLivenessPredicate)
- && !isLive(var, alreadyLoadedPredicate)) {
+ if (isLive(var, currentLivenessPredicate) && !isLive(var, alreadyLoadedPredicate)) {
newVars.add(var);
}
}
@@ -545,25 +534,23 @@
* function for <code>vtableType</code>.
*/
private JsStatement vtableStatFor(JClassType vtableType) {
- JsNameRef prototypeField = new JsNameRef(
- jsprogram.createSourceInfoSynthetic(FragmentExtractor.class),
- "prototype");
+ JsNameRef prototypeField =
+ new JsNameRef(jsprogram.createSourceInfoSynthetic(FragmentExtractor.class), "prototype");
JsExpression constructorRef;
SourceInfo sourceInfoVtableSetup = jsprogram.createSourceInfoSynthetic(FragmentExtractor.class);
if (vtableType == jprogram.getTypeJavaLangString()) {
// The methods of java.lang.String are put onto JavaScript's String
// prototype
- SourceInfo sourceInfoConstructorRef = jsprogram.createSourceInfoSynthetic(FragmentExtractor.class);
+ SourceInfo sourceInfoConstructorRef =
+ jsprogram.createSourceInfoSynthetic(FragmentExtractor.class);
constructorRef = new JsNameRef(sourceInfoConstructorRef, "String");
} else {
- constructorRef = map.nameForType(vtableType).makeRef(
- sourceInfoVtableSetup);
+ constructorRef = map.nameForType(vtableType).makeRef(sourceInfoVtableSetup);
}
prototypeField.setQualifier(constructorRef);
SourceInfo underlineSourceInfo = jsprogram.createSourceInfoSynthetic(FragmentExtractor.class);
- return (new JsBinaryOperation(sourceInfoVtableSetup, JsBinaryOperator.ASG,
- jsprogram.getScope().declareName("_").makeRef(underlineSourceInfo),
- prototypeField)).makeStmt();
+ return (new JsBinaryOperation(sourceInfoVtableSetup, JsBinaryOperator.ASG, jsprogram.getScope()
+ .declareName("_").makeRef(underlineSourceInfo), prototypeField)).makeStmt();
}
/**
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentLoaderCreator.java b/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentLoaderCreator.java
index c31fbf9..6bfa2de 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentLoaderCreator.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/FragmentLoaderCreator.java
@@ -36,7 +36,8 @@
* runAsync and how it works.
*/
public class FragmentLoaderCreator {
- public static final String ASYNC_FRAGMENT_LOADER = "com.google.gwt.core.client.impl.AsyncFragmentLoader";
+ public static final String ASYNC_FRAGMENT_LOADER =
+ "com.google.gwt.core.client.impl.AsyncFragmentLoader";
public static final String ASYNC_LOADER_CLASS_PREFIX = "AsyncLoader";
public static final String ASYNC_LOADER_PACKAGE = "com.google.gwt.lang.asyncloaders";
public static final String BROWSER_LOADER = "AsyncFragmentLoader.BROWSER_LOADER";
@@ -59,8 +60,9 @@
public FragmentLoaderCreator(StandardGeneratorContext context) {
// An empty property oracle is fine, because fragment loaders aren't
// affected by properties anyway
- this.propOracle = new StaticPropertyOracle(new BindingProperty[0],
- new String[0], new ConfigurationProperty[0]);
+ this.propOracle =
+ new StaticPropertyOracle(new BindingProperty[0], new String[0],
+ new ConfigurationProperty[0]);
this.context = context;
}
@@ -92,29 +94,25 @@
private void generateLoaderFields(PrintWriter srcWriter) {
srcWriter.println("// Callbacks that are pending");
- srcWriter.println("private static " + getCallbackListSimpleName()
- + " callbacksHead = null;");
+ srcWriter.println("private static " + getCallbackListSimpleName() + " callbacksHead = null;");
srcWriter.println("// The tail of the callbacks list");
- srcWriter.println("private static " + getCallbackListSimpleName()
- + " callbacksTail = null;");
+ srcWriter.println("private static " + getCallbackListSimpleName() + " callbacksTail = null;");
srcWriter.println("// A callback caller for this entry point");
- srcWriter.println("private static " + getLoaderSimpleName()
- + " instance = null;");
+ srcWriter.println("private static " + getLoaderSimpleName() + " instance = null;");
}
private void generateOnLoadMethod(PrintWriter srcWriter) {
srcWriter.println("public static void onLoad() {");
srcWriter.println("instance = new " + getLoaderSimpleName() + "();");
- srcWriter.println(BROWSER_LOADER + ".fragmentHasLoaded(" + entryNumber
- + ");");
+ srcWriter.println(BROWSER_LOADER + ".fragmentHasLoaded(" + entryNumber + ");");
- srcWriter.println(BROWSER_LOADER + ".logEventProgress(\""
- + RUN_CALLBACKS + entryNumber + "\", \"begin\");");
+ srcWriter.println(BROWSER_LOADER + ".logEventProgress(\"" + RUN_CALLBACKS + entryNumber
+ + "\", \"begin\");");
srcWriter.println("instance." + RUN_CALLBACKS + "();");
- srcWriter.println(BROWSER_LOADER + ".logEventProgress(\""
- + RUN_CALLBACKS + entryNumber + "\", \"end\");");
+ srcWriter.println(BROWSER_LOADER + ".logEventProgress(\"" + RUN_CALLBACKS + entryNumber
+ + "\", \"end\");");
srcWriter.println("}");
}
@@ -143,8 +141,7 @@
srcWriter.println(" instance." + RUN_CALLBACKS + "();");
srcWriter.println(" return;");
srcWriter.println("}");
- srcWriter.println("if (!" + BROWSER_LOADER + ".isLoading(" + entryNumber
- + ")) {");
+ srcWriter.println("if (!" + BROWSER_LOADER + ".isLoading(" + entryNumber + ")) {");
srcWriter.println(" " + BROWSER_LOADER + ".inject(" + entryNumber + ",");
srcWriter.println(" new AsyncFragmentLoader.LoadTerminatedHandler() {");
srcWriter.println(" public void loadTerminated(Throwable reason) {");
@@ -173,8 +170,7 @@
srcWriter.println(" " + UNCAUGHT_EXCEPTION_HANDLER_CLASS + " handler = "
+ "GWT.getUncaughtExceptionHandler();");
- srcWriter.println(" " + getCallbackListSimpleName()
- + " next = callbacksHead;");
+ srcWriter.println(" " + getCallbackListSimpleName() + " next = callbacksHead;");
srcWriter.println(" callbacksHead = callbacksHead.next;");
srcWriter.println(" if (callbacksHead == null) {");
srcWriter.println(" callbacksTail = null;");
@@ -218,17 +214,14 @@
return ASYNC_LOADER_PACKAGE;
}
- private PrintWriter getSourceWriterForLoader(TreeLogger logger,
- GeneratorContext ctx) {
- PrintWriter printWriter = ctx.tryCreate(logger, getPackage(),
- getLoaderSimpleName());
+ private PrintWriter getSourceWriterForLoader(TreeLogger logger, GeneratorContext ctx) {
+ PrintWriter printWriter = ctx.tryCreate(logger, getPackage(), getLoaderSimpleName());
if (printWriter == null) {
return null;
}
printWriter.println("package " + getPackage() + ";");
- String[] imports = new String[] {
- GWT_CLASS, RUN_ASYNC_CALLBACK, ASYNC_FRAGMENT_LOADER};
+ String[] imports = new String[]{GWT_CLASS, RUN_ASYNC_CALLBACK, ASYNC_FRAGMENT_LOADER};
for (String imp : imports) {
printWriter.println("import " + imp + ";");
}
@@ -239,11 +232,9 @@
private void writeCallbackListClass(TreeLogger logger, GeneratorContext ctx)
throws UnableToCompleteException {
- PrintWriter printWriter = ctx.tryCreate(logger, getPackage(),
- getCallbackListSimpleName());
+ PrintWriter printWriter = ctx.tryCreate(logger, getPackage(), getCallbackListSimpleName());
if (printWriter == null) {
- logger.log(TreeLogger.ERROR, "Could not create type: "
- + getCallbackListQualifiedName());
+ logger.log(TreeLogger.ERROR, "Could not create type: " + getCallbackListQualifiedName());
throw new UnableToCompleteException();
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaAST.java b/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaAST.java
index f286b79..75815f1 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaAST.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaAST.java
@@ -141,6 +141,7 @@
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression;
+import org.eclipse.jdt.internal.compiler.ast.OperatorIds;
import org.eclipse.jdt.internal.compiler.ast.PostfixExpression;
import org.eclipse.jdt.internal.compiler.ast.PrefixExpression;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
@@ -232,8 +233,8 @@
* Used to cache {@link Method} lookups.
*/
private static class MethodKey {
- private Class<? extends Object> childClass;
- private String name;
+ private final Class<? extends Object> childClass;
+ private final String name;
public MethodKey(String name, Class<? extends Object> childClass) {
this.name = name;
@@ -244,8 +245,7 @@
public boolean equals(Object obj) {
if (obj instanceof MethodKey) {
MethodKey otherKey = (MethodKey) obj;
- return name.equals(otherKey.name)
- && childClass.equals(otherKey.childClass);
+ return name.equals(otherKey.name) && childClass.equals(otherKey.childClass);
}
return super.equals(obj);
}
@@ -287,8 +287,7 @@
*/
private static final String ARRAY_LENGTH_FIELD = "length";
- private static InternalCompilerException translateException(JNode node,
- Throwable e) {
+ private static InternalCompilerException translateException(JNode node, Throwable e) {
if (e instanceof VirtualMachineError) {
// Always rethrow VM errors (an attempt to wrap may fail).
throw (VirtualMachineError) e;
@@ -298,8 +297,7 @@
ice = (InternalCompilerException) e;
ice.addNode(node);
} else {
- ice = new InternalCompilerException(node,
- "Error constructing Java AST", e);
+ ice = new InternalCompilerException(node, "Error constructing Java AST", e);
}
return ice;
}
@@ -326,9 +324,11 @@
private final boolean enableAsserts;
- private final Map<JsniMethodBody, AbstractMethodDeclaration> jsniMethodMap = new HashMap<JsniMethodBody, AbstractMethodDeclaration>();
+ private final Map<JsniMethodBody, AbstractMethodDeclaration> jsniMethodMap =
+ new HashMap<JsniMethodBody, AbstractMethodDeclaration>();
- private final Map<JMethod, Map<String, JLabel>> labelMap = new IdentityHashMap<JMethod, Map<String, JLabel>>();
+ private final Map<JMethod, Map<String, JLabel>> labelMap =
+ new IdentityHashMap<JMethod, Map<String, JLabel>>();
private final Map<MethodKey, MethodValue> methodCache = new HashMap<MethodKey, MethodValue>();
@@ -336,8 +336,7 @@
private final TypeMap typeMap;
- public JavaASTGenerationVisitor(TypeMap typeMap, JProgram program,
- JJSOptions options) {
+ public JavaASTGenerationVisitor(TypeMap typeMap, JProgram program, JJSOptions options) {
this.typeMap = typeMap;
this.program = program;
this.enableAsserts = options.isEnableAssertions();
@@ -391,8 +390,7 @@
*/
if (clazzBinding.syntheticMethods() != null) {
for (SyntheticMethodBinding synthmeth : clazzBinding.syntheticMethods()) {
- if (synthmeth.purpose == SyntheticMethodBinding.BridgeMethod
- && !synthmeth.isStatic()) {
+ if (synthmeth.purpose == SyntheticMethodBinding.BridgeMethod && !synthmeth.isStatic()) {
JMethod implmeth = (JMethod) typeMap.get(synthmeth.targetMethod);
createBridgeMethod(clazz, synthmeth, implmeth);
@@ -456,8 +454,8 @@
if (currentClass.getSuperClass() != null) {
JMethod myClinit = currentClass.getMethods().get(0);
JMethod superClinit = currentClass.getSuperClass().getMethods().get(0);
- JMethodCall superClinitCall = new JMethodCall(
- myClinit.getSourceInfo(), null, superClinit);
+ JMethodCall superClinitCall =
+ new JMethodCall(myClinit.getSourceInfo(), null, superClinit);
JMethodBody body = (JMethodBody) myClinit.getBody();
body.getBlock().addStmt(0, superClinitCall.makeStatement());
}
@@ -505,8 +503,7 @@
}
// Write the body of the getClass() override.
- if (currentClass instanceof JClassType
- && currentClass != program.getTypeJavaLangObject()) {
+ if (currentClass instanceof JClassType && currentClass != program.getTypeJavaLangObject()) {
JMethod method = currentClass.getMethods().get(2);
assert ("getClass".equals(method.getName()));
@@ -517,17 +514,13 @@
} else {
tryFindUpRefs(method);
SourceInfo info = method.getSourceInfo();
- if (isScript(program)
- && currentClass == program.getIndexedType("Array")) {
+ if (isScript(program) && currentClass == program.getIndexedType("Array")) {
// Special implementation: return this.arrayClass
- implementMethod(
- method,
- new JFieldRef(info, new JThisRef(info,
- (JClassType) currentClass),
- program.getIndexedField("Array.arrayClass"), currentClass));
- } else {
- implementMethod(method, new JClassLiteral(info.makeChild(),
+ implementMethod(method, new JFieldRef(info, new JThisRef(info,
+ (JClassType) currentClass), program.getIndexedField("Array.arrayClass"),
currentClass));
+ } else {
+ implementMethod(method, new JClassLiteral(info.makeChild(), currentClass));
}
}
}
@@ -550,9 +543,9 @@
implementMethod(method, program.getLiteralBoolean(enableAsserts));
if (disableClassMetadata) {
- JMethod isMetadataEnabledMethod = program.getIndexedMethod("Class.isClassMetadataEnabled");
- implementMethod(isMetadataEnabledMethod,
- program.getLiteralBoolean(false));
+ JMethod isMetadataEnabledMethod =
+ program.getIndexedMethod("Class.isClassMetadataEnabled");
+ implementMethod(isMetadataEnabledMethod, program.getLiteralBoolean(false));
}
}
@@ -600,8 +593,7 @@
* literal nodes because they ALWAYS have a constant value.
*/
JExpression result = null;
- if (x != null && x.constant != null
- && x.constant != Constant.NotAConstant) {
+ if (x != null && x.constant != null && x.constant != Constant.NotAConstant) {
result = (JExpression) dispatch("processConstant", x.constant);
}
@@ -620,9 +612,8 @@
// Such trees are cleaned up in FixAssignmentToUnbox.
JType typeToUnbox = (JType) typeMap.get(x.resolvedType);
if (!(typeToUnbox instanceof JClassType)) {
- throw new InternalCompilerException(result,
- "Attempt to unbox a non-class type: " + typeToUnbox.getName(),
- null);
+ throw new InternalCompilerException(result, "Attempt to unbox a non-class type: "
+ + typeToUnbox.getName(), null);
}
result = unbox(result, (JClassType) typeToUnbox);
@@ -686,10 +677,9 @@
JStringLiteral processConstant(StringConstant x) {
// May be processing an annotation
- SourceInfo info = currentMethod == null ? currentClass.getSourceInfo()
- : currentMethod.getSourceInfo();
- return program.getLiteralString(info.makeChild(),
- x.stringValue().toCharArray());
+ SourceInfo info =
+ currentMethod == null ? currentClass.getSourceInfo() : currentMethod.getSourceInfo();
+ return program.getLiteralString(info.makeChild(), x.stringValue().toCharArray());
}
/**
@@ -722,8 +712,7 @@
* steps are 1) assigning synthetic args to fields and 2) running
* initializers.
*/
- boolean hasExplicitThis = (x.constructorCall != null)
- && !x.constructorCall.isSuperAccess();
+ boolean hasExplicitThis = (x.constructorCall != null) && !x.constructorCall.isSuperAccess();
JClassType enclosingType = ctor.getEnclosingType();
JBlock block = currentMethodBody.getBlock();
@@ -743,12 +732,10 @@
JParameter param = paramIt.next();
JField field = (JField) typeMap.get(arg);
if (!hasExplicitThis) {
- block.addStmt(JProgram.createAssignmentStmt(info,
- createVariableRef(info, field),
+ block.addStmt(JProgram.createAssignmentStmt(info, createVariableRef(info, field),
createVariableRef(info, param)));
}
- currentOuterThisRefParams = Maps.put(currentOuterThisRefParams,
- field, param);
+ currentOuterThisRefParams = Maps.put(currentOuterThisRefParams, field, param);
}
}
@@ -758,8 +745,7 @@
for (SyntheticArgumentBinding arg : nestedBinding.outerLocalVariables) {
JParameter param = paramIt.next();
JField field = (JField) typeMap.get(arg);
- block.addStmt(JProgram.createAssignmentStmt(info,
- createVariableRef(info, field),
+ block.addStmt(JProgram.createAssignmentStmt(info, createVariableRef(info, field),
createVariableRef(info, param)));
}
}
@@ -768,15 +754,15 @@
// optional this or super constructor call
if (x.constructorCall != null) {
- JMethodCall superOrThisCall = (JMethodCall) dispatch(
- "processExpression", x.constructorCall);
+ JMethodCall superOrThisCall =
+ (JMethodCall) dispatch("processExpression", x.constructorCall);
// Enums: wire up synthetic name/ordinal params to the super method.
if (enclosingType.isEnumOrSubclass() != null) {
- JVariableRef enumNameRef = createVariableRef(
- superOrThisCall.getSourceInfo(), ctor.getParams().get(0));
+ JVariableRef enumNameRef =
+ createVariableRef(superOrThisCall.getSourceInfo(), ctor.getParams().get(0));
superOrThisCall.addArg(0, enumNameRef);
- JVariableRef enumOrdinalRef = createVariableRef(
- superOrThisCall.getSourceInfo(), ctor.getParams().get(1));
+ JVariableRef enumOrdinalRef =
+ createVariableRef(superOrThisCall.getSourceInfo(), ctor.getParams().get(1));
superOrThisCall.addArg(1, enumOrdinalRef);
}
@@ -833,8 +819,7 @@
int ctorArgc = ctor.getParams().size();
JMethod targetMethod = null;
outer : for (JMethod method : javaLangString.getMethods()) {
- if (method.getName().equals("_String")
- && method.getParams().size() == ctorArgc) {
+ if (method.getName().equals("_String") && method.getParams().size() == ctorArgc) {
for (int i = 0; i < ctorArgc; ++i) {
JParameter mparam = method.getParams().get(i);
JParameter cparam = ctor.getParams().get(i);
@@ -857,8 +842,8 @@
// Enums: hidden arguments for the name and id.
if (x.enumConstant != null) {
- call.addArgs(program.getLiteralString(info, x.enumConstant.name),
- program.getLiteralInt(x.enumConstant.binding.original().id));
+ call.addArgs(program.getLiteralString(info, x.enumConstant.name), program
+ .getLiteralInt(x.enumConstant.binding.original().id));
}
// Synthetic args for inner classes
@@ -884,8 +869,7 @@
if (nestedBinding.outerLocalVariables != null) {
for (SyntheticArgumentBinding arg : nestedBinding.outerLocalVariables) {
JVariable variable = (JVariable) typeMap.get(arg.actualOuterLocalVariable);
- call.addArg(createVariableRef(info, variable,
- arg.actualOuterLocalVariable));
+ call.addArg(createVariableRef(info, variable, arg.actualOuterLocalVariable));
}
}
}
@@ -896,8 +880,7 @@
JExpression processExpression(AND_AND_Expression x) {
JType type = (JType) typeMap.get(x.resolvedType);
SourceInfo info = makeSourceInfo(x);
- return processBinaryOperation(info, JBinaryOperator.AND, type, x.left,
- x.right);
+ return processBinaryOperation(info, JBinaryOperator.AND, type, x.left, x.right);
}
JExpression processExpression(ArrayAllocationExpression x) {
@@ -941,16 +924,15 @@
JExpression processExpression(ArrayReference x) {
SourceInfo info = makeSourceInfo(x);
- JArrayRef arrayRef = new JArrayRef(info,
- dispProcessExpression(x.receiver), dispProcessExpression(x.position));
+ JArrayRef arrayRef =
+ new JArrayRef(info, dispProcessExpression(x.receiver), dispProcessExpression(x.position));
return arrayRef;
}
JExpression processExpression(Assignment x) {
JType type = (JType) typeMap.get(x.resolvedType);
SourceInfo info = makeSourceInfo(x);
- return processBinaryOperation(info, JBinaryOperator.ASG, type, x.lhs,
- x.expression);
+ return processBinaryOperation(info, JBinaryOperator.ASG, type, x.lhs, x.expression);
}
JExpression processExpression(BinaryExpression x) {
@@ -958,58 +940,57 @@
int binOp = (x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
switch (binOp) {
- case BinaryExpression.LEFT_SHIFT:
+ case OperatorIds.LEFT_SHIFT:
op = JBinaryOperator.SHL;
break;
- case BinaryExpression.RIGHT_SHIFT:
+ case OperatorIds.RIGHT_SHIFT:
op = JBinaryOperator.SHR;
break;
- case BinaryExpression.UNSIGNED_RIGHT_SHIFT:
+ case OperatorIds.UNSIGNED_RIGHT_SHIFT:
op = JBinaryOperator.SHRU;
break;
- case BinaryExpression.PLUS:
+ case OperatorIds.PLUS:
if (program.isJavaLangString((JType) typeMap.get(x.resolvedType))) {
op = JBinaryOperator.CONCAT;
} else {
op = JBinaryOperator.ADD;
}
break;
- case BinaryExpression.MINUS:
+ case OperatorIds.MINUS:
op = JBinaryOperator.SUB;
break;
- case BinaryExpression.REMAINDER:
+ case OperatorIds.REMAINDER:
op = JBinaryOperator.MOD;
break;
- case BinaryExpression.XOR:
+ case OperatorIds.XOR:
op = JBinaryOperator.BIT_XOR;
break;
- case BinaryExpression.AND:
+ case OperatorIds.AND:
op = JBinaryOperator.BIT_AND;
break;
- case BinaryExpression.MULTIPLY:
+ case OperatorIds.MULTIPLY:
op = JBinaryOperator.MUL;
break;
- case BinaryExpression.OR:
+ case OperatorIds.OR:
op = JBinaryOperator.BIT_OR;
break;
- case BinaryExpression.DIVIDE:
+ case OperatorIds.DIVIDE:
op = JBinaryOperator.DIV;
break;
- case BinaryExpression.LESS_EQUAL:
+ case OperatorIds.LESS_EQUAL:
op = JBinaryOperator.LTE;
break;
- case BinaryExpression.GREATER_EQUAL:
+ case OperatorIds.GREATER_EQUAL:
op = JBinaryOperator.GTE;
break;
- case BinaryExpression.GREATER:
+ case OperatorIds.GREATER:
op = JBinaryOperator.GT;
break;
- case BinaryExpression.LESS:
+ case OperatorIds.LESS:
op = JBinaryOperator.LT;
break;
default:
- throw new InternalCompilerException(
- "Unexpected operator for BinaryExpression");
+ throw new InternalCompilerException("Unexpected operator for BinaryExpression");
}
JType type = (JType) typeMap.get(x.resolvedType);
@@ -1020,8 +1001,7 @@
JExpression processExpression(CastExpression x) {
SourceInfo info = makeSourceInfo(x);
JType type = (JType) typeMap.get(x.resolvedType);
- JCastOperation cast = new JCastOperation(info, type,
- dispProcessExpression(x.expression));
+ JCastOperation cast = new JCastOperation(info, type, dispProcessExpression(x.expression));
return cast;
}
@@ -1039,46 +1019,45 @@
JBinaryOperator op;
switch (x.operator) {
- case CompoundAssignment.PLUS:
+ case OperatorIds.PLUS:
if (program.isJavaLangString((JType) typeMap.get(x.resolvedType))) {
op = JBinaryOperator.ASG_CONCAT;
} else {
op = JBinaryOperator.ASG_ADD;
}
break;
- case CompoundAssignment.MINUS:
+ case OperatorIds.MINUS:
op = JBinaryOperator.ASG_SUB;
break;
- case CompoundAssignment.MULTIPLY:
+ case OperatorIds.MULTIPLY:
op = JBinaryOperator.ASG_MUL;
break;
- case CompoundAssignment.DIVIDE:
+ case OperatorIds.DIVIDE:
op = JBinaryOperator.ASG_DIV;
break;
- case CompoundAssignment.AND:
+ case OperatorIds.AND:
op = JBinaryOperator.ASG_BIT_AND;
break;
- case CompoundAssignment.OR:
+ case OperatorIds.OR:
op = JBinaryOperator.ASG_BIT_OR;
break;
- case CompoundAssignment.XOR:
+ case OperatorIds.XOR:
op = JBinaryOperator.ASG_BIT_XOR;
break;
- case CompoundAssignment.REMAINDER:
+ case OperatorIds.REMAINDER:
op = JBinaryOperator.ASG_MOD;
break;
- case CompoundAssignment.LEFT_SHIFT:
+ case OperatorIds.LEFT_SHIFT:
op = JBinaryOperator.ASG_SHL;
break;
- case CompoundAssignment.RIGHT_SHIFT:
+ case OperatorIds.RIGHT_SHIFT:
op = JBinaryOperator.ASG_SHR;
break;
case CompoundAssignment.UNSIGNED_RIGHT_SHIFT:
op = JBinaryOperator.ASG_SHRU;
break;
default:
- throw new InternalCompilerException(
- "Unexpected operator for CompoundAssignment");
+ throw new InternalCompilerException("Unexpected operator for CompoundAssignment");
}
JType type = (JType) typeMap.get(x.resolvedType);
@@ -1092,8 +1071,7 @@
JExpression ifTest = dispProcessExpression(x.condition);
JExpression thenExpr = dispProcessExpression(x.valueIfTrue);
JExpression elseExpr = dispProcessExpression(x.valueIfFalse);
- JConditional conditional = new JConditional(info, type, ifTest, thenExpr,
- elseExpr);
+ JConditional conditional = new JConditional(info, type, ifTest, thenExpr, elseExpr);
return conditional;
}
@@ -1107,8 +1085,7 @@
op = JBinaryOperator.NEQ;
break;
default:
- throw new InternalCompilerException(
- "Unexpected operator for EqualExpression");
+ throw new InternalCompilerException("Unexpected operator for EqualExpression");
}
JType type = (JType) typeMap.get(x.resolvedType);
@@ -1189,8 +1166,8 @@
// On a super ref, don't allow polymorphic dispatch. Oddly enough,
// QualifiedSuperReference not derived from SuperReference!
- boolean isSuperRef = x.receiver instanceof SuperReference
- || x.receiver instanceof QualifiedSuperReference;
+ boolean isSuperRef =
+ x.receiver instanceof SuperReference || x.receiver instanceof QualifiedSuperReference;
if (isSuperRef) {
call.setStaticDispatchOnly();
}
@@ -1212,8 +1189,7 @@
JExpression processExpression(OR_OR_Expression x) {
JType type = (JType) typeMap.get(x.resolvedType);
SourceInfo info = makeSourceInfo(x);
- return processBinaryOperation(info, JBinaryOperator.OR, type, x.left,
- x.right);
+ return processBinaryOperation(info, JBinaryOperator.OR, type, x.left, x.right);
}
JExpression processExpression(PostfixExpression x) {
@@ -1233,8 +1209,7 @@
throw new InternalCompilerException("Unexpected postfix operator");
}
- JPostfixOperation postOp = new JPostfixOperation(info, op,
- dispProcessExpression(x.lhs));
+ JPostfixOperation postOp = new JPostfixOperation(info, op, dispProcessExpression(x.lhs));
return postOp;
}
@@ -1255,8 +1230,7 @@
throw new InternalCompilerException("Unexpected prefix operator");
}
- JPrefixOperation preOp = new JPrefixOperation(info, op,
- dispProcessExpression(x.lhs));
+ JPrefixOperation preOp = new JPrefixOperation(info, op, dispProcessExpression(x.lhs));
return preOp;
}
@@ -1288,8 +1262,7 @@
* because the explicit qualifier takes precedence.
*/
if (!currentMethod.isStatic()) {
- JExpression implicitOuter = new JThisRef(info,
- (JClassType) currentClass);
+ JExpression implicitOuter = new JThisRef(info, (JClassType) currentClass);
qualList.add(implicitOuter);
}
@@ -1314,8 +1287,7 @@
if (nestedBinding.outerLocalVariables != null) {
for (SyntheticArgumentBinding arg : nestedBinding.outerLocalVariables) {
JVariable variable = (JVariable) typeMap.get(arg.actualOuterLocalVariable);
- newInstance.addArg(createVariableRef(info, variable,
- arg.actualOuterLocalVariable));
+ newInstance.addArg(createVariableRef(info, variable, arg.actualOuterLocalVariable));
}
}
}
@@ -1455,17 +1427,14 @@
break;
default:
- throw new InternalCompilerException(
- "Unexpected operator for unary expression");
+ throw new InternalCompilerException("Unexpected operator for unary expression");
}
- JPrefixOperation preOp = new JPrefixOperation(info, op,
- dispProcessExpression(x.expression));
+ JPrefixOperation preOp = new JPrefixOperation(info, op, dispProcessExpression(x.expression));
return preOp;
}
- List<JExpressionStatement> processExpressionStatements(
- Statement[] statements) {
+ List<JExpressionStatement> processExpressionStatements(Statement[] statements) {
List<JExpressionStatement> jstatements = new ArrayList<JExpressionStatement>();
if (statements != null) {
for (int i = 0, n = statements.length; i < n; ++i) {
@@ -1502,8 +1471,8 @@
if (initializer != null) {
SourceInfo info = makeSourceInfo(declaration);
// JDeclarationStatement's ctor sets up the field's initializer.
- JStatement decl = new JDeclarationStatement(info, createVariableRef(
- info, field), initializer);
+ JStatement decl =
+ new JDeclarationStatement(info, createVariableRef(info, field), initializer);
// will either be init or clinit
currentMethodBody.getBlock().addStmt(decl);
}
@@ -1550,8 +1519,7 @@
}
}
- void processNativeMethod(AbstractMethodDeclaration x,
- JsniMethodBody nativeMethodBody) {
+ void processNativeMethod(AbstractMethodDeclaration x, JsniMethodBody nativeMethodBody) {
// Squirrel away a reference to the JDT node to enable error reporting.
jsniMethodMap.put(nativeMethodBody, x);
}
@@ -1576,8 +1544,7 @@
JStatement processStatement(BreakStatement x) {
SourceInfo info = makeSourceInfo(x);
- return new JBreakStatement(info, getOrCreateLabel(info, currentMethod,
- x.label));
+ return new JBreakStatement(info, getOrCreateLabel(info, currentMethod, x.label));
}
JStatement processStatement(CaseStatement x) {
@@ -1596,8 +1563,7 @@
JStatement processStatement(ContinueStatement x) {
SourceInfo info = makeSourceInfo(x);
- return new JContinueStatement(info, getOrCreateLabel(info, currentMethod,
- x.label));
+ return new JContinueStatement(info, getOrCreateLabel(info, currentMethod, x.label));
}
JStatement processStatement(DoStatement x) {
@@ -1629,7 +1595,8 @@
JLocal elementVar = (JLocal) typeMap.get(x.elementVariable.binding);
String elementVarName = elementVar.getName();
- JDeclarationStatement elementDecl = (JDeclarationStatement) processStatement(x.elementVariable);
+ JDeclarationStatement elementDecl =
+ (JDeclarationStatement) processStatement(x.elementVariable);
assert (elementDecl.initializer == null);
JForStatement result;
@@ -1645,43 +1612,42 @@
* }
* </pre>
*/
- JLocal arrayVar = JProgram.createLocal(info, elementVarName + "$array",
- ((JType) typeMap.get(x.collection.resolvedType)), true,
- currentMethodBody);
- JLocal indexVar = JProgram.createLocal(info, elementVarName + "$index",
- program.getTypePrimitiveInt(), false, currentMethodBody);
- JLocal maxVar = JProgram.createLocal(info, elementVarName + "$max",
- program.getTypePrimitiveInt(), true, currentMethodBody);
+ JLocal arrayVar =
+ JProgram.createLocal(info, elementVarName + "$array", ((JType) typeMap
+ .get(x.collection.resolvedType)), true, currentMethodBody);
+ JLocal indexVar =
+ JProgram.createLocal(info, elementVarName + "$index", program.getTypePrimitiveInt(),
+ false, currentMethodBody);
+ JLocal maxVar =
+ JProgram.createLocal(info, elementVarName + "$max", program.getTypePrimitiveInt(),
+ true, currentMethodBody);
List<JStatement> initializers = new ArrayList<JStatement>(3);
// T[] i$array = arr
- initializers.add(createDeclaration(info, arrayVar,
- dispProcessExpression(x.collection)));
+ initializers.add(createDeclaration(info, arrayVar, dispProcessExpression(x.collection)));
// int i$index = 0
- initializers.add(createDeclaration(info, indexVar,
- program.getLiteralInt(0)));
+ initializers.add(createDeclaration(info, indexVar, program.getLiteralInt(0)));
// int i$max = i$array.length
- initializers.add(createDeclaration(info, maxVar, new JArrayLength(info,
- new JLocalRef(info, arrayVar))));
+ initializers.add(createDeclaration(info, maxVar, new JArrayLength(info, new JLocalRef(info,
+ arrayVar))));
// i$index < i$max
- JExpression condition = new JBinaryOperation(info,
- program.getTypePrimitiveBoolean(), JBinaryOperator.LT,
- createVariableRef(info, indexVar), createVariableRef(info, maxVar));
+ JExpression condition =
+ new JBinaryOperation(info, program.getTypePrimitiveBoolean(), JBinaryOperator.LT,
+ createVariableRef(info, indexVar), createVariableRef(info, maxVar));
// ++i$index
- List<JExpressionStatement> increments = new ArrayList<JExpressionStatement>(
- 1);
- increments.add(new JPrefixOperation(info, JUnaryOperator.INC,
- createVariableRef(info, indexVar)).makeStatement());
+ List<JExpressionStatement> increments = new ArrayList<JExpressionStatement>(1);
+ increments.add(new JPrefixOperation(info, JUnaryOperator.INC, createVariableRef(info,
+ indexVar)).makeStatement());
// T elementVar = i$array[i$index];
- elementDecl.initializer = new JArrayRef(info, createVariableRef(info,
- arrayVar), createVariableRef(info, indexVar));
+ elementDecl.initializer =
+ new JArrayRef(info, createVariableRef(info, arrayVar),
+ createVariableRef(info, indexVar));
body.addStmt(0, elementDecl);
- result = new JForStatement(info, initializers, condition, increments,
- body);
+ result = new JForStatement(info, initializers, condition, increments, body);
} else {
/**
* <pre>
@@ -1691,25 +1657,24 @@
* }
* </pre>
*/
- JLocal iteratorVar = JProgram.createLocal(info,
- (elementVarName + "$iterator"), program.getIndexedType("Iterator"),
- false, currentMethodBody);
+ JLocal iteratorVar =
+ JProgram.createLocal(info, (elementVarName + "$iterator"), program
+ .getIndexedType("Iterator"), false, currentMethodBody);
List<JStatement> initializers = new ArrayList<JStatement>(1);
// Iterator<T> i$iterator = collection.iterator()
- initializers.add(createDeclaration(
- info,
- iteratorVar,
- new JMethodCall(info, dispProcessExpression(x.collection),
- program.getIndexedMethod("Iterable.iterator"))));
+ initializers.add(createDeclaration(info, iteratorVar, new JMethodCall(info,
+ dispProcessExpression(x.collection), program.getIndexedMethod("Iterable.iterator"))));
// i$iterator.hasNext()
- JExpression condition = new JMethodCall(info, createVariableRef(info,
- iteratorVar), program.getIndexedMethod("Iterator.hasNext"));
+ JExpression condition =
+ new JMethodCall(info, createVariableRef(info, iteratorVar), program
+ .getIndexedMethod("Iterator.hasNext"));
// T elementVar = (T) i$iterator.next();
- elementDecl.initializer = new JMethodCall(info, createVariableRef(info,
- iteratorVar), program.getIndexedMethod("Iterator.next"));
+ elementDecl.initializer =
+ new JMethodCall(info, createVariableRef(info, iteratorVar), program
+ .getIndexedMethod("Iterator.next"));
// Perform any implicit reference type casts (due to generics).
// Note this occurs before potential unboxing.
@@ -1722,8 +1687,7 @@
collectionType = (TypeBinding) privateField.get(x);
} catch (Exception e) {
throw new InternalCompilerException(elementDecl,
- "Failed to retreive collectionElementType through reflection",
- e);
+ "Failed to retreive collectionElementType through reflection", e);
}
JType toType = (JType) typeMap.get(collectionType);
assert (toType instanceof JReferenceType);
@@ -1732,8 +1696,9 @@
body.addStmt(0, elementDecl);
- result = new JForStatement(info, initializers, condition,
- Collections.<JExpressionStatement> emptyList(), body);
+ result =
+ new JForStatement(info, initializers, condition, Collections
+ .<JExpressionStatement> emptyList(), body);
}
// May need to box or unbox the element assignment.
@@ -1744,11 +1709,12 @@
* expression cannot be a constant, so the box type must be exactly
* that associated with the expression.
*/
- elementDecl.initializer = autoboxUtils.box(elementDecl.initializer,
- ((JPrimitiveType) elementDecl.initializer.getType()));
+ elementDecl.initializer =
+ autoboxUtils.box(elementDecl.initializer, ((JPrimitiveType) elementDecl.initializer
+ .getType()));
} else if ((x.elementVariableImplicitWidening & TypeIds.UNBOXING) != 0) {
- elementDecl.initializer = unbox(elementDecl.initializer,
- (JClassType) elementDecl.initializer.getType());
+ elementDecl.initializer =
+ unbox(elementDecl.initializer, (JClassType) elementDecl.initializer.getType());
}
}
return result;
@@ -1776,10 +1742,8 @@
SourceInfo info = makeSourceInfo(x);
JExpression expr = dispProcessExpression(x.condition);
- JStatement thenStmt = removeThen ? null
- : dispProcessStatement(x.thenStatement);
- JStatement elseStmt = removeElse ? null
- : dispProcessStatement(x.elseStatement);
+ JStatement thenStmt = removeThen ? null : dispProcessStatement(x.thenStatement);
+ JStatement elseStmt = removeElse ? null : dispProcessStatement(x.elseStatement);
JIfStatement ifStmt = new JIfStatement(info, expr, thenStmt, elseStmt);
return ifStmt;
}
@@ -1790,8 +1754,7 @@
return null;
}
SourceInfo info = makeSourceInfo(x);
- return new JLabeledStatement(info, getOrCreateLabel(info, currentMethod,
- x.label), body);
+ return new JLabeledStatement(info, getOrCreateLabel(info, currentMethod, x.label), body);
}
JStatement processStatement(LocalDeclaration x) {
@@ -1812,8 +1775,7 @@
JExpression expression = dispProcessExpression(x.expression);
if (isEnumType(expression.getType())) {
// Must be an enum; synthesize a call to ordinal().
- expression = new JMethodCall(info, expression,
- program.getIndexedMethod("Enum.ordinal"));
+ expression = new JMethodCall(info, expression, program.getIndexedMethod("Enum.ordinal"));
}
JBlock block = new JBlock(info);
// Don't use processStatements here, because it stops at control breaks
@@ -1856,8 +1818,7 @@
}
}
JBlock finallyBlock = (JBlock) dispProcessStatement(x.finallyBlock);
- return new JTryStatement(info, tryBlock, catchArgs, catchBlocks,
- finallyBlock);
+ return new JTryStatement(info, tryBlock, catchArgs, catchBlocks, finallyBlock);
}
JStatement processStatement(TypeDeclaration x) {
@@ -1952,8 +1913,7 @@
String varName = String.valueOf(arg.name);
JParameter param = null;
for (JParameter paramIt : currentMethod.getParams()) {
- if (varType == paramIt.getType()
- && varName.equals(paramIt.getName())) {
+ if (varType == paramIt.getType() && varName.equals(paramIt.getName())) {
param = paramIt;
}
}
@@ -2005,8 +1965,8 @@
return call;
}
- private void addAllOuterThisRefs(List<? super JVariableRef> list,
- JExpression expr, JClassType classType) {
+ private void addAllOuterThisRefs(List<? super JVariableRef> list, JExpression expr,
+ JClassType classType) {
for (JField field : classType.getFields()) {
// This fields are always first.
if (!field.isThisRef()) {
@@ -2020,22 +1980,19 @@
if (param != null) {
list.add(new JParameterRef(expr.getSourceInfo(), param));
} else {
- list.add(new JFieldRef(expr.getSourceInfo(), expr, field,
- currentClass));
+ list.add(new JFieldRef(expr.getSourceInfo(), expr, field, currentClass));
}
}
}
- private void addAllOuterThisRefsPlusSuperChain(
- List<? super JVariableRef> workList, JExpression expr,
- JClassType classType) {
+ private void addAllOuterThisRefsPlusSuperChain(List<? super JVariableRef> workList,
+ JExpression expr, JClassType classType) {
for (; classType != null; classType = classType.getSuperClass()) {
addAllOuterThisRefs(workList, expr, classType);
}
}
- private void addCallArgs(Expression[] jdtArgs, JMethodCall call,
- MethodBinding binding) {
+ private void addCallArgs(Expression[] jdtArgs, JMethodCall call, MethodBinding binding) {
JExpression[] args = new JExpression[jdtArgs == null ? 0 : jdtArgs.length];
for (int i = 0; i < args.length; ++i) {
args[i] = dispProcessExpression(jdtArgs[i]);
@@ -2071,8 +2028,8 @@
initializers.add(args[i]);
}
JArrayType lastParamType = (JArrayType) typeMap.get(params[varArg]);
- JNewArray newArray = JNewArray.createInitializers(SourceOrigin.UNKNOWN,
- lastParamType, initializers);
+ JNewArray newArray =
+ JNewArray.createInitializers(SourceOrigin.UNKNOWN, lastParamType, initializers);
call.addArg(newArray);
}
@@ -2090,23 +2047,23 @@
* @param jdtBridgeMethod The corresponding bridge method added in the JDT
* @param implmeth The implementation method to bridge to
*/
- private void createBridgeMethod(JClassType clazz,
- SyntheticMethodBinding jdtBridgeMethod, JMethod implmeth) {
+ private void createBridgeMethod(JClassType clazz, SyntheticMethodBinding jdtBridgeMethod,
+ JMethod implmeth) {
SourceInfo info = implmeth.getSourceInfo().makeChild();
// create the method itself
- JMethod bridgeMethod = program.createMethod(info,
- String.valueOf(jdtBridgeMethod.selector), clazz,
- (JType) typeMap.get(jdtBridgeMethod.returnType.erasure()), false,
- false, implmeth.isFinal(), false, false);
+ JMethod bridgeMethod =
+ program.createMethod(info, String.valueOf(jdtBridgeMethod.selector), clazz,
+ (JType) typeMap.get(jdtBridgeMethod.returnType.erasure()), false, false, implmeth
+ .isFinal(), false, false);
bridgeMethod.setSynthetic();
int paramIdx = 0;
List<JParameter> implParams = implmeth.getParams();
for (TypeBinding jdtParamType : jdtBridgeMethod.parameters) {
JParameter param = implParams.get(paramIdx++);
JType paramType = (JType) typeMap.get(jdtParamType.erasure());
- JParameter newParam = new JParameter(
- info.makeChild(param.getSourceInfo().getOrigin()), param.getName(),
- paramType, true, false, bridgeMethod);
+ JParameter newParam =
+ new JParameter(info.makeChild(param.getSourceInfo().getOrigin()), param.getName(),
+ paramType, true, false, bridgeMethod);
bridgeMethod.addParam(newParam);
}
addThrownExceptions(jdtBridgeMethod, bridgeMethod);
@@ -2114,8 +2071,7 @@
info.addCorrelation(info.getCorrelator().by(bridgeMethod));
// create a call
- JMethodCall call = new JMethodCall(info, new JThisRef(info, clazz),
- implmeth);
+ JMethodCall call = new JMethodCall(info, new JThisRef(info, clazz), implmeth);
for (int i = 0; i < bridgeMethod.getParams().size(); i++) {
JParameter param = bridgeMethod.getParams().get(i);
@@ -2152,8 +2108,7 @@
}
}
- private JDeclarationStatement createDeclaration(SourceInfo info,
- JLocal local, JExpression value) {
+ private JDeclarationStatement createDeclaration(SourceInfo info, JLocal local, JExpression value) {
return new JDeclarationStatement(info, new JLocalRef(info, local), value);
}
@@ -2162,8 +2117,7 @@
* access) of the appropriate type. Always use this method instead of
* creating a naked JThisRef or you won't get the synthetic accesses right.
*/
- private JExpression createQualifiedThisRef(SourceInfo info,
- JClassType targetType) {
+ private JExpression createQualifiedThisRef(SourceInfo info, JClassType targetType) {
assert (currentClass instanceof JClassType);
JExpression expr = new JThisRef(info, ((JClassType) currentClass));
List<JExpression> list = new ArrayList<JExpression>();
@@ -2204,8 +2158,7 @@
*
* TODO(scottb): could we get this info directly from JDT?
*/
- private JExpression createThisRef(JReferenceType qualType,
- List<JExpression> list) {
+ private JExpression createThisRef(JReferenceType qualType, List<JExpression> list) {
LinkedList<JExpression> workList = new LinkedList<JExpression>();
workList.addAll(list);
while (!workList.isEmpty()) {
@@ -2221,8 +2174,7 @@
}
}
- throw new InternalCompilerException(
- "Cannot create a ThisRef of the appropriate type.");
+ throw new InternalCompilerException("Cannot create a ThisRef of the appropriate type.");
}
/**
@@ -2232,8 +2184,7 @@
*/
private JExpression createThisRef(SourceInfo info, JReferenceType targetType) {
assert (currentClass instanceof JClassType);
- return createThisRef(targetType, new JThisRef(info,
- ((JClassType) currentClass)));
+ return createThisRef(targetType, new JThisRef(info, ((JClassType) currentClass)));
}
/**
@@ -2244,8 +2195,7 @@
if (variable instanceof JLocal) {
JLocal local = (JLocal) variable;
if (local.getEnclosingMethod() != currentMethod) {
- throw new InternalCompilerException(
- "LocalRef referencing local in a different method.");
+ throw new InternalCompilerException("LocalRef referencing local in a different method.");
}
return new JLocalRef(info, local);
} else if (variable instanceof JParameter) {
@@ -2261,10 +2211,9 @@
if (!field.isStatic()) {
JClassType fieldEnclosingType = (JClassType) field.getEnclosingType();
instance = createThisRef(info, fieldEnclosingType);
- if (!program.typeOracle.canTriviallyCast(
- (JReferenceType) instance.getType(), fieldEnclosingType)) {
- throw new InternalCompilerException(
- "FieldRef referencing field in a different type.");
+ if (!program.typeOracle.canTriviallyCast((JReferenceType) instance.getType(),
+ fieldEnclosingType)) {
+ throw new InternalCompilerException("FieldRef referencing field in a different type.");
}
}
return new JFieldRef(info, instance, field, currentClass);
@@ -2276,8 +2225,7 @@
* Creates an appropriate JVariableRef for the polymorphic type of the
* requested JVariable.
*/
- private JVariableRef createVariableRef(SourceInfo info, JVariable variable,
- Binding binding) {
+ private JVariableRef createVariableRef(SourceInfo info, JVariable variable, Binding binding) {
// Fix up the reference if it's to an outer local/param
variable = possiblyReferenceOuterLocal(variable, binding);
if (variable == null) {
@@ -2299,8 +2247,8 @@
return typeBinding;
}
- private Method getCachedMethod(String name,
- Class<? extends Object> childClass) throws NoSuchMethodException {
+ private Method getCachedMethod(String name, Class<? extends Object> childClass)
+ throws NoSuchMethodException {
MethodKey key = new MethodKey(name, childClass);
MethodValue value = methodCache.get(key);
if (value == null) {
@@ -2316,8 +2264,7 @@
return value.getMethod();
}
- private JInterfaceType getOrCreateExternalType(SourceInfo info,
- char[][] compoundName) {
+ private JInterfaceType getOrCreateExternalType(SourceInfo info, char[][] compoundName) {
String name = BuildTypeMap.dotify(compoundName);
JInterfaceType external = (JInterfaceType) program.getFromTypeMap(name);
if (external == null) {
@@ -2331,8 +2278,7 @@
* Get a new label of a particular name, or create a new one if it doesn't
* exist already.
*/
- private JLabel getOrCreateLabel(SourceInfo info, JMethod enclosingMethod,
- char[] name) {
+ private JLabel getOrCreateLabel(SourceInfo info, JMethod enclosingMethod, char[] name) {
if (name == null) {
return null;
}
@@ -2378,8 +2324,7 @@
* local parameters.
*/
private Iterator<JParameter> getSyntheticLocalsIterator() {
- return currentMethod.getParams().listIterator(
- currentMethod.getOriginalParamTypes().size());
+ return currentMethod.getParams().listIterator(currentMethod.getOriginalParamTypes().size());
}
private void implementMethod(JMethod method, JExpression returnValue) {
@@ -2431,8 +2376,7 @@
case TypeIds.T_short:
return program.getTypePrimitiveShort();
default:
- throw new InternalCompilerException(
- "Could not determine the desired box type");
+ throw new InternalCompilerException("Could not determine the desired box type");
}
}
@@ -2455,10 +2399,11 @@
}
private SourceInfo makeSourceInfo(Statement x) {
- int startLine = Util.getLineNumber(x.sourceStart,
- currentSeparatorPositions, 0, currentSeparatorPositions.length - 1);
- SourceOrigin toReturn = SourceOrigin.create(x.sourceStart, x.sourceEnd,
- startLine, currentFileName);
+ int startLine =
+ Util.getLineNumber(x.sourceStart, currentSeparatorPositions, 0,
+ currentSeparatorPositions.length - 1);
+ SourceOrigin toReturn =
+ SourceOrigin.create(x.sourceStart, x.sourceEnd, startLine, currentFileName);
if (currentMethod != null) {
return currentMethod.getSourceInfo().makeChild(toReturn);
}
@@ -2469,8 +2414,7 @@
if (expected != expression.getType()) {
// Must be a generic; insert a cast operation.
JReferenceType toType = (JReferenceType) expected;
- return new JCastOperation(expression.getSourceInfo(), toType,
- expression);
+ return new JCastOperation(expression.getSourceInfo(), toType, expression);
} else {
return expression;
}
@@ -2486,8 +2430,7 @@
* Once we have this clue, we can use getEmulationPath to compute the
* current class's binding for that field.
*/
- private JVariable possiblyReferenceOuterLocal(JVariable variable,
- Binding binding) {
+ private JVariable possiblyReferenceOuterLocal(JVariable variable, Binding binding) {
if (variable instanceof JLocal || variable instanceof JParameter) {
LocalVariableBinding localBinding = (LocalVariableBinding) binding;
@@ -2597,17 +2540,15 @@
* look for the specific operators that we think should match each JDT node,
* and throw an error if there's a mismatch.
*/
- private JExpression processBinaryOperation(SourceInfo info,
- JBinaryOperator op, JType type, Expression arg1, Expression arg2) {
+ private JExpression processBinaryOperation(SourceInfo info, JBinaryOperator op, JType type,
+ Expression arg1, Expression arg2) {
JExpression exprArg1 = dispProcessExpression(arg1);
JExpression exprArg2 = dispProcessExpression(arg2);
- JBinaryOperation binaryOperation = new JBinaryOperation(info, type, op,
- exprArg1, exprArg2);
+ JBinaryOperation binaryOperation = new JBinaryOperation(info, type, op, exprArg1, exprArg2);
return binaryOperation;
}
- private JExpression processQualifiedThisOrSuperRef(
- QualifiedThisReference x, JClassType qualType) {
+ private JExpression processQualifiedThisOrSuperRef(QualifiedThisReference x, JClassType qualType) {
/*
* WEIRD: If a thisref or superref is qualified with the EXACT type of the
* innermost type (in other words, a needless qualifier), it must refer to
@@ -2627,8 +2568,7 @@
}
}
- private InternalCompilerException translateException(Object node,
- Throwable e) {
+ private InternalCompilerException translateException(Object node, Throwable e) {
if (e instanceof VirtualMachineError) {
// Always rethrow VM errors (an attempt to wrap may fail).
throw (VirtualMachineError) e;
@@ -2679,14 +2619,13 @@
* For a given method(and method binding), recursively try to find all
* methods that it overrides/implements.
*/
- private void tryFindUpRefsRecursive(JMethod method,
- JDeclaredType searchThisType, List<JMethod> overrides) {
+ private void tryFindUpRefsRecursive(JMethod method, JDeclaredType searchThisType,
+ List<JMethod> overrides) {
// See if this class has any uprefs, unless this class is myself
if (method.getEnclosingType() != searchThisType) {
for (JMethod upRef : searchThisType.getMethods()) {
- if (JTypeOracle.methodsDoMatch(method, upRef)
- && !overrides.contains(upRef)) {
+ if (JTypeOracle.methodsDoMatch(method, upRef) && !overrides.contains(upRef)) {
overrides.add(upRef);
break;
}
@@ -2695,8 +2634,7 @@
// recurse super class
if (searchThisType.getSuperClass() != null) {
- tryFindUpRefsRecursive(method, searchThisType.getSuperClass(),
- overrides);
+ tryFindUpRefsRecursive(method, searchThisType.getSuperClass(), overrides);
}
// recurse super interfaces
@@ -2749,9 +2687,8 @@
private JExpression unbox(JExpression toUnbox, JClassType wrapperType) {
JPrimitiveType primitiveType = getPrimitiveTypeForWrapperType(wrapperType);
if (primitiveType == null) {
- throw new InternalCompilerException(toUnbox,
- "Attempt to unbox unexpected type '" + wrapperType.getName() + "'",
- null);
+ throw new InternalCompilerException(toUnbox, "Attempt to unbox unexpected type '"
+ + wrapperType.getName() + "'", null);
}
String valueMethodName = primitiveType.getName() + "Value";
@@ -2768,14 +2705,12 @@
}
if (valueMethod == null) {
- throw new InternalCompilerException(toUnbox,
- "Expected to find a method on '" + wrapperType.getName()
- + "' whose signature matches 'public "
- + primitiveType.getName() + " " + valueMethodName + "()'", null);
+ throw new InternalCompilerException(toUnbox, "Expected to find a method on '"
+ + wrapperType.getName() + "' whose signature matches 'public "
+ + primitiveType.getName() + " " + valueMethodName + "()'", null);
}
- JMethodCall unboxCall = new JMethodCall(toUnbox.getSourceInfo(), toUnbox,
- valueMethod);
+ JMethodCall unboxCall = new JMethodCall(toUnbox.getSourceInfo(), toUnbox, valueMethod);
return unboxCall;
}
@@ -2789,24 +2724,24 @@
* class Map { $MAP = Enum.createValueOfMap($VALUES); }
*/
SourceInfo typeInfo = type.getSourceInfo().makeChild();
- JClassType mapClass = program.createClass(typeInfo, type.getName()
- + "$Map", false, true);
+ JClassType mapClass = program.createClass(typeInfo, type.getName() + "$Map", false, true);
typeInfo.addCorrelation(typeInfo.getCorrelator().by(mapClass));
mapClass.setSuperClass(program.getTypeJavaLangObject());
SourceInfo fieldInfo = typeInfo.makeChild();
- mapField = program.createField(fieldInfo, "$MAP", mapClass,
- program.getJavaScriptObject(), true, Disposition.FINAL);
+ mapField =
+ program.createField(fieldInfo, "$MAP", mapClass, program.getJavaScriptObject(), true,
+ Disposition.FINAL);
fieldInfo.addCorrelation(fieldInfo.getCorrelator().by(mapField));
SourceInfo methodInfo = typeInfo.makeChild();
- JMethodCall call = new JMethodCall(methodInfo, null,
- program.getIndexedMethod("Enum.createValueOfMap"));
+ JMethodCall call =
+ new JMethodCall(methodInfo, null, program.getIndexedMethod("Enum.createValueOfMap"));
call.addArg(new JFieldRef(methodInfo, null, valuesField, type));
JFieldRef mapRef = new JFieldRef(methodInfo, null, mapField, type);
- JDeclarationStatement declStmt = new JDeclarationStatement(methodInfo,
- mapRef, call);
- JMethod clinit = program.createMethod(methodInfo, "$clinit", mapClass,
- program.getTypeVoid(), false, true, true, true, false);
+ JDeclarationStatement declStmt = new JDeclarationStatement(methodInfo, mapRef, call);
+ JMethod clinit =
+ program.createMethod(methodInfo, "$clinit", mapClass, program.getTypeVoid(), false,
+ true, true, true, false);
clinit.freezeParamTypes();
methodInfo.addCorrelation(methodInfo.getCorrelator().by(clinit));
JBlock clinitBlock = ((JMethodBody) clinit.getBody()).getBlock();
@@ -2820,14 +2755,12 @@
{
SourceInfo sourceInfo = currentMethodBody.getSourceInfo();
JFieldRef mapRef = new JFieldRef(sourceInfo, null, mapField, type);
- JVariableRef nameRef = createVariableRef(sourceInfo,
- currentMethod.getParams().get(0));
+ JVariableRef nameRef = createVariableRef(sourceInfo, currentMethod.getParams().get(0));
JMethod delegateTo = program.getIndexedMethod("Enum.valueOf");
JMethodCall call = new JMethodCall(sourceInfo, null, delegateTo);
call.addArgs(mapRef, nameRef);
- currentMethodBody.getBlock().addStmt(
- new JReturnStatement(sourceInfo, call));
+ currentMethodBody.getBlock().addStmt(new JReturnStatement(sourceInfo, call));
}
}
@@ -2837,19 +2770,17 @@
// $VALUES = new E[]{A,B,B};
SourceInfo fieldInfo = type.getSourceInfo().makeChild();
JArrayType enumArrayType = program.getTypeArray(type);
- valuesField = program.createField(fieldInfo, "$VALUES", type,
- enumArrayType, true, Disposition.FINAL);
+ valuesField =
+ program.createField(fieldInfo, "$VALUES", type, enumArrayType, true, Disposition.FINAL);
fieldInfo.addCorrelation(fieldInfo.getCorrelator().by(valuesField));
List<JExpression> initializers = new ArrayList<JExpression>();
for (JEnumField field : type.getEnumList()) {
JFieldRef fieldRef = new JFieldRef(fieldInfo, null, field, type);
initializers.add(fieldRef);
}
- JNewArray newExpr = JNewArray.createInitializers(fieldInfo,
- enumArrayType, initializers);
+ JNewArray newExpr = JNewArray.createInitializers(fieldInfo, enumArrayType, initializers);
JFieldRef valuesRef = new JFieldRef(fieldInfo, null, valuesField, type);
- JDeclarationStatement declStmt = new JDeclarationStatement(fieldInfo,
- valuesRef, newExpr);
+ JDeclarationStatement declStmt = new JDeclarationStatement(fieldInfo, valuesRef, newExpr);
JBlock clinitBlock = ((JMethodBody) type.getMethods().get(0).getBody()).getBlock();
/*
@@ -2867,8 +2798,7 @@
// return $VALUES;
SourceInfo sourceInfo = currentMethod.getSourceInfo();
JFieldRef valuesRef = new JFieldRef(sourceInfo, null, valuesField, type);
- currentMethodBody.getBlock().addStmt(
- new JReturnStatement(sourceInfo, valuesRef));
+ currentMethodBody.getBlock().addStmt(new JReturnStatement(sourceInfo, valuesRef));
}
return valuesField;
}
@@ -2883,8 +2813,7 @@
private final AbstractMethodDeclaration methodDecl;
private final JsniMethodBody nativeMethodBody;
- private JsniRefResolver(AbstractMethodDeclaration methodDecl,
- JsniMethodBody nativeMethodBody) {
+ private JsniRefResolver(AbstractMethodDeclaration methodDecl, JsniMethodBody nativeMethodBody) {
this.methodDecl = methodDecl;
this.nativeMethodBody = nativeMethodBody;
}
@@ -2900,19 +2829,18 @@
private JNode findJsniRefTarget(final SourceInfo info, String ident) {
JsniRef parsed = JsniRef.parse(ident);
if (parsed == null) {
- JsniCollector.reportJsniError(info, methodDecl,
- "Badly formatted native reference '" + ident + "'");
+ JsniCollector.reportJsniError(info, methodDecl, "Badly formatted native reference '"
+ + ident + "'");
return null;
}
JProgram prog = program;
- return JsniRefLookup.findJsniRefTarget(parsed, prog,
- new JsniRefLookup.ErrorReporter() {
- public void reportError(String error) {
- JsniCollector.reportJsniError(info, methodDecl, error);
- }
- });
+ return JsniRefLookup.findJsniRefTarget(parsed, prog, new JsniRefLookup.ErrorReporter() {
+ public void reportError(String error) {
+ JsniCollector.reportJsniError(info, methodDecl, error);
+ }
+ });
}
private void processClassLiteral(JClassLiteral classLiteral, JsContext ctx) {
@@ -2920,8 +2848,7 @@
nativeMethodBody.addClassRef(classLiteral);
}
- private void processField(JsNameRef nameRef, SourceInfo info,
- JField field, JsContext ctx) {
+ private void processField(JsNameRef nameRef, SourceInfo info, JField field, JsContext ctx) {
/*
* We must replace any compile-time constants with the constant value of
* the field.
@@ -2941,16 +2868,15 @@
}
// Normal: create a jsniRef.
- JsniFieldRef fieldRef = new JsniFieldRef(info, nameRef.getIdent(),
- field, currentClass, ctx.isLvalue());
+ JsniFieldRef fieldRef =
+ new JsniFieldRef(info, nameRef.getIdent(), field, currentClass, ctx.isLvalue());
nativeMethodBody.addJsniRef(fieldRef);
}
- private void processMethod(JsNameRef nameRef, SourceInfo info,
- JMethod method, JsContext ctx) {
+ private void processMethod(JsNameRef nameRef, SourceInfo info, JMethod method, JsContext ctx) {
assert !ctx.isLvalue();
- JsniMethodRef methodRef = new JsniMethodRef(info, nameRef.getIdent(),
- method, program.getJavaScriptObject());
+ JsniMethodRef methodRef =
+ new JsniMethodRef(info, nameRef.getIdent(), method, program.getJavaScriptObject());
nativeMethodBody.addJsniRef(methodRef);
}
@@ -3022,12 +2948,11 @@
* Combines the information from the JDT type nodes and the type map to create
* a JProgram structure.
*/
- public static void exec(TypeDeclaration[] types, TypeMap typeMap,
- JProgram jprogram, JJSOptions options) {
+ public static void exec(TypeDeclaration[] types, TypeMap typeMap, JProgram jprogram,
+ JJSOptions options) {
Event generateJavaAstEvent = SpeedTracerLogger.start(CompilerEventType.GENERATE_JAVA_AST);
// Construct the basic AST.
- JavaASTGenerationVisitor v = new JavaASTGenerationVisitor(typeMap,
- jprogram, options);
+ JavaASTGenerationVisitor v = new JavaASTGenerationVisitor(typeMap, jprogram, options);
for (TypeDeclaration type : types) {
v.processType(type);
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptAST.java b/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptAST.java
index 80517a8..b36d175 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptAST.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptAST.java
@@ -245,8 +245,7 @@
* referenced as instance on null-types (as determined by type flow)
*/
JMethod nullMethod = x.getNullMethod();
- polymorphicNames.put(nullMethod,
- objectScope.declareName(nullMethod.getName()));
+ polymorphicNames.put(nullMethod, objectScope.declareName(nullMethod.getName()));
JField nullField = x.getNullField();
JsName nullFieldName = objectScope.declareName(nullField.getName());
names.put(nullField, nullFieldName);
@@ -366,8 +365,7 @@
* 1:1 mapping to obfuscated symbols. Leaving them in global scope
* causes no harm.
*/
- jsFunction = new JsFunction(x.getSourceInfo(), topScope, globalName,
- true);
+ jsFunction = new JsFunction(x.getSourceInfo(), topScope, globalName, true);
}
if (polymorphicNames.containsKey(x)) {
polymorphicJsFunctions.add(jsFunction);
@@ -376,8 +374,9 @@
push(jsFunction.getScope());
if (program.getIndexedMethods().contains(x)) {
- indexedFunctions = Maps.put(indexedFunctions,
- x.getEnclosingType().getShortName() + "." + x.getName(), jsFunction);
+ indexedFunctions =
+ Maps.put(indexedFunctions, x.getEnclosingType().getShortName() + "." + x.getName(),
+ jsFunction);
}
return true;
}
@@ -391,8 +390,7 @@
for (int i = 0, c = catchArgs.size(); i < c; ++i) {
JLocalRef arg = catchArgs.get(i);
JBlock catchBlock = catchBlocks.get(i);
- JsCatch jsCatch = new JsCatch(x.getSourceInfo(), peek(),
- arg.getTarget().getName());
+ JsCatch jsCatch = new JsCatch(x.getSourceInfo(), peek(), arg.getTarget().getName());
JsParameter jsParam = jsCatch.getParameter();
names.put(arg.getTarget(), jsParam.getName());
catchMap.put(catchBlock, jsCatch);
@@ -441,18 +439,17 @@
private void recordSymbol(JReferenceType x, JsName jsName) {
int queryId = program.getQueryId(x);
JsonObject castableTypeMapObj = program.getCastableTypeMap(x);
- CastableTypeMap castableTypeMap = new StandardCastableTypeMap(
- castableTypeMapObj.toString());
+ CastableTypeMap castableTypeMap = new StandardCastableTypeMap(castableTypeMapObj.toString());
- StandardSymbolData symbolData = StandardSymbolData.forClass(x.getName(),
- x.getSourceInfo().getFileName(), x.getSourceInfo().getStartLine(),
- queryId, castableTypeMap);
+ StandardSymbolData symbolData =
+ StandardSymbolData.forClass(x.getName(), x.getSourceInfo().getFileName(), x
+ .getSourceInfo().getStartLine(), queryId, castableTypeMap);
assert !symbolTable.containsKey(symbolData);
symbolTable.put(symbolData, jsName);
}
- private <T extends HasEnclosingType & HasName & HasSourceInfo> void recordSymbol(
- T x, JsName jsName) {
+ private <T extends HasEnclosingType & HasName & HasSourceInfo> void recordSymbol(T x,
+ JsName jsName) {
/*
* NB: The use of x.getName() can produce confusion in cases where a type
* has both polymorphic and static dispatch for a method, because you
@@ -481,12 +478,11 @@
methodSig = null;
}
- StandardSymbolData symbolData = StandardSymbolData.forMember(
- x.getEnclosingType().getName(), x.getName(), methodSig,
- makeUriString(x), x.getSourceInfo().getStartLine());
- assert !symbolTable.containsKey(symbolData) : "Duplicate symbol "
- + "recorded " + jsName.getIdent() + " for " + x.getName()
- + " and key " + symbolData.getJsniIdent();
+ StandardSymbolData symbolData =
+ StandardSymbolData.forMember(x.getEnclosingType().getName(), x.getName(), methodSig,
+ makeUriString(x), x.getSourceInfo().getStartLine());
+ assert !symbolTable.containsKey(symbolData) : "Duplicate symbol " + "recorded "
+ + jsName.getIdent() + " for " + x.getName() + " and key " + symbolData.getJsniIdent();
symbolTable.put(symbolData, jsName);
}
}
@@ -495,7 +491,9 @@
private final Set<JClassType> alreadyRan = new HashSet<JClassType>();
- private Map<JClassType, JsFunction> clinitMap = new HashMap<JClassType, JsFunction>();
+ private final JsName arrayLength = objectScope.declareName("length");
+
+ private final Map<JClassType, JsFunction> clinitMap = new HashMap<JClassType, JsFunction>();
private JMethod currentMethod = null;
@@ -512,8 +510,6 @@
*/
private Map<JMethod, Integer> entryMethodToIndex;
- private final JsName arrayLength = objectScope.declareName("length");
-
private final JsName globalTemp = topScope.declareName("_");
private final JsName prototype = objectScope.declareName("prototype");
@@ -561,12 +557,10 @@
* Use === and !== on reference types, or else you can get wrong answers
* when Object.toString() == 'some string'.
*/
- if (myOp == JsBinaryOperator.EQ
- && x.getLhs().getType() instanceof JReferenceType
+ if (myOp == JsBinaryOperator.EQ && x.getLhs().getType() instanceof JReferenceType
&& x.getRhs().getType() instanceof JReferenceType) {
myOp = JsBinaryOperator.REF_EQ;
- } else if (myOp == JsBinaryOperator.NEQ
- && x.getLhs().getType() instanceof JReferenceType
+ } else if (myOp == JsBinaryOperator.NEQ && x.getLhs().getType() instanceof JReferenceType
&& x.getRhs().getType() instanceof JReferenceType) {
myOp = JsBinaryOperator.REF_NEQ;
}
@@ -724,15 +718,14 @@
JsNameRef localRef = (JsNameRef) pop(); // localRef
JVariable target = x.getVariableRef().getTarget();
- if (target instanceof JField
- && ((JField) target).getLiteralInitializer() != null) {
+ if (target instanceof JField && ((JField) target).getLiteralInitializer() != null) {
// Will initialize at top scope; no need to double-initialize.
push(null);
return;
}
- JsBinaryOperation binOp = new JsBinaryOperation(x.getSourceInfo(),
- JsBinaryOperator.ASG, localRef, initializer);
+ JsBinaryOperation binOp =
+ new JsBinaryOperation(x.getSourceInfo(), JsBinaryOperator.ASG, localRef, initializer);
push(binOp.makeStmt());
}
@@ -761,8 +754,7 @@
if (x.getLiteralInitializer() != null) {
// setup the constant value
accept(x.getLiteralInitializer());
- } else if (!x.hasInitializer()
- && x.getEnclosingType() != program.getTypeJavaLangObject()) {
+ } else if (!x.hasInitializer() && x.getEnclosingType() != program.getTypeJavaLangObject()) {
// setup a default value
accept(x.getType().getDefaultValue());
} else {
@@ -1080,8 +1072,7 @@
}
if (cur == null) {
// the multi-expression was empty; use undefined
- cur = new JsNameRef(x.getSourceInfo(),
- JsRootScope.INSTANCE.getUndefined());
+ cur = new JsNameRef(x.getSourceInfo(), JsRootScope.INSTANCE.getUndefined());
}
push(cur);
}
@@ -1118,15 +1109,17 @@
@Override
public void endVisit(JPostfixOperation x, Context ctx) {
- JsUnaryOperation op = new JsPostfixOperation(x.getSourceInfo(),
- JavaToJsOperatorMap.get(x.getOp()), ((JsExpression) pop())); // arg
+ JsUnaryOperation op =
+ new JsPostfixOperation(x.getSourceInfo(), JavaToJsOperatorMap.get(x.getOp()),
+ ((JsExpression) pop())); // arg
push(op);
}
@Override
public void endVisit(JPrefixOperation x, Context ctx) {
- JsUnaryOperation op = new JsPrefixOperation(x.getSourceInfo(),
- JavaToJsOperatorMap.get(x.getOp()), ((JsExpression) pop())); // arg
+ JsUnaryOperation op =
+ new JsPrefixOperation(x.getSourceInfo(), JavaToJsOperatorMap.get(x.getOp()),
+ ((JsExpression) pop())); // arg
push(op);
}
@@ -1135,9 +1128,7 @@
List<JsStatement> globalStmts = jsProgram.getGlobalBlock().getStatements();
// Generate entry methods
- generateGwtOnLoad(
- Arrays.asList(entryFunctions).subList(0, x.getEntryCount(0)),
- globalStmts);
+ generateGwtOnLoad(Arrays.asList(entryFunctions).subList(0, x.getEntryCount(0)), globalStmts);
generateNullFunc(globalStmts);
// Add a few things onto the beginning.
@@ -1166,10 +1157,11 @@
* Likewise, add a call to
* AsyncFragmentLoader.leftoversFragmentHasLoaded().
*/
- List<JsFunction> nonInitialEntries = Arrays.asList(entryFunctions).subList(
- x.getEntryCount(0), entryFunctions.length);
+ List<JsFunction> nonInitialEntries =
+ Arrays.asList(entryFunctions).subList(x.getEntryCount(0), entryFunctions.length);
if (!nonInitialEntries.isEmpty()) {
- JMethod loadedMethod = program.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded");
+ JMethod loadedMethod =
+ program.getIndexedMethod("AsyncFragmentLoader.browserLoaderLeftoversFragmentHasLoaded");
JsName loadedMethodName = names.get(loadedMethod);
JsInvocation call = new JsInvocation(jsProgram.getSourceInfo());
call.setQualifier(loadedMethodName.makeRef(jsProgram.getSourceInfo().makeChild()));
@@ -1178,8 +1170,7 @@
for (JsFunction func : nonInitialEntries) {
if (func != null) {
JsInvocation call = new JsInvocation(jsProgram.getSourceInfo());
- call.setQualifier(func.getName().makeRef(
- jsProgram.getSourceInfo().makeChild()));
+ call.setQualifier(func.getName().makeRef(jsProgram.getSourceInfo().makeChild()));
globalStmts.add(call.makeStmt());
}
}
@@ -1476,23 +1467,19 @@
}
private JsExpression createAssignment(JsExpression lhs, JsExpression rhs) {
- return new JsBinaryOperation(lhs.getSourceInfo(), JsBinaryOperator.ASG,
- lhs, rhs);
+ return new JsBinaryOperation(lhs.getSourceInfo(), JsBinaryOperator.ASG, lhs, rhs);
}
- private JsExpression createCommaExpression(JsExpression lhs,
- JsExpression rhs) {
+ private JsExpression createCommaExpression(JsExpression lhs, JsExpression rhs) {
if (lhs == null) {
return rhs;
} else if (rhs == null) {
return lhs;
}
- return new JsBinaryOperation(lhs.getSourceInfo(), JsBinaryOperator.COMMA,
- lhs, rhs);
+ return new JsBinaryOperation(lhs.getSourceInfo(), JsBinaryOperator.COMMA, lhs, rhs);
}
- private void generateCastableTypeMap(JClassType x,
- List<JsStatement> globalStmts) {
+ private void generateCastableTypeMap(JClassType x, List<JsStatement> globalStmts) {
JsonObject castableTypeMap = program.getCastableTypeMap(x);
if (castableTypeMap != null) {
JField castableTypeMapField = program.getIndexedField("Object.castableTypeMap");
@@ -1534,8 +1521,8 @@
* Must execute in clinit statement order, NOT field order, so that back
* refs to super classes are preserved.
*/
- JMethodBody clinitBody = (JMethodBody) program.getTypeClassLiteralHolder().getMethods().get(
- 0).getBody();
+ JMethodBody clinitBody =
+ (JMethodBody) program.getTypeClassLiteralHolder().getMethods().get(0).getBody();
for (JStatement stmt : clinitBody.getStatements()) {
if (stmt instanceof JDeclarationStatement) {
generateClassLiteral((JDeclarationStatement) stmt, vars);
@@ -1557,8 +1544,7 @@
generateCastableTypeMap(x, globalStmts);
}
- private void generateGwtOnLoad(List<JsFunction> entryFuncs,
- List<JsStatement> globalStmts) {
+ private void generateGwtOnLoad(List<JsFunction> entryFuncs, List<JsStatement> globalStmts) {
/**
* <pre>
* var $entry = Impl.registerEntry();
@@ -1584,8 +1570,7 @@
JsVar entryVar = new JsVar(sourceInfo, entryName);
JsInvocation registerEntryCall = new JsInvocation(sourceInfo);
JsFunction registerEntryFunction = indexedFunctions.get("Impl.registerEntry");
- registerEntryCall.setQualifier(registerEntryFunction.getName().makeRef(
- sourceInfo));
+ registerEntryCall.setQualifier(registerEntryFunction.getName().makeRef(sourceInfo));
entryVar.setInitExpr(registerEntryCall);
JsVars entryVars = new JsVars(sourceInfo);
entryVars.add(entryVar);
@@ -1593,8 +1578,7 @@
JsName gwtOnLoadName = topScope.declareName("gwtOnLoad");
gwtOnLoadName.setObfuscatable(false);
- JsFunction gwtOnLoad = new JsFunction(sourceInfo, topScope,
- gwtOnLoadName, true);
+ JsFunction gwtOnLoad = new JsFunction(sourceInfo, topScope, gwtOnLoadName, true);
globalStmts.add(gwtOnLoad.makeStmt());
JsBlock body = new JsBlock(sourceInfo);
gwtOnLoad.setBody(body);
@@ -1608,20 +1592,22 @@
params.add(new JsParameter(sourceInfo, modName));
params.add(new JsParameter(sourceInfo, modBase));
params.add(new JsParameter(sourceInfo, softPermutationId));
- JsExpression asg = createAssignment(
- topScope.findExistingUnobfuscatableName("$moduleName").makeRef(
+ JsExpression asg =
+ createAssignment(topScope.findExistingUnobfuscatableName("$moduleName").makeRef(
sourceInfo), modName.makeRef(sourceInfo));
body.getStatements().add(asg.makeStmt());
- asg = createAssignment(
- topScope.findExistingUnobfuscatableName("$moduleBase").makeRef(
+ asg =
+ createAssignment(topScope.findExistingUnobfuscatableName("$moduleBase").makeRef(
sourceInfo), modBase.makeRef(sourceInfo));
body.getStatements().add(asg.makeStmt());
// Assignment to CollapsedPropertyHolder.permutationId only if it's used
- JsName permutationIdFieldName = names.get(program.getIndexedField("CollapsedPropertyHolder.permutationId"));
+ JsName permutationIdFieldName =
+ names.get(program.getIndexedField("CollapsedPropertyHolder.permutationId"));
if (permutationIdFieldName != null) {
- asg = createAssignment(permutationIdFieldName.makeRef(sourceInfo),
- softPermutationId.makeRef(sourceInfo));
+ asg =
+ createAssignment(permutationIdFieldName.makeRef(sourceInfo), softPermutationId
+ .makeRef(sourceInfo));
body.getStatements().add(asg.makeStmt());
}
@@ -1668,23 +1654,20 @@
private void generateNullFunc(List<JsStatement> globalStatements) {
// handle null method
SourceInfo sourceInfo = jsProgram.createSourceInfoSynthetic(GenerateJavaScriptAST.class);
- JsFunction nullFunc = new JsFunction(sourceInfo, topScope,
- nullMethodName, true);
+ JsFunction nullFunc = new JsFunction(sourceInfo, topScope, nullMethodName, true);
nullFunc.setBody(new JsBlock(sourceInfo));
// Add it first, so that script-tag chunking in IFrameLinker works
globalStatements.add(0, nullFunc.makeStmt());
}
- private void generateSeedFuncAndPrototype(JClassType x,
- List<JsStatement> globalStmts) {
+ private void generateSeedFuncAndPrototype(JClassType x, List<JsStatement> globalStmts) {
SourceInfo sourceInfo = x.getSourceInfo();
if (x != program.getTypeJavaLangString()) {
JsName seedFuncName = names.get(x);
// seed function
// function com_example_foo_Foo() { }
- JsFunction seedFunc = new JsFunction(sourceInfo, topScope,
- seedFuncName, true);
+ JsFunction seedFunc = new JsFunction(sourceInfo, topScope, seedFuncName, true);
seedFuncName.setStaticRef(seedFunc);
JsBlock body = new JsBlock(sourceInfo);
seedFunc.setBody(body);
@@ -1698,8 +1681,7 @@
seedProtoRef.setQualifier(seedFuncName.makeRef(sourceInfo));
JsExpression protoObj;
if (x.getSuperClass() != null) {
- JsNameRef superPrototypeRef = names.get(x.getSuperClass()).makeRef(
- sourceInfo);
+ JsNameRef superPrototypeRef = names.get(x.getSuperClass()).makeRef(sourceInfo);
JsNew newExpr = new JsNew(sourceInfo, superPrototypeRef);
protoObj = newExpr;
} else {
@@ -1717,8 +1699,7 @@
}
// Finally, assign to the temp var for setup code.
- JsExpression tmpAsg = createAssignment(globalTemp.makeRef(sourceInfo),
- protoAsg);
+ JsExpression tmpAsg = createAssignment(globalTemp.makeRef(sourceInfo), protoAsg);
JsExprStmt tmpAsgStmt = tmpAsg.makeStmt();
globalStmts.add(tmpAsgStmt);
typeForStatMap.put(tmpAsgStmt, x);
@@ -1728,18 +1709,16 @@
* primitive with a modified prototype.
*/
JsNameRef rhs = prototype.makeRef(sourceInfo);
- rhs.setQualifier(JsRootScope.INSTANCE.findExistingUnobfuscatableName(
- "String").makeRef(sourceInfo));
- JsExpression tmpAsg = createAssignment(globalTemp.makeRef(sourceInfo),
- rhs);
+ rhs.setQualifier(JsRootScope.INSTANCE.findExistingUnobfuscatableName("String").makeRef(
+ sourceInfo));
+ JsExpression tmpAsg = createAssignment(globalTemp.makeRef(sourceInfo), rhs);
JsExprStmt tmpAsgStmt = tmpAsg.makeStmt();
globalStmts.add(tmpAsgStmt);
typeForStatMap.put(tmpAsgStmt, x);
}
}
- private void generateToStringAlias(JClassType x,
- List<JsStatement> globalStmts) {
+ private void generateToStringAlias(JClassType x, List<JsStatement> globalStmts) {
JMethod toStringMeth = program.getIndexedMethod("Object.toString");
if (x.getMethods().contains(toStringMeth)) {
SourceInfo sourceInfo = x.getSourceInfo();
@@ -1753,8 +1732,7 @@
// rhs
JsInvocation call = new JsInvocation(sourceInfo);
- JsNameRef toStringRef = new JsNameRef(sourceInfo,
- polymorphicNames.get(toStringMeth));
+ JsNameRef toStringRef = new JsNameRef(sourceInfo, polymorphicNames.get(toStringMeth));
toStringRef.setQualifier(new JsThisRef(sourceInfo));
call.setQualifier(toStringRef);
JsReturn jsReturn = new JsReturn(sourceInfo, call);
@@ -1781,8 +1759,7 @@
SourceInfo sourceInfo = jsProgram.createSourceInfoSynthetic(GenerateJavaScriptAST.class);
JsNameRef fieldRef = typeMarkerName.makeRef(sourceInfo);
fieldRef.setQualifier(globalTemp.makeRef(sourceInfo));
- JsExpression asg = createAssignment(fieldRef,
- nullMethodName.makeRef(sourceInfo));
+ JsExpression asg = createAssignment(fieldRef, nullMethodName.makeRef(sourceInfo));
JsExprStmt stmt = asg.makeStmt();
globalStmts.add(stmt);
typeForStatMap.put(stmt, program.getTypeJavaLangObject());
@@ -1813,9 +1790,9 @@
List<JsStatement> statements = clinitFunc.getBody().getStatements();
SourceInfo sourceInfo = clinitFunc.getSourceInfo();
// self-assign to the null method immediately (to prevent reentrancy)
- JsExpression asg = createAssignment(
- clinitFunc.getName().makeRef(sourceInfo),
- nullMethodName.makeRef(sourceInfo));
+ JsExpression asg =
+ createAssignment(clinitFunc.getName().makeRef(sourceInfo), nullMethodName
+ .makeRef(sourceInfo));
statements.add(0, asg.makeStmt());
}
@@ -1863,10 +1840,10 @@
}
private static class JavaToJsOperatorMap {
- private static final Map<JBinaryOperator, JsBinaryOperator> bOpMap = new EnumMap<JBinaryOperator, JsBinaryOperator>(
- JBinaryOperator.class);
- private static final Map<JUnaryOperator, JsUnaryOperator> uOpMap = new EnumMap<JUnaryOperator, JsUnaryOperator>(
- JUnaryOperator.class);
+ private static final Map<JBinaryOperator, JsBinaryOperator> bOpMap =
+ new EnumMap<JBinaryOperator, JsBinaryOperator>(JBinaryOperator.class);
+ private static final Map<JUnaryOperator, JsUnaryOperator> uOpMap =
+ new EnumMap<JUnaryOperator, JsUnaryOperator>(JUnaryOperator.class);
static {
bOpMap.put(JBinaryOperator.MUL, JsBinaryOperator.MUL);
@@ -1997,8 +1974,8 @@
public static JavaToJavaScriptMap exec(JProgram program, JsProgram jsProgram,
JsOutputOption output, Map<StandardSymbolData, JsName> symbolTable,
PropertyOracle[] propertyOracles) {
- GenerateJavaScriptAST generateJavaScriptAST = new GenerateJavaScriptAST(
- program, jsProgram, output, symbolTable, propertyOracles);
+ GenerateJavaScriptAST generateJavaScriptAST =
+ new GenerateJavaScriptAST(program, jsProgram, output, symbolTable, propertyOracles);
return generateJavaScriptAST.execImpl();
}
@@ -2010,7 +1987,7 @@
* A list of methods that are called from another class (ie might need to
* clinit).
*/
- private Set<JMethod> crossClassTargets = new HashSet<JMethod>();
+ private final Set<JMethod> crossClassTargets = new HashSet<JMethod>();
private Map<String, JsFunction> indexedFunctions = Maps.create();
@@ -2030,7 +2007,8 @@
*/
private final Map<Long, JsName> longLits = new TreeMap<Long, JsName>();
private final Map<JsName, JsExpression> longObjects = new IdentityHashMap<JsName, JsExpression>();
- private final Map<JAbstractMethodBody, JsFunction> methodBodyMap = new IdentityHashMap<JAbstractMethodBody, JsFunction>();
+ private final Map<JAbstractMethodBody, JsFunction> methodBodyMap =
+ new IdentityHashMap<JAbstractMethodBody, JsFunction>();
private final Map<HasName, JsName> names = new IdentityHashMap<HasName, JsName>();
private JsName nullMethodName;
@@ -2064,7 +2042,7 @@
* If true, polymorphic functions are made anonymous vtable declarations and
* not assigned topScope identifiers.
*/
- private boolean stripStack;
+ private final boolean stripStack;
/**
* Maps JsNames to machine-usable identifiers.
@@ -2076,15 +2054,16 @@
*/
private final JsScope topScope;
- private final Map<JsStatement, JClassType> typeForStatMap = new HashMap<JsStatement, JClassType>();
+ private final Map<JsStatement, JClassType> typeForStatMap =
+ new HashMap<JsStatement, JClassType>();
private final JTypeOracle typeOracle;
- private final Map<JsStatement, JMethod> vtableInitForMethodMap = new HashMap<JsStatement, JMethod>();
+ private final Map<JsStatement, JMethod> vtableInitForMethodMap =
+ new HashMap<JsStatement, JMethod>();
- private GenerateJavaScriptAST(JProgram program, JsProgram jsProgram,
- JsOutputOption output, Map<StandardSymbolData, JsName> symbolTable,
- PropertyOracle[] propertyOracles) {
+ private GenerateJavaScriptAST(JProgram program, JsProgram jsProgram, JsOutputOption output,
+ Map<StandardSymbolData, JsName> symbolTable, PropertyOracle[] propertyOracles) {
this.program = program;
typeOracle = program.typeOracle;
this.jsProgram = jsProgram;
@@ -2094,7 +2073,8 @@
this.output = output;
this.symbolTable = symbolTable;
- this.stripStack = JsStackEmulator.getStackMode(propertyOracles) == JsStackEmulator.StackMode.STRIP;
+ this.stripStack =
+ JsStackEmulator.getStackMode(propertyOracles) == JsStackEmulator.StackMode.STRIP;
/*
* Because we modify String's prototype, all fields and polymorphic methods
* on String's super types need special handling.
@@ -2156,8 +2136,7 @@
}
String mangleNameForGlobal(JMethod x) {
- String s = getNameString(x.getEnclosingType()) + '_' + getNameString(x)
- + "__";
+ String s = getNameString(x.getEnclosingType()) + '_' + getNameString(x) + "__";
for (int i = 0; i < x.getOriginalParamTypes().size(); ++i) {
JType type = x.getOriginalParamTypes().get(i);
s += type.getJavahSignatureName();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptLiterals.java b/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptLiterals.java
index fb50d79..2b2f26c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptLiterals.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/GenerateJavaScriptLiterals.java
@@ -125,8 +125,7 @@
return list;
}
- protected final <T extends JsVisitable> void popList(List<T> collection,
- int count) {
+ protected final <T extends JsVisitable> void popList(List<T> collection, int count) {
List<T> list = new ArrayList<T>();
while (count > 0) {
T item = this.<T> pop();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/GwtAstBuilder.java b/dev/core/src/com/google/gwt/dev/jjs/impl/GwtAstBuilder.java
index 32034c9..0812f5b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/GwtAstBuilder.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/GwtAstBuilder.java
@@ -154,6 +154,7 @@
import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.eclipse.jdt.internal.compiler.ast.NullLiteral;
import org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression;
+import org.eclipse.jdt.internal.compiler.ast.OperatorIds;
import org.eclipse.jdt.internal.compiler.ast.PostfixExpression;
import org.eclipse.jdt.internal.compiler.ast.PrefixExpression;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;
@@ -337,7 +338,7 @@
private final Stack<MethodInfo> methodStack = new Stack<MethodInfo>();
- private ArrayList<JNode> nodeStack = new ArrayList<JNode>();
+ private final ArrayList<JNode> nodeStack = new ArrayList<JNode>();
@Override
public void endVisit(AllocationExpression x, BlockScope scope) {
@@ -433,53 +434,53 @@
JBinaryOperator op;
int binOp = (x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT;
switch (binOp) {
- case BinaryExpression.LEFT_SHIFT:
+ case OperatorIds.LEFT_SHIFT:
op = JBinaryOperator.SHL;
break;
- case BinaryExpression.RIGHT_SHIFT:
+ case OperatorIds.RIGHT_SHIFT:
op = JBinaryOperator.SHR;
break;
- case BinaryExpression.UNSIGNED_RIGHT_SHIFT:
+ case OperatorIds.UNSIGNED_RIGHT_SHIFT:
op = JBinaryOperator.SHRU;
break;
- case BinaryExpression.PLUS:
+ case OperatorIds.PLUS:
if (x.resolvedType instanceof ReferenceBinding) {
op = JBinaryOperator.CONCAT;
} else {
op = JBinaryOperator.ADD;
}
break;
- case BinaryExpression.MINUS:
+ case OperatorIds.MINUS:
op = JBinaryOperator.SUB;
break;
- case BinaryExpression.REMAINDER:
+ case OperatorIds.REMAINDER:
op = JBinaryOperator.MOD;
break;
- case BinaryExpression.XOR:
+ case OperatorIds.XOR:
op = JBinaryOperator.BIT_XOR;
break;
- case BinaryExpression.AND:
+ case OperatorIds.AND:
op = JBinaryOperator.BIT_AND;
break;
- case BinaryExpression.MULTIPLY:
+ case OperatorIds.MULTIPLY:
op = JBinaryOperator.MUL;
break;
- case BinaryExpression.OR:
+ case OperatorIds.OR:
op = JBinaryOperator.BIT_OR;
break;
- case BinaryExpression.DIVIDE:
+ case OperatorIds.DIVIDE:
op = JBinaryOperator.DIV;
break;
- case BinaryExpression.LESS_EQUAL:
+ case OperatorIds.LESS_EQUAL:
op = JBinaryOperator.LTE;
break;
- case BinaryExpression.GREATER_EQUAL:
+ case OperatorIds.GREATER_EQUAL:
op = JBinaryOperator.GTE;
break;
- case BinaryExpression.GREATER:
+ case OperatorIds.GREATER:
op = JBinaryOperator.GT;
break;
- case BinaryExpression.LESS:
+ case OperatorIds.LESS:
op = JBinaryOperator.LT;
break;
default:
@@ -572,41 +573,41 @@
public void endVisit(CompoundAssignment x, BlockScope scope) {
JBinaryOperator op;
switch (x.operator) {
- case CompoundAssignment.PLUS:
+ case OperatorIds.PLUS:
if (x.resolvedType instanceof ReferenceBinding) {
op = JBinaryOperator.ASG_CONCAT;
} else {
op = JBinaryOperator.ASG_ADD;
}
break;
- case CompoundAssignment.MINUS:
+ case OperatorIds.MINUS:
op = JBinaryOperator.ASG_SUB;
break;
- case CompoundAssignment.MULTIPLY:
+ case OperatorIds.MULTIPLY:
op = JBinaryOperator.ASG_MUL;
break;
- case CompoundAssignment.DIVIDE:
+ case OperatorIds.DIVIDE:
op = JBinaryOperator.ASG_DIV;
break;
- case CompoundAssignment.AND:
+ case OperatorIds.AND:
op = JBinaryOperator.ASG_BIT_AND;
break;
- case CompoundAssignment.OR:
+ case OperatorIds.OR:
op = JBinaryOperator.ASG_BIT_OR;
break;
- case CompoundAssignment.XOR:
+ case OperatorIds.XOR:
op = JBinaryOperator.ASG_BIT_XOR;
break;
- case CompoundAssignment.REMAINDER:
+ case OperatorIds.REMAINDER:
op = JBinaryOperator.ASG_MOD;
break;
- case CompoundAssignment.LEFT_SHIFT:
+ case OperatorIds.LEFT_SHIFT:
op = JBinaryOperator.ASG_SHL;
break;
- case CompoundAssignment.RIGHT_SHIFT:
+ case OperatorIds.RIGHT_SHIFT:
op = JBinaryOperator.ASG_SHR;
break;
- case CompoundAssignment.UNSIGNED_RIGHT_SHIFT:
+ case OperatorIds.UNSIGNED_RIGHT_SHIFT:
op = JBinaryOperator.ASG_SHRU;
break;
default:
@@ -734,11 +735,11 @@
@Override
public void endVisit(EqualExpression x, BlockScope scope) {
JBinaryOperator op;
- switch ((x.bits & BinaryExpression.OperatorMASK) >> BinaryExpression.OperatorSHIFT) {
- case BinaryExpression.EQUAL_EQUAL:
+ switch ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT) {
+ case OperatorIds.EQUAL_EQUAL:
op = JBinaryOperator.EQ;
break;
- case BinaryExpression.NOT_EQUAL:
+ case OperatorIds.NOT_EQUAL:
op = JBinaryOperator.NEQ;
break;
default:
@@ -1179,11 +1180,11 @@
SourceInfo info = makeSourceInfo(x);
JUnaryOperator op;
switch (x.operator) {
- case PostfixExpression.MINUS:
+ case OperatorIds.MINUS:
op = JUnaryOperator.DEC;
break;
- case PostfixExpression.PLUS:
+ case OperatorIds.PLUS:
op = JUnaryOperator.INC;
break;
@@ -1204,11 +1205,11 @@
SourceInfo info = makeSourceInfo(x);
JUnaryOperator op;
switch (x.operator) {
- case PostfixExpression.MINUS:
+ case OperatorIds.MINUS:
op = JUnaryOperator.DEC;
break;
- case PostfixExpression.PLUS:
+ case OperatorIds.PLUS:
op = JUnaryOperator.INC;
break;
@@ -1454,23 +1455,23 @@
try {
SourceInfo info = makeSourceInfo(x);
JUnaryOperator op;
- int operator = ((x.bits & UnaryExpression.OperatorMASK) >> UnaryExpression.OperatorSHIFT);
+ int operator = ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT);
switch (operator) {
- case UnaryExpression.MINUS:
+ case OperatorIds.MINUS:
op = JUnaryOperator.NEG;
break;
- case UnaryExpression.NOT:
+ case OperatorIds.NOT:
op = JUnaryOperator.NOT;
break;
- case UnaryExpression.PLUS:
+ case OperatorIds.PLUS:
// Odd case.. useless + operator; just leave the operand on the
// stack.
return;
- case UnaryExpression.TWIDDLE:
+ case OperatorIds.TWIDDLE:
op = JUnaryOperator.BIT_NOT;
break;
@@ -2098,17 +2099,17 @@
private JExpression getConstant(SourceInfo info, Constant constant) {
switch (constant.typeID()) {
- case Constant.T_int:
+ case TypeIds.T_int:
return JIntLiteral.get(constant.intValue());
- case Constant.T_byte:
+ case TypeIds.T_byte:
return JIntLiteral.get(constant.byteValue());
- case Constant.T_short:
+ case TypeIds.T_short:
return JIntLiteral.get(constant.shortValue());
- case Constant.T_char:
+ case TypeIds.T_char:
return JCharLiteral.get(constant.charValue());
- case Constant.T_float:
+ case TypeIds.T_float:
return JFloatLiteral.get(constant.floatValue());
- case Constant.T_double:
+ case TypeIds.T_double:
return JDoubleLiteral.get(constant.doubleValue());
case Constant.T_boolean:
return JBooleanLiteral.get(constant.booleanValue());
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/HandleCrossFragmentReferences.java b/dev/core/src/com/google/gwt/dev/jjs/impl/HandleCrossFragmentReferences.java
index 35e21c6..6c0490b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/HandleCrossFragmentReferences.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/HandleCrossFragmentReferences.java
@@ -126,9 +126,9 @@
@Override
public void endVisit(JsFunction x, JsContext ctx) {
if (namesToPredefine.contains(x.getName())) {
- JsBinaryOperation asg = new JsBinaryOperation(x.getSourceInfo(),
- JsBinaryOperator.ASG, makeRefViaJslink(x.getName(),
- x.getSourceInfo()), x);
+ JsBinaryOperation asg =
+ new JsBinaryOperation(x.getSourceInfo(), JsBinaryOperator.ASG, makeRefViaJslink(x
+ .getName(), x.getSourceInfo()), x);
x.setName(null);
ctx.replaceMe(asg);
}
@@ -169,9 +169,9 @@
// The var was predefined
if (var.getInitExpr() != null) {
// If it has an initializer, add an assignment statement
- JsBinaryOperation asg = new JsBinaryOperation(var.getSourceInfo(),
- JsBinaryOperator.ASG, makeRefViaJslink(var.getName(),
- var.getSourceInfo()), var.getInitExpr());
+ JsBinaryOperation asg =
+ new JsBinaryOperation(var.getSourceInfo(), JsBinaryOperator.ASG, makeRefViaJslink(
+ var.getName(), var.getSourceInfo()), var.getInitExpr());
ctx.insertBefore(asg.makeStmt());
currentVar = null;
}
@@ -197,8 +197,7 @@
public static String PROP_PREDECLARE_VARS = "compiler.predeclare.cross.fragment.references";
- public static void exec(TreeLogger logger, JsProgram jsProgram,
- PropertyOracle[] propertyOracles) {
+ public static void exec(TreeLogger logger, JsProgram jsProgram, PropertyOracle[] propertyOracles) {
new HandleCrossFragmentReferences(logger, jsProgram, propertyOracles).execImpl();
}
@@ -213,9 +212,9 @@
private JsName jslink;
private final JsProgram jsProgram;
+ private final TreeLogger logger;
private final Set<JsName> namesToPredefine = new LinkedHashSet<JsName>();
private final PropertyOracle[] propertyOracles;
- private final TreeLogger logger;
private HandleCrossFragmentReferences(TreeLogger logger, JsProgram jsProgram,
PropertyOracle[] propertyOracles) {
@@ -276,8 +275,7 @@
defineJsLink();
FindNameReferences findNameReferences = new FindNameReferences();
findNameReferences.accept(jsProgram);
- chooseNamesToPredefine(findNameReferences.islandsDefining,
- findNameReferences.islandsUsing);
+ chooseNamesToPredefine(findNameReferences.islandsDefining, findNameReferences.islandsUsing);
new RewriteDeclsAndRefs().accept(jsProgram);
}
@@ -288,8 +286,8 @@
private boolean shouldPredeclareReferences() {
for (PropertyOracle props : propertyOracles) {
try {
- String propValue = props.getSelectionProperty(logger,
- PROP_PREDECLARE_VARS).getCurrentValue();
+ String propValue =
+ props.getSelectionProperty(logger, PROP_PREDECLARE_VARS).getCurrentValue();
if (Boolean.parseBoolean(propValue)) {
return true;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ImplementClassLiteralsAsFields.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ImplementClassLiteralsAsFields.java
index d6b6a2e..511dbc6 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ImplementClassLiteralsAsFields.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ImplementClassLiteralsAsFields.java
@@ -26,6 +26,7 @@
import com.google.gwt.dev.jjs.ast.JDeclaredType;
import com.google.gwt.dev.jjs.ast.JEnumType;
import com.google.gwt.dev.jjs.ast.JField;
+import com.google.gwt.dev.jjs.ast.JField.Disposition;
import com.google.gwt.dev.jjs.ast.JFieldRef;
import com.google.gwt.dev.jjs.ast.JInterfaceType;
import com.google.gwt.dev.jjs.ast.JLiteral;
@@ -39,7 +40,6 @@
import com.google.gwt.dev.jjs.ast.JProgram;
import com.google.gwt.dev.jjs.ast.JStringLiteral;
import com.google.gwt.dev.jjs.ast.JType;
-import com.google.gwt.dev.jjs.ast.JField.Disposition;
import com.google.gwt.dev.jjs.ast.js.JsniMethodRef;
import com.google.gwt.dev.util.log.speedtracer.CompilerEventType;
import com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger;
@@ -281,8 +281,7 @@
if (type instanceof JArrayType) {
JArrayType aType = (JArrayType) type;
if (program.isJavaScriptObject(aType.getLeafType())) {
- return program.getTypeArray(program.getJavaScriptObject(),
- aType.getDims());
+ return program.getTypeArray(program.getJavaScriptObject(), aType.getDims());
}
}
@@ -290,7 +289,7 @@
}
/**
- * Resolve a class literal field. Takes the form:
+ * Resolve a class literal field. Takes the form:
*
* <pre>
* class ClassLiteralHolder {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ImplicitUpcastAnalyzer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ImplicitUpcastAnalyzer.java
index a84cb64..5a1b0fa 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ImplicitUpcastAnalyzer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ImplicitUpcastAnalyzer.java
@@ -38,26 +38,26 @@
import java.util.List;
/**
- * This class will identify instances of an implicit upcast between non-primitive
- * types, and call the overridable processImplicitUpcast method.
+ * This class will identify instances of an implicit upcast between
+ * non-primitive types, and call the overridable processImplicitUpcast method.
*
- * TODO(jbrosenberg): Consider extending to handle implicit upcasts between primitive types.
- * This is not as straightforward as for reference types, because primitives
- * can be boxed and unboxed implicitly as well.
+ * TODO(jbrosenberg): Consider extending to handle implicit upcasts between
+ * primitive types. This is not as straightforward as for reference types,
+ * because primitives can be boxed and unboxed implicitly as well.
*/
public class ImplicitUpcastAnalyzer extends JVisitor {
-
+
protected JMethod currentMethod;
- private final JType throwableType;
private final JType javaScriptObjectType;
private final JType nullType;
-
+ private final JType throwableType;
+
public ImplicitUpcastAnalyzer(JProgram program) {
this.throwableType = program.getIndexedType("Throwable");
this.javaScriptObjectType = program.getJavaScriptObject();
this.nullType = program.getTypeNull();
}
-
+
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
if (x.isAssignment()) {
@@ -66,33 +66,32 @@
processIfTypesNotEqual(nullType, x.getLhs().getType(), x.getSourceInfo());
} else if (x.getLhs().getType() == nullType) {
processIfTypesNotEqual(nullType, x.getRhs().getType(), x.getSourceInfo());
- } else if (x.getOp() == JBinaryOperator.CONCAT ||
- x.getOp() == JBinaryOperator.EQ ||
- x.getOp() == JBinaryOperator.NEQ) {
+ } else if (x.getOp() == JBinaryOperator.CONCAT || x.getOp() == JBinaryOperator.EQ
+ || x.getOp() == JBinaryOperator.NEQ) {
/*
* Since we are not attempting to handle detection of upcasts between
- * primitive types, we limit handling here to CONCAT, EQ and NEQ.
- * Need to do both directions.
+ * primitive types, we limit handling here to CONCAT, EQ and NEQ. Need to
+ * do both directions.
*/
processIfTypesNotEqual(x.getLhs().getType(), x.getRhs().getType(), x.getSourceInfo());
processIfTypesNotEqual(x.getRhs().getType(), x.getLhs().getType(), x.getSourceInfo());
}
}
-
+
@Override
public void endVisit(JConditional x, Context ctx) {
processIfTypesNotEqual(x.getThenExpr().getType(), x.getType(), x.getSourceInfo());
processIfTypesNotEqual(x.getElseExpr().getType(), x.getType(), x.getSourceInfo());
}
-
+
@Override
public void endVisit(JDeclarationStatement x, Context ctx) {
if (x.getInitializer() != null) {
- processIfTypesNotEqual(x.getInitializer().getType(),
- x.getVariableRef().getType(), x.getSourceInfo());
+ processIfTypesNotEqual(x.getInitializer().getType(), x.getVariableRef().getType(), x
+ .getSourceInfo());
}
}
-
+
@Override
public void endVisit(JField x, Context ctx) {
if (x.getInitializer() == null && !x.isFinal()) {
@@ -102,7 +101,7 @@
}
}
}
-
+
@Override
public void endVisit(JMethod x, Context ctx) {
// check for upcast in return type as compared to an overridden method
@@ -112,27 +111,27 @@
// overridden methods are visited, don't want to do redundant work
processIfTypesNotEqual(x.getType(), overrides.get(0).getType(), x.getSourceInfo());
}
-
+
if (x.getBody() != null && x.getBody().isNative()) {
/*
- * Check if this method has a native (jsni) method body, in which case
- * all arguments passed in are implicitly cast to JavaScriptObject
- */
+ * Check if this method has a native (jsni) method body, in which case all
+ * arguments passed in are implicitly cast to JavaScriptObject
+ */
List<JParameter> params = x.getParams();
for (int i = 0; i < params.size(); i++) {
processIfTypesNotEqual(params.get(i).getType(), javaScriptObjectType, x.getSourceInfo());
}
-
+
/*
- * Check if this method has a non-void return type, in which case
- * it will be implicitly cast from JavaScriptObject
+ * Check if this method has a non-void return type, in which case it will
+ * be implicitly cast from JavaScriptObject
*/
if (x.getType() != JPrimitiveType.VOID) {
processIfTypesNotEqual(javaScriptObjectType, x.getType(), x.getSourceInfo());
}
}
}
-
+
@Override
public void endVisit(JMethodCall x, Context ctx) {
// check for upcast in argument passing
@@ -146,21 +145,7 @@
}
}
}
-
- @Override
- public void endVisit(JsniMethodRef x, Context ctx) {
- // the return type of this method ref will be cast to JavaScriptObject
- if (x.getTarget().getType() != JPrimitiveType.VOID) {
- processIfTypesNotEqual(x.getTarget().getType(), javaScriptObjectType, x.getSourceInfo());
- }
-
- // check referenced method's params, which are passed as JavaScriptObjects
- List<JParameter> params = x.getTarget().getParams();
- for (int i = 0; i < params.size(); i++) {
- processIfTypesNotEqual(javaScriptObjectType, params.get(i).getType(), x.getSourceInfo());
- }
- }
-
+
@Override
public void endVisit(JReturnStatement x, Context ctx) {
if (x.getExpr() != null) {
@@ -168,7 +153,21 @@
processIfTypesNotEqual(x.getExpr().getType(), currentMethod.getType(), x.getSourceInfo());
}
}
-
+
+ @Override
+ public void endVisit(JsniMethodRef x, Context ctx) {
+ // the return type of this method ref will be cast to JavaScriptObject
+ if (x.getTarget().getType() != JPrimitiveType.VOID) {
+ processIfTypesNotEqual(x.getTarget().getType(), javaScriptObjectType, x.getSourceInfo());
+ }
+
+ // check referenced method's params, which are passed as JavaScriptObjects
+ List<JParameter> params = x.getTarget().getParams();
+ for (int i = 0; i < params.size(); i++) {
+ processIfTypesNotEqual(javaScriptObjectType, params.get(i).getType(), x.getSourceInfo());
+ }
+ }
+
@Override
public void endVisit(JThrowStatement x, Context ctx) {
// all things thrown are upcast to a Throwable
@@ -178,16 +177,17 @@
}
processIfTypesNotEqual(type, throwableType, x.getSourceInfo());
}
-
+
@Override
public boolean visit(JMethod x, Context ctx) {
// save this, so can use it later for checking JReturnStatement
currentMethod = x;
return true;
}
-
+
/**
* An overriding method will be called for each detected implicit upcast.
+ *
* @param fromType
* @param destType
*/
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JavaAndJavaScript.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JavaAndJavaScript.java
index 7526b14..7c75cc7 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JavaAndJavaScript.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JavaAndJavaScript.java
@@ -23,11 +23,12 @@
*/
public class JavaAndJavaScript {
public final JProgram jprogram;
- public final JsProgram jsprogram;
public final String[] jscode;
+ public final JsProgram jsprogram;
public final JavaToJavaScriptMap map;
- public JavaAndJavaScript(JProgram jprogram, JsProgram jsprogram, String[] jscode, JavaToJavaScriptMap map) {
+ public JavaAndJavaScript(JProgram jprogram, JsProgram jsprogram, String[] jscode,
+ JavaToJavaScriptMap map) {
this.jprogram = jprogram;
this.jsprogram = jsprogram;
this.jscode = jscode;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JavaPrecedenceVisitor.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JavaPrecedenceVisitor.java
index de3bd4c..d3b4503 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JavaPrecedenceVisitor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JavaPrecedenceVisitor.java
@@ -60,7 +60,8 @@
JavaPrecedenceVisitor visitor = new JavaPrecedenceVisitor();
visitor.accept(expression);
if (visitor.answer < 0) {
- throw new InternalCompilerException("Precedence must be >= 0 (" + expression + ") " + expression.getClass());
+ throw new InternalCompilerException("Precedence must be >= 0 (" + expression + ") "
+ + expression.getClass());
}
return visitor.answer;
}
@@ -143,6 +144,13 @@
}
@Override
+ public boolean visit(JGwtCreate x, Context ctx) {
+ // It's a method call.
+ answer = 0;
+ return false;
+ }
+
+ @Override
public boolean visit(JInstanceOf of, Context ctx) {
answer = 6;
return false;
@@ -173,13 +181,6 @@
}
@Override
- public boolean visit(JGwtCreate x, Context ctx) {
- // It's a method call.
- answer = 0;
- return false;
- }
-
- @Override
public boolean visit(JMultiExpression x, Context ctx) {
answer = 14;
return false;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JsAbstractTextTransformer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JsAbstractTextTransformer.java
index 25ea9cd..20b9c42 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JsAbstractTextTransformer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JsAbstractTextTransformer.java
@@ -1,12 +1,12 @@
/*
* Copyright 2009 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -29,16 +29,16 @@
protected StatementRanges statementRanges;
- public JsAbstractTextTransformer(String js, StatementRanges statementRanges) {
- this.js = js;
- this.statementRanges = statementRanges;
- }
-
public JsAbstractTextTransformer(JsAbstractTextTransformer xformer) {
this.js = xformer.getJs();
this.statementRanges = xformer.getStatementRanges();
}
+ public JsAbstractTextTransformer(String js, StatementRanges statementRanges) {
+ this.js = js;
+ this.statementRanges = statementRanges;
+ }
+
public abstract void exec();
public String getJs() {
@@ -49,15 +49,14 @@
return statementRanges;
}
- protected void addStatement(String code, StringBuilder newJs,
- ArrayList<Integer> starts, ArrayList<Integer> ends) {
+ protected void addStatement(String code, StringBuilder newJs, ArrayList<Integer> starts,
+ ArrayList<Integer> ends) {
beginStatement(newJs, starts);
newJs.append(code);
endStatement(newJs, ends);
}
- protected void beginStatement(StringBuilder newJs,
- ArrayList<Integer> starts) {
+ protected void beginStatement(StringBuilder newJs, ArrayList<Integer> starts) {
starts.add(newJs.length());
}
@@ -87,7 +86,7 @@
/**
* Called if any operations need to be performed after all statements have
* been processed.
- *
+ *
* @param newJs
* @param starts
* @param ends
@@ -97,8 +96,7 @@
}
protected String getJsForRange(int stmtIndex) {
- return js.substring(statementRanges.start(stmtIndex),
- statementRanges.end(stmtIndex));
+ return js.substring(statementRanges.start(stmtIndex), statementRanges.end(stmtIndex));
}
/**
@@ -112,21 +110,17 @@
ArrayList<Integer> ends = new ArrayList<Integer>();
beginStatements(newJs, starts, ends);
- for (int i = 0; i < stmtIndices.length; i++) {
- String code = getJsForRange(stmtIndices[i]);
+ for (int stmtIndice : stmtIndices) {
+ String code = getJsForRange(stmtIndice);
addStatement(code, newJs, starts, ends);
}
endStatements(newJs, starts, ends);
- assert
- starts.size() == ends.size() :
- "Size mismatch between start and" + " end statement ranges.";
- assert starts.get(0) == 0 && ends.get(ends.size() - 1) ==
- newJs.length() :
- "statement ranges don't cover entire JS output string.";
+ assert starts.size() == ends.size() : "Size mismatch between start and"
+ + " end statement ranges.";
+ assert starts.get(0) == 0 && ends.get(ends.size() - 1) == newJs.length() : "statement ranges don't cover entire JS output string.";
- StandardStatementRanges newRanges = new StandardStatementRanges(starts,
- ends);
+ StandardStatementRanges newRanges = new StandardStatementRanges(starts, ends);
js = newJs.toString();
statementRanges = newRanges;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JsFunctionClusterer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JsFunctionClusterer.java
index f18cda9..6bef7d4 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JsFunctionClusterer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JsFunctionClusterer.java
@@ -35,12 +35,12 @@
/**
* Used by isFunctionDeclaration to check a statement is a function
- * declaration or not. This should match standard declarations,
- * such as "function a() { ... }" and "jslink.a=function() { ... }".
- * The latter form is typically emitted by the cross-site linker.
+ * declaration or not. This should match standard declarations, such as
+ * "function a() { ... }" and "jslink.a=function() { ... }". The latter form
+ * is typically emitted by the cross-site linker.
*/
- private static final Pattern functionDeclarationPattern =
- Pattern.compile("function |[a-zA-Z][.$_a-zA-Z0-9]*=function");
+ private static final Pattern functionDeclarationPattern = Pattern
+ .compile("function |[a-zA-Z][.$_a-zA-Z0-9]*=function");
/**
* Functions which have an edit-distance greater than this limit are
@@ -49,8 +49,8 @@
private static final int MAX_DISTANCE_LIMIT = 100;
/**
- * Maximum number of functions to search for minimal edit-distance
- * before giving up.
+ * Maximum number of functions to search for minimal edit-distance before
+ * giving up.
*/
private static final int SEARCH_LIMIT = 10;
@@ -99,7 +99,7 @@
// get the last outputted function to match against
String currentCode = getJsForRange(clusteredIndices[currentFunction]);
final GeneralEditDistance editDistance =
- GeneralEditDistances.getLevenshteinDistance(currentCode);
+ GeneralEditDistances.getLevenshteinDistance(currentCode);
int bestIndex = 0;
int bestFunction = functionIndices.getFirst();
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JsIEBlockTextTransformer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JsIEBlockTextTransformer.java
index fd29391..5e41f97 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JsIEBlockTextTransformer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JsIEBlockTextTransformer.java
@@ -1,12 +1,12 @@
/*
* Copyright 2009 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -20,27 +20,27 @@
import java.util.ArrayList;
/**
- * Limits top-level blocks to MAX_BLOCK_SIZE statements.
+ * Limits top-level blocks to MAX_BLOCK_SIZE statements.
*/
public class JsIEBlockTextTransformer extends JsAbstractTextTransformer {
// uncomment to test
- // private static final int MAX_BLOCK_SIZE = 10;
+ // private static final int MAX_BLOCK_SIZE = 10;
private static final int MAX_BLOCK_SIZE = 1 << 15 - 1;
- private boolean doSplits;
-
private int currentStatementCount;
- public JsIEBlockTextTransformer(String js, StatementRanges statementRanges) {
- super(js, statementRanges);
- }
+ private boolean doSplits;
public JsIEBlockTextTransformer(JsAbstractTextTransformer xformer) {
super(xformer);
}
+ public JsIEBlockTextTransformer(String js, StatementRanges statementRanges) {
+ super(js, statementRanges);
+ }
+
/**
* Do not perform clustering, only fix up IE7 block issue.
*/
@@ -60,8 +60,7 @@
* Record start of statement, and optionally inject new open block.
*/
@Override
- protected void beginStatement(StringBuilder newJs,
- ArrayList<Integer> starts) {
+ protected void beginStatement(StringBuilder newJs, ArrayList<Integer> starts) {
if (doSplits && currentStatementCount == 0) {
super.beginStatement(newJs, starts);
newJs.append('{');
@@ -106,10 +105,8 @@
/**
* Close last block if it never filled.
*/
- private void optionallyCloseLastBlock(StringBuilder newJs,
- ArrayList<Integer> ends) {
- if (doSplits && currentStatementCount > 1
- && currentStatementCount < MAX_BLOCK_SIZE) {
+ private void optionallyCloseLastBlock(StringBuilder newJs, ArrayList<Integer> ends) {
+ if (doSplits && currentStatementCount > 1 && currentStatementCount < MAX_BLOCK_SIZE) {
newJs.append("}");
ends.add(newJs.length());
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JsniRefLookup.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JsniRefLookup.java
index b43a622..33684c5 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JsniRefLookup.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JsniRefLookup.java
@@ -62,8 +62,7 @@
if (!className.equals("null")) {
type = program.getTypeFromJsniRef(className);
if (type == null) {
- errorReporter.reportError("Unresolvable native reference to type '"
- + className + "'");
+ errorReporter.reportError("Unresolvable native reference to type '" + className + "'");
return null;
}
}
@@ -95,15 +94,16 @@
}
}
- errorReporter.reportError("Unresolvable native reference to field '"
- + fieldName + "' in type '" + className + "'");
+ errorReporter.reportError("Unresolvable native reference to field '" + fieldName
+ + "' in type '" + className + "'");
return null;
} else if (type instanceof JPrimitiveType) {
errorReporter.reportError("May not refer to methods on primitive types");
return null;
} else {
// look for a method
- LinkedHashMap<String, LinkedHashMap<String, JMethod>> matchesBySig = new LinkedHashMap<String, LinkedHashMap<String, JMethod>>();
+ LinkedHashMap<String, LinkedHashMap<String, JMethod>> matchesBySig =
+ new LinkedHashMap<String, LinkedHashMap<String, JMethod>>();
String methodName = ref.memberName();
String jsniSig = ref.memberSignature();
if (type == null) {
@@ -111,8 +111,7 @@
return program.getNullMethod();
}
} else {
- findMostDerivedMembers(matchesBySig, (JDeclaredType) type, methodName,
- true);
+ findMostDerivedMembers(matchesBySig, (JDeclaredType) type, methodName, true);
LinkedHashMap<String, JMethod> matches = matchesBySig.get(jsniSig);
if (matches != null && matches.size() == 1) {
/*
@@ -131,8 +130,8 @@
// Not found; signal an error
if (matchesBySig.isEmpty()) {
- errorReporter.reportError("Unresolvable native reference to method '"
- + methodName + "' in type '" + className + "'");
+ errorReporter.reportError("Unresolvable native reference to method '" + methodName
+ + "' in type '" + className + "'");
return null;
} else {
StringBuilder suggestList = new StringBuilder();
@@ -148,9 +147,8 @@
suggestList.append(comma + "'" + almost + "'");
comma = ", ";
}
- errorReporter.reportError("Unresolvable native reference to method '"
- + methodName + "' in type '" + className + "' (did you mean "
- + suggestList.toString() + "?)");
+ errorReporter.reportError("Unresolvable native reference to method '" + methodName
+ + "' in type '" + className + "' (did you mean " + suggestList.toString() + "?)");
return null;
}
}
@@ -164,8 +162,7 @@
* @param refSig The string used to refer to that member, possibly shortened
* @param fullSig The fully qualified signature for that member
*/
- private static void addMember(
- LinkedHashMap<String, LinkedHashMap<String, JMethod>> matchesBySig,
+ private static void addMember(LinkedHashMap<String, LinkedHashMap<String, JMethod>> matchesBySig,
JMethod member, String refSig, String fullSig) {
LinkedHashMap<String, JMethod> matchesByFullSig = matchesBySig.get(refSig);
if (matchesByFullSig == null) {
@@ -182,9 +179,8 @@
* methods.
*/
private static void findMostDerivedMembers(
- LinkedHashMap<String, LinkedHashMap<String, JMethod>> matchesBySig,
- JDeclaredType targetType, String memberName,
- boolean addConstructorsAndPrivates) {
+ LinkedHashMap<String, LinkedHashMap<String, JMethod>> matchesBySig, JDeclaredType targetType,
+ String memberName, boolean addConstructorsAndPrivates) {
/*
* Analyze superclasses and interfaces first. More derived members will thus
* be seen later.
@@ -192,8 +188,7 @@
if (targetType instanceof JClassType) {
JClassType targetClass = (JClassType) targetType;
if (targetClass.getSuperClass() != null) {
- findMostDerivedMembers(matchesBySig, targetClass.getSuperClass(),
- memberName, false);
+ findMostDerivedMembers(matchesBySig, targetClass.getSuperClass(), memberName, false);
}
}
for (JDeclaredType intf : targetType.getImplements()) {
@@ -222,8 +217,7 @@
continue;
}
String fullSig = JProgram.getJsniSig(method, false);
- String wildcardSig = method.getName() + "("
- + JsniRef.WILDCARD_PARAM_LIST + ")";
+ String wildcardSig = method.getName() + "(" + JsniRef.WILDCARD_PARAM_LIST + ")";
addMember(matchesBySig, method, fullSig, fullSig);
addMember(matchesBySig, method, wildcardSig, fullSig);
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/JsoDevirtualizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/JsoDevirtualizer.java
index 2ef127c..ef77843 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/JsoDevirtualizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/JsoDevirtualizer.java
@@ -21,7 +21,6 @@
import com.google.gwt.dev.jjs.ast.JClassType;
import com.google.gwt.dev.jjs.ast.JConditional;
import com.google.gwt.dev.jjs.ast.JDeclaredType;
-import com.google.gwt.dev.jjs.ast.JExpression;
import com.google.gwt.dev.jjs.ast.JLocal;
import com.google.gwt.dev.jjs.ast.JLocalRef;
import com.google.gwt.dev.jjs.ast.JMethod;
@@ -53,19 +52,21 @@
*/
private class RewriteVirtualDispatches extends JModVisitor {
+ /**
+ * A method call at this point can be one of 5 things:
+ * <ol>
+ * <li>a dual dispatch interface</li>
+ * <li>a single dispatch trough single-jso interface</li>
+ * <li>a java.lang.Object override from JavaScriptObject</li>
+ * <li>a regular dispatch (no JSOs involved or static JSO call)</li>
+ * <li>in draftMode, a 'static' virtual JSO call that hasn't been made
+ * static yet.</li>
+ * </ol>
+ */
@Override
public void endVisit(JMethodCall x, Context ctx) {
JMethod method = x.getTarget();
JMethod newMethod;
- /**
- * A method call at this point can be one of5 things:
- * 1) a dual dispatch interface
- * 2) a single dispatch trough single-jso interface
- * 3) a java.lang.Object override from JavaScriptObject
- * 4) a regular dispatch (no JSOs involved or static JSO call)
- * 5) in draftMode, a 'static' virtual JSO call that hasn't been
- * made static yet.
- */
JDeclaredType targetType = method.getEnclosingType();
if (targetType == null) {
@@ -78,7 +79,7 @@
JType instanceType = x.getInstance().getType();
// if the instance can't possibly be a JSO, don't devirtualize
if (instanceType != program.getTypeJavaLangObject()
- && !program.typeOracle.canBeJavaScriptObject(instanceType)) {
+ && !program.typeOracle.canBeJavaScriptObject(instanceType)) {
return;
}
@@ -86,8 +87,8 @@
// already did this one before
newMethod = polyMethodToJsoMethod.get(method);
} else if (program.typeOracle.isDualJsoInterface(targetType)) {
- JMethod overridingMethod = findOverridingMethod(method,
- program.typeOracle.getSingleJsoImpl(targetType));
+ JMethod overridingMethod =
+ findOverridingMethod(method, program.typeOracle.getSingleJsoImpl(targetType));
assert overridingMethod != null;
JMethod jsoStaticImpl = getStaticImpl(overridingMethod);
@@ -97,17 +98,16 @@
// It's a virtual JSO dispatch, usually occurs in draftCompile
newMethod = getStaticImpl(method);
polyMethodToJsoMethod.put(method, newMethod);
- } else if (program.typeOracle.isSingleJsoImpl(targetType)) {
+ } else if (program.typeOracle.isSingleJsoImpl(targetType)) {
// interface dispatch with single implementing JSO concrete type
- JMethod overridingMethod = findOverridingMethod(method,
- program.typeOracle.getSingleJsoImpl(targetType));
+ JMethod overridingMethod =
+ findOverridingMethod(method, program.typeOracle.getSingleJsoImpl(targetType));
assert overridingMethod != null;
newMethod = getStaticImpl(overridingMethod);
polyMethodToJsoMethod.put(method, newMethod);
} else if (targetType == program.getTypeJavaLangObject()) {
// it's a java.lang.Object overriden method in JSO
- JMethod overridingMethod = findOverridingMethod(method,
- program.getJavaScriptObject());
+ JMethod overridingMethod = findOverridingMethod(method, program.getJavaScriptObject());
if (overridingMethod != null) {
JMethod jsoStaticImpl = getStaticImpl(overridingMethod);
newMethod = getOrCreateDevirtualMethod(x, jsoStaticImpl);
@@ -145,16 +145,17 @@
protected Map<JMethod, JMethod> polyMethodToJsoMethod = new HashMap<JMethod, JMethod>();
/**
- * Contains the set of devirtualizing methods that replace polymorphic calls
- * to Object methods.
- */
- private Map<JMethod, JMethod> polyMethodToDevirtualMethods = new HashMap<JMethod, JMethod>();
-
- /**
* Contains the Cast.isJavaObject method.
*/
private final JMethod isJavaObjectMethod;
+ /**
+ * Contains the set of devirtualizing methods that replace polymorphic calls
+ * to Object methods.
+ */
+ private final Map<JMethod, JMethod> polyMethodToDevirtualMethods =
+ new HashMap<JMethod, JMethod>();
+
private final JProgram program;
private final CreateStaticImplsVisitor staticImplCreator;
@@ -193,73 +194,71 @@
}
/**
- * Create a conditional method to discriminate between static and virtual
- * dispatch.
- *
- * <pre>
+ * Create a conditional method to discriminate between static and virtual
+ * dispatch.
+ *
+ * <pre>
* static boolean equals__devirtual$(Object this, Object other) {
* return Cast.isJavaObject(this) ? this.equals(other) : JavaScriptObject.equals$(this, other);
* }
* </pre>
- */
- private JMethod getOrCreateDevirtualMethod(JMethodCall polyMethodCall,
- JMethod jsoImpl) {
+ */
+ private JMethod getOrCreateDevirtualMethod(JMethodCall polyMethodCall, JMethod jsoImpl) {
JMethod polyMethod = polyMethodCall.getTarget();
/**
- * TODO(cromwellian) generate a inlined expression instead of Method
- * Because devirtualization happens after optimization, the devirtual
- * methods don't optimize well in the JS pass. Consider "inlining" a
- * hand optimized devirtual method at callsites instead of a JMethodCall.
- * As a bonus, the inlined code can be specialized for each callsite, for
- * example, if there are no side effects, then there's no need for a
- * temporary. Or, if the instance can't possibly be java.lang.String,
- * then the JSO check becomes a cheaper check for typeMarker.
+ * TODO(cromwellian) generate a inlined expression instead of Method Because
+ * devirtualization happens after optimization, the devirtual methods don't
+ * optimize well in the JS pass. Consider "inlining" a hand optimized
+ * devirtual method at callsites instead of a JMethodCall. As a bonus, the
+ * inlined code can be specialized for each callsite, for example, if there
+ * are no side effects, then there's no need for a temporary. Or, if the
+ * instance can't possibly be java.lang.String, then the JSO check becomes a
+ * cheaper check for typeMarker.
*/
if (polyMethodToDevirtualMethods.containsKey(polyMethod)) {
return polyMethodToDevirtualMethods.get(polyMethod);
}
JClassType jsoType = program.getJavaScriptObject();
- SourceInfo sourceInfo = jsoType.getSourceInfo()
- .makeChild(SourceOrigin.UNKNOWN);
+ SourceInfo sourceInfo = jsoType.getSourceInfo().makeChild(SourceOrigin.UNKNOWN);
// Create the new method.
String name = polyMethod.getName() + "__devirtual$";
- JMethod newMethod = program.createMethod(sourceInfo, name, jsoType,
- polyMethod.getType(), false, true, true, false, false);
+ JMethod newMethod =
+ program.createMethod(sourceInfo, name, jsoType, polyMethod.getType(), false, true, true,
+ false, false);
newMethod.setSynthetic();
// Setup parameters.
- JParameter thisParam = JProgram.createParameter(sourceInfo, "this$static",
- program.getTypeJavaLangObject(), true, true, newMethod);
+ JParameter thisParam =
+ JProgram.createParameter(sourceInfo, "this$static", program.getTypeJavaLangObject(), true,
+ true, newMethod);
for (JParameter oldParam : polyMethod.getParams()) {
- JProgram.createParameter(sourceInfo, oldParam.getName(),
- oldParam.getType(), true, false, newMethod);
+ JProgram.createParameter(sourceInfo, oldParam.getName(), oldParam.getType(), true, false,
+ newMethod);
}
newMethod.freezeParamTypes();
newMethod.addThrownExceptions(polyMethod.getThrownExceptions());
sourceInfo.addCorrelation(sourceInfo.getCorrelator().by(newMethod));
// maybeJsoInvocation = this$static
- JExpression instance = polyMethodCall.getInstance();
- JLocal temp = JProgram.createLocal(sourceInfo, "maybeJsoInvocation",
- thisParam.getType(), true, (JMethodBody) newMethod.getBody());
+ JLocal temp =
+ JProgram.createLocal(sourceInfo, "maybeJsoInvocation", thisParam.getType(), true,
+ (JMethodBody) newMethod.getBody());
JMultiExpression multi = new JMultiExpression(sourceInfo);
// (maybeJsoInvocation = this$static, )
- multi.exprs.add(JProgram.createAssignmentStmt(sourceInfo,
- new JLocalRef(sourceInfo, temp),
+ multi.exprs.add(JProgram.createAssignmentStmt(sourceInfo, new JLocalRef(sourceInfo, temp),
new JParameterRef(sourceInfo, thisParam)).getExpr());
// Build from bottom up.
// isJavaObject(temp)
- JMethodCall condition = new JMethodCall(sourceInfo, null,
- isJavaObjectMethod);
+ JMethodCall condition = new JMethodCall(sourceInfo, null, isJavaObjectMethod);
condition.addArg(new JLocalRef(sourceInfo, temp));
// temp.method(args)
- JMethodCall thenValue = new JMethodCall(sourceInfo, new JLocalRef(
- sourceInfo, temp), polyMethod);
+ JMethodCall thenValue =
+ new JMethodCall(sourceInfo, new JLocalRef(sourceInfo, temp), polyMethod);
for (JParameter param : newMethod.getParams()) {
if (param != thisParam) {
thenValue.addArg(new JParameterRef(sourceInfo, param));
@@ -276,17 +275,15 @@
}
// isJavaObject(temp) ? temp.method(args) : jso$method(temp, args)
- JConditional conditional = new JConditional(sourceInfo,
- polyMethod.getType(),
- condition, thenValue, elseValue);
+ JConditional conditional =
+ new JConditional(sourceInfo, polyMethod.getType(), condition, thenValue, elseValue);
multi.exprs.add(conditional);
- JReturnStatement returnStatement = new JReturnStatement(sourceInfo,
- multi);
+ JReturnStatement returnStatement = new JReturnStatement(sourceInfo, multi);
((JMethodBody) newMethod.getBody()).getBlock().addStmt(returnStatement);
polyMethodToDevirtualMethods.put(polyMethod, newMethod);
-
+
return newMethod;
}
@@ -300,4 +297,3 @@
return staticImpl;
}
}
-
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/LongCastNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/LongCastNormalizer.java
index e82d54d..52df25c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/LongCastNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/LongCastNormalizer.java
@@ -100,8 +100,8 @@
JExpression newLhs = checkAndReplace(x.getLhs(), lhsType);
JExpression newRhs = checkAndReplace(x.getRhs(), rhsType);
if (newLhs != x.getLhs() || newRhs != x.getRhs()) {
- JBinaryOperation binOp = new JBinaryOperation(x.getSourceInfo(),
- resultType, op, newLhs, newRhs);
+ JBinaryOperation binOp =
+ new JBinaryOperation(x.getSourceInfo(), resultType, op, newLhs, newRhs);
ctx.replaceMe(binOp);
}
}
@@ -111,8 +111,8 @@
JExpression newThen = checkAndReplace(x.getThenExpr(), x.getType());
JExpression newElse = checkAndReplace(x.getElseExpr(), x.getType());
if (newThen != x.getThenExpr() || newElse != x.getElseExpr()) {
- JConditional newCond = new JConditional(x.getSourceInfo(), x.getType(),
- x.getIfTest(), newThen, newElse);
+ JConditional newCond =
+ new JConditional(x.getSourceInfo(), x.getType(), x.getIfTest(), newThen, newElse);
ctx.replaceMe(newCond);
}
}
@@ -123,8 +123,8 @@
if (init != null) {
init = checkAndReplace(init, x.getVariableRef().getType());
if (init != x.getInitializer()) {
- JDeclarationStatement newStmt = new JDeclarationStatement(
- x.getSourceInfo(), x.getVariableRef(), init);
+ JDeclarationStatement newStmt =
+ new JDeclarationStatement(x.getSourceInfo(), x.getVariableRef(), init);
ctx.replaceMe(newStmt);
}
}
@@ -171,8 +171,7 @@
if (expr != null) {
JExpression newExpr = checkAndReplace(expr, currentMethod.getType());
if (expr != newExpr) {
- JReturnStatement newStmt = new JReturnStatement(x.getSourceInfo(),
- newExpr);
+ JReturnStatement newStmt = new JReturnStatement(x.getSourceInfo(), newExpr);
ctx.replaceMe(newStmt);
}
}
@@ -211,8 +210,7 @@
}
private void execImpl() {
- ImplicitCastVisitor visitor = new ImplicitCastVisitor(
- program.getTypePrimitiveLong());
+ ImplicitCastVisitor visitor = new ImplicitCastVisitor(program.getTypePrimitiveLong());
visitor.accept(program);
}
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/LongEmulationNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/LongEmulationNormalizer.java
index 4a00988..42f5749 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/LongEmulationNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/LongEmulationNormalizer.java
@@ -70,20 +70,17 @@
case SHR:
case SHRU:
if (rhsType == longType) {
- throw new InternalCompilerException(
- "Expected right operand not to be of type long");
+ throw new InternalCompilerException("Expected right operand not to be of type long");
}
break;
default:
if (rhsType != longType) {
- throw new InternalCompilerException(
- "Expected right operand to be of type long");
+ throw new InternalCompilerException("Expected right operand to be of type long");
}
}
JMethod method = program.getIndexedMethod("LongLib." + methodName);
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method,
- x.getType());
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method, x.getType());
call.addArgs(x.getLhs(), x.getRhs());
ctx.replaceMe(call);
}
@@ -92,8 +89,7 @@
public void endVisit(JPostfixOperation x, Context ctx) {
JType argType = x.getArg().getType();
if (argType == longType) {
- throw new InternalCompilerException(
- "Postfix operations on longs should not reach here");
+ throw new InternalCompilerException("Postfix operations on longs should not reach here");
}
}
@@ -106,8 +102,7 @@
String methodName = getEmulationMethod(x.getOp());
JMethod method = program.getIndexedMethod("LongLib." + methodName);
- JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method,
- x.getType());
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method, x.getType());
call.addArg(x.getArg());
ctx.replaceMe(call);
}
@@ -151,8 +146,7 @@
case AND:
case OR:
- throw new InternalCompilerException(
- "AND and OR should not have long operands");
+ throw new InternalCompilerException("AND and OR should not have long operands");
case ASG:
// Nothing to do.
@@ -169,8 +163,7 @@
case ASG_BIT_AND:
case ASG_BIT_OR:
case ASG_BIT_XOR:
- throw new InternalCompilerException(
- "Modifying long ops should not reach here");
+ throw new InternalCompilerException("Modifying long ops should not reach here");
default:
throw new InternalCompilerException("Should not reach here");
}
@@ -180,13 +173,11 @@
switch (op) {
case INC:
case DEC:
- throw new InternalCompilerException(
- "Modifying long ops should not reach here");
+ throw new InternalCompilerException("Modifying long ops should not reach here");
case NEG:
return "neg";
case NOT:
- throw new InternalCompilerException(
- "NOT should not have a long operand");
+ throw new InternalCompilerException("NOT should not have a long operand");
case BIT_NOT:
return "not";
default:
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/MakeCallsStatic.java b/dev/core/src/com/google/gwt/dev/jjs/impl/MakeCallsStatic.java
index 0e9345a..aef2ca7 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/MakeCallsStatic.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/MakeCallsStatic.java
@@ -66,8 +66,6 @@
* most cases the polymorphic version can be pruned later.
*/
public class MakeCallsStatic {
- private static final String NAME = MakeCallsStatic.class.getSimpleName();
-
/**
* For all methods that should be made static, move the contents of the method
* to a new static method, and have the original (instance) method delegate to
@@ -109,8 +107,7 @@
private final JParameter thisParam;
private final Map<JParameter, JParameter> varMap;
- public RewriteMethodBody(JParameter thisParam,
- Map<JParameter, JParameter> varMap) {
+ public RewriteMethodBody(JParameter thisParam, Map<JParameter, JParameter> varMap) {
this.thisParam = thisParam;
this.varMap = varMap;
}
@@ -129,13 +126,18 @@
}
}
- private JProgram program;
+ private final JProgram program;
CreateStaticImplsVisitor(JProgram program) {
this.program = program;
}
@Override
+ public boolean visit(JConstructor x, Context ctx) {
+ throw new InternalCompilerException("Should not try to staticify constructors");
+ }
+
+ @Override
public boolean visit(JMethod x, Context ctx) {
// Let's do it!
JClassType enclosingType = (JClassType) x.getEnclosingType();
@@ -151,20 +153,22 @@
* Don't use the JProgram helper because it auto-adds the new method to
* its enclosing class.
*/
- JMethod newMethod = new JMethod(sourceInfo, newName, enclosingType,
- returnType, false, true, true, x.isPrivate());
+ JMethod newMethod =
+ new JMethod(sourceInfo, newName, enclosingType, returnType, false, true, true, x
+ .isPrivate());
newMethod.setSynthetic();
newMethod.addThrownExceptions(x.getThrownExceptions());
// Setup parameters; map from the old params to the new params
- JParameter thisParam = JParameter.create(sourceInfo, "this$static",
- enclosingType.getNonNull(), true, true, newMethod);
+ JParameter thisParam =
+ JParameter.create(sourceInfo, "this$static", enclosingType.getNonNull(), true, true,
+ newMethod);
Map<JParameter, JParameter> varMap = new IdentityHashMap<JParameter, JParameter>();
for (int i = 0; i < x.getParams().size(); ++i) {
JParameter oldVar = x.getParams().get(i);
- JParameter newVar = JParameter.create(oldVar.getSourceInfo(),
- oldVar.getName(), oldVar.getType(), oldVar.isFinal(), false,
- newMethod);
+ JParameter newVar =
+ JParameter.create(oldVar.getSourceInfo(), oldVar.getName(), oldVar.getType(), oldVar
+ .isFinal(), false, newMethod);
varMap.put(oldVar, newVar);
}
@@ -218,12 +222,6 @@
enclosingType.getMethods().add(myIndexInClass + 1, newMethod);
return false;
}
-
- @Override
- public boolean visit(JConstructor x, Context ctx) {
- throw new InternalCompilerException(
- "Should not try to staticify constructors");
- }
}
/**
@@ -245,8 +243,7 @@
}
// Did we already do this one?
- if (program.getStaticImpl(method) != null
- || toBeMadeStatic.contains(method)) {
+ if (program.getStaticImpl(method) != null || toBeMadeStatic.contains(method)) {
return;
}
@@ -323,8 +320,7 @@
@Override
public boolean visit(JMethod x, Context ctx) {
- currentMethodIsInitiallyLive = initiallyLive.getLiveFieldsAndMethods().contains(
- x);
+ currentMethodIsInitiallyLive = initiallyLive.getLiveFieldsAndMethods().contains(x);
return true;
}
@@ -335,9 +331,10 @@
}
}
+ private static final String NAME = MakeCallsStatic.class.getSimpleName();
+
public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new MakeCallsStatic(program).execImpl();
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/MethodCallTightener.java b/dev/core/src/com/google/gwt/dev/jjs/impl/MethodCallTightener.java
index 1f0205e..c92894f 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/MethodCallTightener.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/MethodCallTightener.java
@@ -1,12 +1,12 @@
/*
* Copyright 2007 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -36,13 +36,11 @@
* Update polymorphic method calls to tighter bindings based on the type of the
* qualifier. For a given polymorphic method call to a non-final target, see if
* the static type of the qualifer would let us target an override instead.
- *
+ *
* This is possible because the qualifier might have been tightened by
* {@link com.google.gwt.dev.jjs.impl.TypeTightener}.
*/
public class MethodCallTightener {
- public static final String NAME = MethodCallTightener.class.getSimpleName();
-
/**
* Updates polymorphic method calls to tighter bindings based on the type of
* the qualifier.
@@ -50,11 +48,6 @@
public class MethodCallTighteningVisitor extends JModVisitor {
@Override
- public void endVisit(JNewInstance x, Context ctx) {
- // Do not tighten new operations.
- }
-
- @Override
public void endVisit(JMethodCall x, Context ctx) {
JMethod method = x.getTarget();
JExpression instance = x.getInstance();
@@ -67,8 +60,7 @@
JReferenceType instanceType = ((JReferenceType) instance.getType()).getUnderlyingType();
JReferenceType enclosingType = method.getEnclosingType();
- if (instanceType == enclosingType
- || instanceType instanceof JInterfaceType) {
+ if (instanceType == enclosingType || instanceType instanceof JInterfaceType) {
// This method call is as tight as it can be for the type of the
// qualifier
return;
@@ -92,8 +84,8 @@
*/
JMethod foundMethod = null;
JClassType type;
- outer : for (type = (JClassType) instanceType; type != null
- && type != enclosingType; type = type.getSuperClass()) {
+ outer : for (type = (JClassType) instanceType; type != null && type != enclosingType; type =
+ type.getSuperClass()) {
for (JMethod methodIt : type.getMethods()) {
if (methodOverrides(methodIt, method)) {
foundMethod = methodIt;
@@ -110,21 +102,24 @@
* Replace the call to the original method with a call to the same method
* on the tighter type.
*/
- JMethodCall call = new JMethodCall(x.getSourceInfo(), x.getInstance(),
- foundMethod);
+ JMethodCall call = new JMethodCall(x.getSourceInfo(), x.getInstance(), foundMethod);
call.addArgs(x.getArgs());
ctx.replaceMe(call);
}
+ @Override
+ public void endVisit(JNewInstance x, Context ctx) {
+ // Do not tighten new operations.
+ }
+
/**
* Check whether <code>subMethod</code> overrides <code>supMethod</code>.
* For the purposes of this method, indirect overrides are considered
* overrides. For example, if method A.m overrides B.m, and B.m overrides
* C.m, then A.m is considered to override C.m. Additionally, implementing
- * an interface is considered
- * <q>overriding</q>
- * for the purposes of this method.
- *
+ * an interface is considered <q>overriding</q> for the purposes of this
+ * method.
+ *
*/
private boolean methodOverrides(JMethod subMethod, JMethod supMethod) {
if (subMethod.getParams().size() != supMethod.getParams().size()) {
@@ -142,9 +137,10 @@
}
}
+ public static final String NAME = MethodCallTightener.class.getSimpleName();
+
public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(
- CompilerEventType.OPTIMIZE, "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new MethodCallTightener(program).execImpl();
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/MethodInliner.java b/dev/core/src/com/google/gwt/dev/jjs/impl/MethodInliner.java
index edb1257..57c9069 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/MethodInliner.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/MethodInliner.java
@@ -57,8 +57,7 @@
/**
* Clones an expression, ensuring no local or this refs.
*/
- private static class CloneCalleeExpressionVisitor extends
- CloneExpressionVisitor {
+ private static class CloneCalleeExpressionVisitor extends CloneExpressionVisitor {
@Override
public boolean visit(JLocalRef x, Context ctx) {
throw new InternalCompilerException(
@@ -110,16 +109,14 @@
List<JStatement> stmts = body.getStatements();
if (method.getEnclosingType() != null
- && method.getEnclosingType().getMethods().get(0) == method
- && !stmts.isEmpty()) {
+ && method.getEnclosingType().getMethods().get(0) == method && !stmts.isEmpty()) {
// clinit() calls cannot be inlined unless they are empty
possibleToInline = false;
} else if (!body.getLocals().isEmpty()) {
// methods with local variables cannot be inlined
possibleToInline = false;
} else {
- JMultiExpression multi = createMultiExpressionFromBody(body,
- ignoringReturnValueFor == x);
+ JMultiExpression multi = createMultiExpressionFromBody(body, ignoringReturnValueFor == x);
if (multi != null) {
possibleToInline = tryInlineExpression(x, ctx, multi);
}
@@ -168,8 +165,7 @@
JMethod clinit = targetType.getMethods().get(0);
// If the clinit is a non-native, empty body we can optimize it out here
- if (!clinit.isNative()
- && (((JMethodBody) clinit.getBody())).getStatements().size() == 0) {
+ if (!clinit.isNative() && (((JMethodBody) clinit.getBody())).getStatements().size() == 0) {
return null;
}
@@ -181,8 +177,7 @@
* possible clinit. This is a precursor for inlining the remainder of a
* method.
*/
- private JMultiExpression createMultiExpressionForInstanceAndClinit(
- JMethodCall x) {
+ private JMultiExpression createMultiExpressionForInstanceAndClinit(JMethodCall x) {
JMultiExpression multi = new JMultiExpression(x.getSourceInfo());
// Any instance expression goes first (this can happen even with statics).
@@ -273,8 +268,7 @@
/**
* Inline a call to an expression.
*/
- private boolean tryInlineExpression(JMethodCall x, Context ctx,
- JMultiExpression targetExpr) {
+ private boolean tryInlineExpression(JMethodCall x, Context ctx, JMultiExpression targetExpr) {
/*
* Limit inlined methods to multiexpressions of length 2 for now. This
* handles the simple { return JVariableRef; } or { expression; return
@@ -295,8 +289,7 @@
// Make sure the expression we're about to inline doesn't include a call
// to the target method!
- RecursionCheckVisitor recursionCheckVisitor = new RecursionCheckVisitor(
- x.getTarget());
+ RecursionCheckVisitor recursionCheckVisitor = new RecursionCheckVisitor(x.getTarget());
recursionCheckVisitor.accept(targetExpr);
if (recursionCheckVisitor.isRecursive()) {
return false;
@@ -449,8 +442,7 @@
@Override
public void endVisit(JParameterRef x, Context ctx) {
- int paramIndex = methodCall.getTarget().getParams().indexOf(
- x.getParameter());
+ int paramIndex = methodCall.getTarget().getParams().indexOf(x.getParameter());
assert paramIndex != -1;
// Replace with a cloned call argument.
@@ -465,7 +457,7 @@
private static class RecursionCheckVisitor extends JVisitor {
private boolean isRecursive = false;
- private JMethod method;
+ private final JMethod method;
public RecursionCheckVisitor(JMethod method) {
this.method = method;
@@ -493,8 +485,7 @@
public static String NAME = MethodInliner.class.getSimpleName();
public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new MethodInliner(program).execImpl();
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/OptimizerStats.java b/dev/core/src/com/google/gwt/dev/jjs/impl/OptimizerStats.java
index 60611f2..abb475f 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/OptimizerStats.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/OptimizerStats.java
@@ -1,12 +1,12 @@
/*
* Copyright 2010 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -23,7 +23,7 @@
* Stores statistics on the results of running an optimizer pass.
*/
public class OptimizerStats {
- private List<OptimizerStats> children = new ArrayList<OptimizerStats>();
+ private final List<OptimizerStats> children = new ArrayList<OptimizerStats>();
private final String name;
private int numMods = 0;
private int numVisits = 0;
@@ -106,7 +106,7 @@
/**
* Increment the number of times the tree was modified.
- *
+ *
* @param numMods the number of changes made to the AST.
*/
public OptimizerStats recordModified(int numMods) {
@@ -135,8 +135,7 @@
int mods = getNumMods();
String ratioString = " ----";
if (visits > 0) {
- ratioString = String.format(
- "%5.2f", ((double) mods / (double) visits) * 100.0);
+ ratioString = String.format("%5.2f", ((double) mods / (double) visits) * 100.0);
}
String entry = String.format("%-6s%% (%6d/%6d)", ratioString, mods, visits);
builder.append(String.format("%12s: %-22s ", name, entry));
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/PostOptimizationCompoundAssignmentNormalizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/PostOptimizationCompoundAssignmentNormalizer.java
index a25fd54..9d7633c 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/PostOptimizationCompoundAssignmentNormalizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/PostOptimizationCompoundAssignmentNormalizer.java
@@ -29,8 +29,7 @@
* Normalize compound assignments as needed after optimization. Integer division
* and operations on longs need to be broken up.
*/
-public class PostOptimizationCompoundAssignmentNormalizer extends
- CompoundAssignmentNormalizer {
+public class PostOptimizationCompoundAssignmentNormalizer extends CompoundAssignmentNormalizer {
public static void exec(JProgram program) {
new PostOptimizationCompoundAssignmentNormalizer().accept(program);
}
@@ -44,11 +43,8 @@
JType rhsType = op.getRhs().getType();
if (lhsType != rhsType) {
// first widen binary op to encompass both sides, then add narrow cast
- return new JCastOperation(op.getSourceInfo(), lhsType,
- new JBinaryOperation(op.getSourceInfo(),
- widenType(lhsType, rhsType),
- op.getOp(),
- op.getLhs(), op.getRhs()));
+ return new JCastOperation(op.getSourceInfo(), lhsType, new JBinaryOperation(op
+ .getSourceInfo(), widenType(lhsType, rhsType), op.getOp(), op.getLhs(), op.getRhs()));
}
return op;
}
@@ -58,8 +54,7 @@
if (x.getType() == JPrimitiveType.LONG) {
return true;
}
- if (x.getOp() == JBinaryOperator.ASG_DIV
- && x.getType() != JPrimitiveType.FLOAT
+ if (x.getOp() == JBinaryOperator.ASG_DIV && x.getType() != JPrimitiveType.FLOAT
&& x.getType() != JPrimitiveType.DOUBLE) {
return true;
}
@@ -96,17 +91,18 @@
}
/**
- * Implements http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#26917
+ * Implements 5.6 Numeric Promotions.
+ *
+ * <pre>
+ * http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#26917
+ * </pre>
*/
private JType widenType(JType lhsType, JType rhsType) {
- if (lhsType == JPrimitiveType.DOUBLE ||
- rhsType == JPrimitiveType.DOUBLE) {
+ if (lhsType == JPrimitiveType.DOUBLE || rhsType == JPrimitiveType.DOUBLE) {
return JPrimitiveType.DOUBLE;
- } else if (lhsType == JPrimitiveType.FLOAT ||
- rhsType == JPrimitiveType.FLOAT) {
+ } else if (lhsType == JPrimitiveType.FLOAT || rhsType == JPrimitiveType.FLOAT) {
return JPrimitiveType.FLOAT;
- } else if (lhsType == JPrimitiveType.LONG ||
- rhsType == JPrimitiveType.LONG) {
+ } else if (lhsType == JPrimitiveType.LONG || rhsType == JPrimitiveType.LONG) {
return JPrimitiveType.LONG;
} else {
return JPrimitiveType.INT;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java b/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java
index 4cf1372..0ffdcf4 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java
@@ -88,7 +88,7 @@
* and null method, and drop assignments to pruned variables.
*/
private class CleanupRefsVisitor extends JModVisitor {
- private Stack<JExpression> lValues = new Stack<JExpression>();
+ private final Stack<JExpression> lValues = new Stack<JExpression>();
private final Map<JMethod, ArrayList<JParameter>> methodToOriginalParamsMap;
private final Set<? extends JNode> referencedNonTypes;
{
@@ -112,8 +112,8 @@
JVariableRef variableRef = (JVariableRef) lhs;
if (isVariablePruned(variableRef.getTarget())) {
// TODO: better null tracking; we might be missing some NPEs here.
- JExpression replacement = makeReplacementForAssignment(
- x.getSourceInfo(), variableRef, x.getRhs());
+ JExpression replacement =
+ makeReplacementForAssignment(x.getSourceInfo(), variableRef, x.getRhs());
ctx.replaceMe(replacement);
}
}
@@ -125,8 +125,8 @@
lValues.pop();
// The variable may have been pruned.
if (isVariablePruned(x.getVariableRef().getTarget())) {
- JExpression replacement = makeReplacementForAssignment(
- x.getSourceInfo(), x.getVariableRef(), x.getInitializer());
+ JExpression replacement =
+ makeReplacementForAssignment(x.getSourceInfo(), x.getVariableRef(), x.getInitializer());
ctx.replaceMe(replacement.makeStatement());
}
}
@@ -210,8 +210,9 @@
String ident = x.getIdent();
JField nullField = program.getNullField();
program.jsniMap.put(ident, nullField);
- JsniFieldRef nullFieldRef = new JsniFieldRef(x.getSourceInfo(), ident,
- nullField, x.getEnclosingType(), x.isLvalue());
+ JsniFieldRef nullFieldRef =
+ new JsniFieldRef(x.getSourceInfo(), ident, nullField, x.getEnclosingType(), x
+ .isLvalue());
ctx.replaceMe(nullFieldRef);
}
}
@@ -223,8 +224,8 @@
String ident = x.getIdent();
JMethod nullMethod = program.getNullMethod();
program.jsniMap.put(ident, nullMethod);
- JsniMethodRef nullMethodRef = new JsniMethodRef(x.getSourceInfo(),
- ident, nullMethod, program.getJavaScriptObject());
+ JsniMethodRef nullMethodRef =
+ new JsniMethodRef(x.getSourceInfo(), ident, nullMethod, program.getJavaScriptObject());
ctx.replaceMe(nullMethodRef);
}
}
@@ -259,8 +260,8 @@
return !referencedNonTypes.contains(variable);
}
- private JExpression makeReplacementForAssignment(SourceInfo info,
- JVariableRef variableRef, JExpression rhs) {
+ private JExpression makeReplacementForAssignment(SourceInfo info, JVariableRef variableRef,
+ JExpression rhs) {
// Replace with a multi, which may wind up empty.
JMultiExpression multi = new JMultiExpression(info);
@@ -284,8 +285,7 @@
}
}
- private void replaceForPrunedParameters(JMethodCall x, JMethodCall newCall,
- Context ctx) {
+ private void replaceForPrunedParameters(JMethodCall x, JMethodCall newCall, Context ctx) {
assert !x.getTarget().canBePolymorphic();
List<JParameter> originalParams = methodToOriginalParamsMap.get(x.getTarget());
JMultiExpression currentMulti = null;
@@ -328,7 +328,8 @@
* unreferenced methods and fields from their containing classes.
*/
private class PruneVisitor extends JModVisitor {
- private final Map<JMethod, ArrayList<JParameter>> methodToOriginalParamsMap = new HashMap<JMethod, ArrayList<JParameter>>();
+ private final Map<JMethod, ArrayList<JParameter>> methodToOriginalParamsMap =
+ new HashMap<JMethod, ArrayList<JParameter>>();
private final Set<? extends JNode> referencedNonTypes;
private final Set<? extends JReferenceType> referencedTypes;
@@ -359,8 +360,7 @@
for (int i = 0; i < type.getMethods().size(); ++i) {
JMethod method = type.getMethods().get(i);
- if (!methodIsReferenced(method)
- || pruneViaNoninstantiability(isInstantiated, method)) {
+ if (!methodIsReferenced(method) || pruneViaNoninstantiability(isInstantiated, method)) {
// Never prune clinit directly out of the class.
if (i > 0) {
type.removeMethod(i);
@@ -429,19 +429,15 @@
*/
JMethod staticImplFor = program.staticImplFor(x);
// Unless the instance method has already been pruned, of course.
- if (saveCodeGenTypes
- && staticImplFor != null
- && staticImplFor.getEnclosingType().getMethods().contains(
- staticImplFor)) {
+ if (saveCodeGenTypes && staticImplFor != null
+ && staticImplFor.getEnclosingType().getMethods().contains(staticImplFor)) {
// instance method is still live
return true;
}
- JsFunction func = x.isNative()
- ? ((JsniMethodBody) x.getBody()).getFunc() : null;
+ JsFunction func = x.isNative() ? ((JsniMethodBody) x.getBody()).getFunc() : null;
- ArrayList<JParameter> originalParams = new ArrayList<JParameter>(
- x.getParams());
+ ArrayList<JParameter> originalParams = new ArrayList<JParameter>(x.getParams());
for (int i = 0; i < x.getParams().size(); ++i) {
JParameter param = x.getParams().get(i);
@@ -479,8 +475,7 @@
}
for (Iterator<JDeclaredType> it = program.getDeclaredTypes().iterator(); it.hasNext();) {
JDeclaredType type = it.next();
- if (referencedTypes.contains(type)
- || program.typeOracle.isInstantiatedType(type)) {
+ if (referencedTypes.contains(type) || program.typeOracle.isInstantiatedType(type)) {
accept(type);
} else {
it.remove();
@@ -515,8 +510,7 @@
return false;
}
- private boolean pruneViaNoninstantiability(boolean isInstantiated,
- CanBeStatic it) {
+ private boolean pruneViaNoninstantiability(boolean isInstantiated, CanBeStatic it) {
return (!isInstantiated && !it.isStatic());
}
}
@@ -524,8 +518,7 @@
private static final String NAME = Pruner.class.getSimpleName();
public static OptimizerStats exec(JProgram program, boolean noSpecialTypes) {
- Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new Pruner(program, noSpecialTypes).execImpl();
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
@@ -562,9 +555,9 @@
instance = program.getLiteralNull();
}
- JFieldRef fieldRef = new JFieldRef(x.getSourceInfo(), instance,
- program.getNullField(), x.getEnclosingType(), primitiveTypeOrNullType(
- program, x.getType()));
+ JFieldRef fieldRef =
+ new JFieldRef(x.getSourceInfo(), instance, program.getNullField(), x.getEnclosingType(),
+ primitiveTypeOrNullType(program, x.getType()));
return fieldRef;
}
@@ -572,8 +565,7 @@
* Transform a call to a pruned instance method (or static impl) into a call
* to the null method, which will be used to replace <code>x</code>.
*/
- public static JMethodCall transformToNullMethodCall(JMethodCall x,
- JProgram program) {
+ public static JMethodCall transformToNullMethodCall(JMethodCall x, JProgram program) {
JExpression instance = x.getInstance();
List<JExpression> args = x.getArgs();
if (program.isStaticImpl(x.getTarget())) {
@@ -604,8 +596,9 @@
instance = program.getLiteralNull();
}
- JMethodCall newCall = new JMethodCall(x.getSourceInfo(), instance,
- program.getNullMethod(), primitiveTypeOrNullType(program, x.getType()));
+ JMethodCall newCall =
+ new JMethodCall(x.getSourceInfo(), instance, program.getNullMethod(),
+ primitiveTypeOrNullType(program, x.getType()));
// Retain the original arguments, they will be evaluated for side effects.
newCall.addArgs(args);
return newCall;
@@ -651,17 +644,17 @@
program.typeOracle.setInstantiatedTypes(livenessAnalyzer.getInstantiatedTypes());
- PruneVisitor pruner = new PruneVisitor(
- livenessAnalyzer.getReferencedTypes(),
- livenessAnalyzer.getLiveFieldsAndMethods());
+ PruneVisitor pruner =
+ new PruneVisitor(livenessAnalyzer.getReferencedTypes(), livenessAnalyzer
+ .getLiveFieldsAndMethods());
pruner.accept(program);
stats.recordModified(pruner.getNumMods());
if (!pruner.didChange()) {
break;
}
- CleanupRefsVisitor cleaner = new CleanupRefsVisitor(
- livenessAnalyzer.getLiveFieldsAndMethods(),
- pruner.getMethodToOriginalParamsMap());
+ CleanupRefsVisitor cleaner =
+ new CleanupRefsVisitor(livenessAnalyzer.getLiveFieldsAndMethods(), pruner
+ .getMethodToOriginalParamsMap());
cleaner.accept(program.getDeclaredTypes());
}
return stats;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/RecordRebinds.java b/dev/core/src/com/google/gwt/dev/jjs/impl/RecordRebinds.java
index 64ff60f..5a360c1 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/RecordRebinds.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/RecordRebinds.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -51,8 +51,8 @@
recordRebindsEvent.end();
}
- private final JProgram program;
private final Set<String> liveRebindRequests;
+ private final JProgram program;
private RecordRebinds(JProgram program, Set<String> liveRebindRequests) {
this.program = program;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/RemoveEmptySuperCalls.java b/dev/core/src/com/google/gwt/dev/jjs/impl/RemoveEmptySuperCalls.java
index 1009b1b..51da0c6 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/RemoveEmptySuperCalls.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/RemoveEmptySuperCalls.java
@@ -35,8 +35,7 @@
public static class EmptySuperCallVisitor extends JModVisitor {
@Override
public void endVisit(JExpressionStatement x, Context ctx) {
- if (x.getExpr() instanceof JMethodCall
- && !(x.getExpr() instanceof JNewInstance)) {
+ if (x.getExpr() instanceof JMethodCall && !(x.getExpr() instanceof JNewInstance)) {
JMethodCall call = (JMethodCall) x.getExpr();
if (call.getTarget() instanceof JConstructor) {
JConstructor ctor = (JConstructor) call.getTarget();
@@ -47,8 +46,7 @@
} else if (call.getArgs().size() == 1) {
ctx.replaceMe(call.getArgs().get(0).makeStatement());
} else {
- JMultiExpression multi = new JMultiExpression(
- call.getSourceInfo());
+ JMultiExpression multi = new JMultiExpression(call.getSourceInfo());
multi.exprs.addAll(call.getArgs());
ctx.replaceMe(multi.makeStatement());
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRebinds.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRebinds.java
index 19627d5..66db954 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRebinds.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRebinds.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -83,8 +83,9 @@
JClassLiteral classLiteral = (JClassLiteral) arg;
JReferenceType sourceType = (JReferenceType) classLiteral.getRefType();
List<JClassType> allRebindResults = getAllPossibleRebindResults(sourceType);
- JGwtCreate gwtCreate = new JGwtCreate(x.getSourceInfo(), sourceType,
- allRebindResults, program.getTypeJavaLangObject(), currentClass);
+ JGwtCreate gwtCreate =
+ new JGwtCreate(x.getSourceInfo(), sourceType, allRebindResults, program
+ .getTypeJavaLangObject(), currentClass);
if (allRebindResults.size() == 1) {
// Just replace with the instantiation expression.
ctx.replaceMe(gwtCreate.getInstantiationExpressions().get(0));
@@ -106,8 +107,8 @@
if (ref != null) {
final List<String> errors = new ArrayList<String>();
- JNode node = JsniRefLookup.findJsniRefTarget(ref, program,
- new JsniRefLookup.ErrorReporter() {
+ JNode node =
+ JsniRefLookup.findJsniRefTarget(ref, program, new JsniRefLookup.ErrorReporter() {
public void reportError(String error) {
errors.add(error);
}
@@ -125,8 +126,9 @@
} else {
// See if it's just @foo.Bar, which would result in the class seed
- refType = program.getFromTypeMap(stringValue.charAt(0) == '@'
- ? stringValue.substring(1) : stringValue);
+ refType =
+ program.getFromTypeMap(stringValue.charAt(0) == '@' ? stringValue.substring(1)
+ : stringValue);
if (refType != null) {
named = refType;
}
@@ -136,14 +138,12 @@
// Not found, must be null
ctx.replaceMe(JNullLiteral.INSTANCE);
} else {
- ctx.replaceMe(new JNameOf(x.getSourceInfo(), stringLiteral.getType(),
- named));
+ ctx.replaceMe(new JNameOf(x.getSourceInfo(), stringLiteral.getType(), named));
}
}
}
- public static boolean exec(TreeLogger logger, JProgram program,
- RebindPermutationOracle rpo) {
+ public static boolean exec(TreeLogger logger, JProgram program, RebindPermutationOracle rpo) {
Event replaceRebindsEvent = SpeedTracerLogger.start(CompilerEventType.REPLACE_REBINDS);
boolean didChange = new ReplaceRebinds(logger, program, rpo).execImpl();
replaceRebindsEvent.end();
@@ -154,8 +154,7 @@
private final JProgram program;
private final RebindPermutationOracle rpo;
- private ReplaceRebinds(TreeLogger logger, JProgram program,
- RebindPermutationOracle rpo) {
+ private ReplaceRebinds(TreeLogger logger, JProgram program, RebindPermutationOracle rpo) {
this.logger = logger;
this.program = program;
this.rpo = rpo;
@@ -169,9 +168,8 @@
answers = rpo.getAllPossibleRebindAnswers(logger, reqType);
} catch (UnableToCompleteException e) {
// Should never happen.
- throw new InternalCompilerException(
- "Unexpected failure to get possible rebind answers for '" + reqType
- + "'");
+ throw new InternalCompilerException("Unexpected failure to get possible rebind answers for '"
+ + reqType + "'");
}
List<JClassType> rebindAnswers = new ArrayList<JClassType>();
for (String answer : answers) {
@@ -184,9 +182,9 @@
}
private boolean execImpl() {
- RebindVisitor rebinder = new RebindVisitor(
- program.getIndexedMethod("Impl.getNameOf"),
- program.getIndexedMethod("GWT.create"));
+ RebindVisitor rebinder =
+ new RebindVisitor(program.getIndexedMethod("Impl.getNameOf"), program
+ .getIndexedMethod("GWT.create"));
rebinder.accept(program);
return rebinder.didChange();
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRunAsyncs.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRunAsyncs.java
index b3b81f9..d0ae938 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRunAsyncs.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ReplaceRunAsyncs.java
@@ -60,8 +60,7 @@
private final String name;
private final int number;
- RunAsyncReplacement(int number, JMethod enclosingMethod,
- JMethod loadMethod, String name) {
+ RunAsyncReplacement(int number, JMethod enclosingMethod, JMethod loadMethod, String name) {
this.number = number;
this.enclosingMethod = enclosingMethod;
this.loadMethod = loadMethod;
@@ -133,11 +132,10 @@
JClassType loader = getFragmentLoader(entryNumber);
JMethod loadMethod = getRunAsyncMethod(loader);
assert loadMethod != null;
- runAsyncReplacements.put(entryNumber, new RunAsyncReplacement(
- entryNumber, currentMethod, loadMethod, name));
+ runAsyncReplacements.put(entryNumber, new RunAsyncReplacement(entryNumber, currentMethod,
+ loadMethod, name));
- JMethodCall methodCall = new JMethodCall(x.getSourceInfo(), null,
- loadMethod);
+ JMethodCall methodCall = new JMethodCall(x.getSourceInfo(), null, loadMethod);
methodCall.addArg(asyncCallback);
tightenCallbackType(entryNumber, asyncCallback.getType());
@@ -202,13 +200,12 @@
* target the onSuccess method of a specific callback class.
*/
callbackField.setType(callbackType);
- JMethod runCallbacksMethod = getMethod(loaderClass,
- FragmentLoaderCreator.RUN_CALLBACKS);
+ JMethod runCallbacksMethod = getMethod(loaderClass, FragmentLoaderCreator.RUN_CALLBACKS);
MethodCallTightener.exec(program, runCallbacksMethod);
}
}
private class ReplaceRunAsyncResources extends JModVisitor {
- private Map<String, List<RunAsyncReplacement>> replacementsByName;
+ private final Map<String, List<RunAsyncReplacement>> replacementsByName;
public ReplaceRunAsyncResources() {
replacementsByName = new HashMap<String, List<RunAsyncReplacement>>();
@@ -230,8 +227,7 @@
if (x.getTarget() == program.getIndexedMethod("RunAsyncCode.runAsyncCode")) {
JExpression arg0 = x.getArgs().get(0);
if (!(arg0 instanceof JClassLiteral)) {
- error(arg0.getSourceInfo(),
- "Only a class literal may be passed to runAsyncCode");
+ error(arg0.getSourceInfo(), "Only a class literal may be passed to runAsyncCode");
return;
}
JClassLiteral lit = (JClassLiteral) arg0;
@@ -242,8 +238,7 @@
return;
}
if (matches.size() > 1) {
- TreeLogger branch = error(x.getSourceInfo(),
- "Multiple runAsync calls are named " + name);
+ TreeLogger branch = error(x.getSourceInfo(), "Multiple runAsync calls are named " + name);
for (RunAsyncReplacement match : matches) {
branch.log(TreeLogger.ERROR, "One call is in "
+ methodDescription(match.getEnclosingMethod()));
@@ -252,8 +247,9 @@
}
Integer splitPoint = matches.get(0).getNumber();
- JMethodCall newCall = new JMethodCall(x.getSourceInfo(), null,
- program.getIndexedMethod("RunAsyncCode.forSplitPointNumber"));
+ JMethodCall newCall =
+ new JMethodCall(x.getSourceInfo(), null, program
+ .getIndexedMethod("RunAsyncCode.forSplitPointNumber"));
newCall.addArg(program.getLiteralInt(splitPoint));
ctx.replaceMe(newCall);
}
@@ -274,12 +270,11 @@
}
}
- public static void exec(TreeLogger logger, JProgram program)
- throws UnableToCompleteException {
- Event codeSplitterEvent = SpeedTracerLogger.start(
- CompilerEventType.CODE_SPLITTER, "phase", "ReplaceRunAsyncs");
- TreeLogger branch = logger.branch(TreeLogger.TRACE,
- "Replacing GWT.runAsync with island loader calls");
+ public static void exec(TreeLogger logger, JProgram program) throws UnableToCompleteException {
+ Event codeSplitterEvent =
+ SpeedTracerLogger.start(CompilerEventType.CODE_SPLITTER, "phase", "ReplaceRunAsyncs");
+ TreeLogger branch =
+ logger.branch(TreeLogger.TRACE, "Replacing GWT.runAsync with island loader calls");
new ReplaceRunAsyncs(branch, program).execImpl();
codeSplitterEvent.end();
}
@@ -301,8 +296,7 @@
return method;
}
}
- throw new InternalCompilerException("Method not found: " + type.getName()
- + "." + name);
+ throw new InternalCompilerException("Method not found: " + type.getName() + "." + name);
}
private static JMethod getOnLoadMethod(JClassType loaderType) {
@@ -320,7 +314,8 @@
JMethod method = getMethod(loaderType, "runAsync");
assert (method.isStatic());
assert (method.getParams().size() == 1);
- assert (method.getParams().get(0).getType().getName().equals(FragmentLoaderCreator.RUN_ASYNC_CALLBACK));
+ assert (method.getParams().get(0).getType().getName()
+ .equals(FragmentLoaderCreator.RUN_ASYNC_CALLBACK));
return method;
}
@@ -333,9 +328,10 @@
private boolean errorsFound = false;
private final TreeLogger logger;
- private JProgram program;
+ private final JProgram program;
- private Map<Integer, RunAsyncReplacement> runAsyncReplacements = new HashMap<Integer, RunAsyncReplacement>();
+ private final Map<Integer, RunAsyncReplacement> runAsyncReplacements =
+ new HashMap<Integer, RunAsyncReplacement>();
private ReplaceRunAsyncs(TreeLogger logger, JProgram program) {
this.logger = logger;
@@ -344,8 +340,8 @@
private TreeLogger error(SourceInfo info, String message) {
errorsFound = true;
- TreeLogger fileLogger = logger.branch(TreeLogger.ERROR, "Error in '"
- + info.getFileName() + "'");
+ TreeLogger fileLogger =
+ logger.branch(TreeLogger.ERROR, "Error in '" + info.getFileName() + "'");
String linePrefix = "";
if (info.getStartLine() > 0) {
linePrefix = "Line " + info.getStartLine() + ": ";
@@ -371,14 +367,13 @@
return field;
}
}
- throw new InternalCompilerException("Field not found: " + type.getName()
- + "." + name);
+ throw new InternalCompilerException("Field not found: " + type.getName() + "." + name);
}
private JClassType getFragmentLoader(int fragmentNumber) {
- String fragmentLoaderClassName = FragmentLoaderCreator.ASYNC_LOADER_PACKAGE
- + "." + FragmentLoaderCreator.ASYNC_LOADER_CLASS_PREFIX
- + fragmentNumber;
+ String fragmentLoaderClassName =
+ FragmentLoaderCreator.ASYNC_LOADER_PACKAGE + "."
+ + FragmentLoaderCreator.ASYNC_LOADER_CLASS_PREFIX + fragmentNumber;
JType result = program.getFromTypeMap(fragmentLoaderClassName);
assert (result != null);
assert (result instanceof JClassType);
@@ -386,9 +381,10 @@
}
private JClassType getFragmentLoaderCallbackList(int fragmentNumber) {
- String className = FragmentLoaderCreator.ASYNC_LOADER_PACKAGE + "."
- + FragmentLoaderCreator.ASYNC_LOADER_CLASS_PREFIX + fragmentNumber
- + FragmentLoaderCreator.CALLBACK_LIST_SUFFIX;
+ String className =
+ FragmentLoaderCreator.ASYNC_LOADER_PACKAGE + "."
+ + FragmentLoaderCreator.ASYNC_LOADER_CLASS_PREFIX + fragmentNumber
+ + FragmentLoaderCreator.CALLBACK_LIST_SUFFIX;
JType result = program.getFromTypeMap(className);
assert (result != null);
return (JClassType) result;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ResolveRebinds.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ResolveRebinds.java
index 8054c63..e69fded 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ResolveRebinds.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ResolveRebinds.java
@@ -56,8 +56,8 @@
public void endVisit(JGwtCreate x, Context ctx) {
if (isSoftRebind(x.getSourceType())) {
- JMethod method = rebindMethod(x.getSourceType(), x.getResultTypes(),
- x.getInstantiationExpressions());
+ JMethod method =
+ rebindMethod(x.getSourceType(), x.getResultTypes(), x.getInstantiationExpressions());
JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method);
ctx.replaceMe(call);
return;
@@ -73,16 +73,14 @@
return;
}
}
- throw new InternalCompilerException(
- "No matching rebind result in all rebind results!");
+ throw new InternalCompilerException("No matching rebind result in all rebind results!");
}
@Override
public void endVisit(JReboundEntryPoint x, Context ctx) {
if (isSoftRebind(x.getSourceType())) {
- JMethod method = rebindMethod(x.getSourceType(), x.getResultTypes(),
- x.getEntryCalls());
+ JMethod method = rebindMethod(x.getSourceType(), x.getResultTypes(), x.getEntryCalls());
JMethodCall call = new JMethodCall(x.getSourceInfo(), null, method);
ctx.replaceMe(call.makeStatement());
return;
@@ -98,13 +96,11 @@
return;
}
}
- throw new InternalCompilerException(
- "No matching rebind result in all rebind results!");
+ throw new InternalCompilerException("No matching rebind result in all rebind results!");
}
}
- public static boolean exec(JProgram program,
- Map<String, String>[] orderedRebindAnswers) {
+ public static boolean exec(JProgram program, Map<String, String>[] orderedRebindAnswers) {
return new ResolveRebinds(program, orderedRebindAnswers).execImpl();
}
@@ -112,8 +108,7 @@
* Returns the rebind answers that do not vary across various maps of rebind
* answers.
*/
- public static Map<String, String> getHardRebindAnswers(
- Map<String, String>[] rebindAnswers) {
+ public static Map<String, String> getHardRebindAnswers(Map<String, String>[] rebindAnswers) {
Iterator<Map<String, String>> it = Arrays.asList(rebindAnswers).iterator();
// Start with an arbitrary copy of a rebind answer map
@@ -133,10 +128,10 @@
private final Map<String, String>[] orderedRebindAnswers;
private final JMethod permutationIdMethod;
private final JProgram program;
- private final Map<JReferenceType, JMethod> rebindMethods = new IdentityHashMap<JReferenceType, JMethod>();
+ private final Map<JReferenceType, JMethod> rebindMethods =
+ new IdentityHashMap<JReferenceType, JMethod>();
- private ResolveRebinds(JProgram program,
- Map<String, String>[] orderedRebindAnswers) {
+ private ResolveRebinds(JProgram program, Map<String, String>[] orderedRebindAnswers) {
this.program = program;
this.orderedRebindAnswers = orderedRebindAnswers;
@@ -153,8 +148,7 @@
// The fact that we already compute every rebind permutation before
// compiling should prevent this case from ever happening in real life.
//
- throw new InternalCompilerException("Unexpected failure to rebind '"
- + reqType + "'");
+ throw new InternalCompilerException("Unexpected failure to rebind '" + reqType + "'");
}
JDeclaredType result = program.getFromTypeMap(reboundClassName);
assert (result != null);
@@ -172,8 +166,8 @@
return !hardRebindAnswers.containsKey(reqType);
}
- private JMethod rebindMethod(JReferenceType requestType,
- List<JClassType> resultTypes, List<JExpression> instantiationExpressions) {
+ private JMethod rebindMethod(JReferenceType requestType, List<JClassType> resultTypes,
+ List<JExpression> instantiationExpressions) {
assert resultTypes.size() == instantiationExpressions.size();
JMethod toReturn = rebindMethods.get(requestType);
@@ -181,16 +175,15 @@
return toReturn;
}
- SourceInfo info = requestType.getSourceInfo().makeChild(
- SourceOrigin.UNKNOWN);
+ SourceInfo info = requestType.getSourceInfo().makeChild(SourceOrigin.UNKNOWN);
// Maps the result types to the various virtual permutation ids
- Map<JClassType, List<Integer>> resultsToPermutations = new LinkedHashMap<JClassType, List<Integer>>();
+ Map<JClassType, List<Integer>> resultsToPermutations =
+ new LinkedHashMap<JClassType, List<Integer>>();
for (int i = 0, j = orderedRebindAnswers.length; i < j; i++) {
Map<String, String> answerMap = orderedRebindAnswers[i];
- String answerTypeName = answerMap.get(requestType.getName().replace('$',
- '.'));
+ String answerTypeName = answerMap.get(requestType.getName().replace('$', '.'));
// We take an answer class, e.g. DOMImplSafari ...
JClassType answerType = (JClassType) program.getFromTypeMap(answerTypeName);
@@ -218,10 +211,10 @@
assert mostUsed != null;
// c_g_g_d_c_i_DOMImpl
- toReturn = program.createMethod(info,
- requestType.getName().replace("_", "_1").replace('.', '_'), holderType,
- program.getTypeJavaLangObject().getNonNull(), false, true, true, false,
- false);
+ toReturn =
+ program.createMethod(info, requestType.getName().replace("_", "_1").replace('.', '_'),
+ holderType, program.getTypeJavaLangObject().getNonNull(), false, true, true, false,
+ false);
toReturn.freezeParamTypes();
info.addCorrelation(info.getCorrelator().by(toReturn));
rebindMethods.put(requestType, toReturn);
@@ -246,8 +239,7 @@
for (int permutationId : permutations) {
// case 33:
- switchBody.addStmt(new JCaseStatement(info,
- program.getLiteralInt(permutationId)));
+ switchBody.addStmt(new JCaseStatement(info, program.getLiteralInt(permutationId)));
}
// return new FooImpl();
@@ -259,13 +251,12 @@
+ "for supposedly soft-rebind type " + requestType.getName();
// switch (CollapsedPropertyHolder.getPermutationId()) { ... }
- JSwitchStatement sw = new JSwitchStatement(info, new JMethodCall(info,
- null, permutationIdMethod), switchBody);
+ JSwitchStatement sw =
+ new JSwitchStatement(info, new JMethodCall(info, null, permutationIdMethod), switchBody);
// return new FallbackImpl(); at the very end.
assert mostUsedExpression != null : "No most-used expression";
- JReturnStatement fallbackReturn = new JReturnStatement(info,
- mostUsedExpression);
+ JReturnStatement fallbackReturn = new JReturnStatement(info, mostUsedExpression);
JMethodBody body = (JMethodBody) toReturn.getBody();
body.getBlock().addStmt(sw);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/SameParameterValueOptimizer.java b/dev/core/src/com/google/gwt/dev/jjs/impl/SameParameterValueOptimizer.java
index 61d0f6b..e064689 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/SameParameterValueOptimizer.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/SameParameterValueOptimizer.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -49,9 +49,6 @@
// TODO: this optimization can mistakenly act on methods such as LongLib.fromInt
// since only one call is seen in LongLib itself.
public class SameParameterValueOptimizer {
- private static final String NAME =
- SameParameterValueOptimizer.class.getSimpleName();
-
/**
* Fill parameterValues map.
*/
@@ -137,8 +134,7 @@
rescuedMethods.add(x);
} else {
JMethod staticImpl = program.staticImplFor(x);
- if (staticImpl != null
- && staticImpl.getEnclosingType().getMethods().contains(staticImpl)) {
+ if (staticImpl != null && staticImpl.getEnclosingType().getMethods().contains(staticImpl)) {
// instance method is still alive.
rescuedMethods.add(x);
}
@@ -166,12 +162,11 @@
* Substitute all parameter references with expression.
*/
private class SubstituteParameterVisitor extends JModVisitor {
- private CloneExpressionVisitor cloner;
+ private final CloneExpressionVisitor cloner;
private final JExpression expression;
private final JParameter parameter;
- public SubstituteParameterVisitor(JParameter parameter,
- JExpression expression) {
+ public SubstituteParameterVisitor(JParameter parameter, JExpression expression) {
this.parameter = parameter;
this.expression = expression;
cloner = new CloneExpressionVisitor();
@@ -185,33 +180,34 @@
}
}
+ private static final String NAME = SameParameterValueOptimizer.class.getSimpleName();
+
public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(
- CompilerEventType.OPTIMIZE, "optimizer", NAME);
- OptimizerStats stats = new SameParameterValueOptimizer(program).execImpl(
- program);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
+ OptimizerStats stats = new SameParameterValueOptimizer(program).execImpl(program);
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
}
/**
* Parameter values.
- *
+ *
* If doesn't contain a parameter, then its value is unknown. If contains
* parameter, and value is null - the parameter's value is not the same across
* all calls. If value is not null - the parameter's value is the same across
* all calls.
*/
- private Map<JParameter, JValueLiteral> parameterValues = new IdentityHashMap<JParameter, JValueLiteral>();
+ private final Map<JParameter, JValueLiteral> parameterValues =
+ new IdentityHashMap<JParameter, JValueLiteral>();
private final JProgram program;
/**
* These methods should not be tried to optimized due to their polymorphic
* nature.
- *
+ *
* TODO: support polymorphic calls properly.
*/
- private Set<JMethod> rescuedMethods = new HashSet<JMethod>();
+ private final Set<JMethod> rescuedMethods = new HashSet<JMethod>();
private final Simplifier simplifier;
private SameParameterValueOptimizer(JProgram program) {
@@ -230,9 +226,11 @@
}
JValueLiteral valueLiteral = parameterValues.get(parameter);
if (valueLiteral != null) {
- SubstituteParameterVisitor substituteParameterVisitor = new SubstituteParameterVisitor(parameter, simplifier.cast(parameter.getType(), valueLiteral));
+ SubstituteParameterVisitor substituteParameterVisitor =
+ new SubstituteParameterVisitor(parameter, simplifier.cast(parameter.getType(),
+ valueLiteral));
substituteParameterVisitor.accept(parameter.getEnclosingMethod());
- stats.recordModified(substituteParameterVisitor.getNumMods());
+ stats.recordModified(substituteParameterVisitor.getNumMods());
}
}
return stats;
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/Simplifier.java b/dev/core/src/com/google/gwt/dev/jjs/impl/Simplifier.java
index f36f23a..66a66bf 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/Simplifier.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/Simplifier.java
@@ -85,8 +85,7 @@
this.program = program;
}
- public JExpression cast(JExpression original, SourceInfo info, JType type,
- JExpression exp) {
+ public JExpression cast(JExpression original, SourceInfo info, JType type, JExpression exp) {
info = getBestSourceInfo(original, info, exp);
if (type == exp.getType()) {
return exp;
@@ -125,9 +124,8 @@
return cast(null, exp.getSourceInfo(), type, exp);
}
- public JExpression conditional(JConditional original, SourceInfo info,
- JType type, JExpression condExpr, JExpression thenExpr,
- JExpression elseExpr) {
+ public JExpression conditional(JConditional original, SourceInfo info, JType type,
+ JExpression condExpr, JExpression thenExpr, JExpression elseExpr) {
info = getBestSourceInfo(original, info, condExpr);
if (condExpr instanceof JMultiExpression) {
// (a,b,c)?d:e -> a,b,(c?d:e)
@@ -135,8 +133,7 @@
JMultiExpression condMulti = (JMultiExpression) condExpr;
JMultiExpression newMulti = new JMultiExpression(info);
newMulti.exprs.addAll(allButLast(condMulti.exprs));
- newMulti.exprs.add(conditional(null, info, type, last(condMulti.exprs),
- thenExpr, elseExpr));
+ newMulti.exprs.add(conditional(null, info, type, last(condMulti.exprs), thenExpr, elseExpr));
// TODO(spoon): immediately simplify the resulting multi
return newMulti;
}
@@ -181,9 +178,8 @@
return new JConditional(info, type, condExpr, thenExpr, elseExpr);
}
- public JStatement ifStatement(JIfStatement original, SourceInfo info,
- JExpression condExpr, JStatement thenStmt, JStatement elseStmt,
- JMethod currentMethod) {
+ public JStatement ifStatement(JIfStatement original, SourceInfo info, JExpression condExpr,
+ JStatement thenStmt, JStatement elseStmt, JMethod currentMethod) {
info = getBestSourceInfo(original, info, condExpr);
if (condExpr instanceof JMultiExpression) {
// if(a,b,c) d else e -> {a; b; if(c) d else e; }
@@ -192,8 +188,8 @@
for (JExpression expr : allButLast(condMulti.exprs)) {
newBlock.addStmt(expr.makeStatement());
}
- newBlock.addStmt(ifStatement(null, info, last(condMulti.exprs), thenStmt,
- elseStmt, currentMethod));
+ newBlock.addStmt(ifStatement(null, info, last(condMulti.exprs), thenStmt, elseStmt,
+ currentMethod));
// TODO(spoon): immediately simplify the resulting block
return newBlock;
}
@@ -225,13 +221,12 @@
// TODO: this goes away when we normalize the Java AST properly.
thenStmt = ensureBlock(thenStmt);
elseStmt = ensureBlock(elseStmt);
- return ifStatement(null, info, unflipped, elseStmt, thenStmt,
- currentMethod);
+ return ifStatement(null, info, unflipped, elseStmt, thenStmt, currentMethod);
}
}
- JStatement rewritenStatement = rewriteIfIntoBoolean(info, condExpr,
- thenStmt, elseStmt, currentMethod);
+ JStatement rewritenStatement =
+ rewriteIfIntoBoolean(info, condExpr, thenStmt, elseStmt, currentMethod);
if (rewritenStatement != null) {
return rewritenStatement;
}
@@ -243,8 +238,7 @@
return new JIfStatement(info, condExpr, thenStmt, elseStmt);
}
- public JExpression not(JPrefixOperation original, SourceInfo info,
- JExpression arg) {
+ public JExpression not(JPrefixOperation original, SourceInfo info, JExpression arg) {
info = getBestSourceInfo(original, info, arg);
if (arg instanceof JMultiExpression) {
// !(a,b,c) -> (a,b,!c)
@@ -280,8 +274,8 @@
newOp = JBinaryOperator.GTE;
}
if (newOp != null) {
- JBinaryOperation newBinOp = new JBinaryOperation(info, argOp.getType(),
- newOp, argOp.getLhs(), argOp.getRhs());
+ JBinaryOperation newBinOp =
+ new JBinaryOperation(info, argOp.getType(), newOp, argOp.getLhs(), argOp.getRhs());
return newBinOp;
}
} else if (arg instanceof JPrefixOperation) {
@@ -315,8 +309,8 @@
* if (isWhatever() && false) -> if (false), unless side effects
* </pre>
*/
- public JExpression shortCircuitAnd(JBinaryOperation original,
- SourceInfo info, JExpression lhs, JExpression rhs) {
+ public JExpression shortCircuitAnd(JBinaryOperation original, SourceInfo info, JExpression lhs,
+ JExpression rhs) {
info = getBestSourceInfo(original, info, lhs);
if (lhs instanceof JBooleanLiteral) {
JBooleanLiteral booleanLiteral = (JBooleanLiteral) lhs;
@@ -338,8 +332,7 @@
if (original != null) {
return original;
}
- return new JBinaryOperation(info, rhs.getType(), JBinaryOperator.AND, lhs,
- rhs);
+ return new JBinaryOperation(info, rhs.getType(), JBinaryOperator.AND, lhs, rhs);
}
/**
@@ -353,8 +346,8 @@
* if (isWhatever() || true) -> if (true), unless side effects
* </pre>
*/
- public JExpression shortCircuitOr(JBinaryOperation original, SourceInfo info,
- JExpression lhs, JExpression rhs) {
+ public JExpression shortCircuitOr(JBinaryOperation original, SourceInfo info, JExpression lhs,
+ JExpression rhs) {
info = getBestSourceInfo(original, info, lhs);
if (lhs instanceof JBooleanLiteral) {
JBooleanLiteral booleanLiteral = (JBooleanLiteral) lhs;
@@ -376,8 +369,7 @@
if (original != null) {
return original;
}
- return new JBinaryOperation(info, rhs.getType(), JBinaryOperator.OR, lhs,
- rhs);
+ return new JBinaryOperation(info, rhs.getType(), JBinaryOperator.OR, lhs, rhs);
}
private JStatement ensureBlock(JStatement stmt) {
@@ -412,8 +404,7 @@
return stmt;
}
- private SourceInfo getBestSourceInfo(JNode original, SourceInfo info,
- JNode defaultNode) {
+ private SourceInfo getBestSourceInfo(JNode original, SourceInfo info, JNode defaultNode) {
if (info == null) {
if (original == null) {
info = defaultNode.getSourceInfo();
@@ -424,14 +415,13 @@
return info;
}
- private JStatement rewriteIfIntoBoolean(SourceInfo sourceInfo,
- JExpression condExpr, JStatement thenStmt, JStatement elseStmt,
- JMethod currentMethod) {
+ private JStatement rewriteIfIntoBoolean(SourceInfo sourceInfo, JExpression condExpr,
+ JStatement thenStmt, JStatement elseStmt, JMethod currentMethod) {
thenStmt = extractSingleStatement(thenStmt);
elseStmt = extractSingleStatement(elseStmt);
- if (thenStmt instanceof JReturnStatement
- && elseStmt instanceof JReturnStatement && currentMethod != null) {
+ if (thenStmt instanceof JReturnStatement && elseStmt instanceof JReturnStatement
+ && currentMethod != null) {
// Special case
// if () { return ..; } else { return ..; } =>
// return ... ? ... : ...;
@@ -442,11 +432,11 @@
return null;
}
- JConditional conditional = new JConditional(sourceInfo,
- currentMethod.getType(), condExpr, thenExpression, elseExpression);
+ JConditional conditional =
+ new JConditional(sourceInfo, currentMethod.getType(), condExpr, thenExpression,
+ elseExpression);
- JReturnStatement returnStatement = new JReturnStatement(sourceInfo,
- conditional);
+ JReturnStatement returnStatement = new JReturnStatement(sourceInfo, conditional);
return returnStatement;
}
@@ -456,8 +446,9 @@
JExpression elseExpression = extractExpression(elseStmt);
if (thenExpression != null && elseExpression != null) {
- JConditional conditional = new JConditional(sourceInfo,
- JPrimitiveType.VOID, condExpr, thenExpression, elseExpression);
+ JConditional conditional =
+ new JConditional(sourceInfo, JPrimitiveType.VOID, condExpr, thenExpression,
+ elseExpression);
return conditional.makeStatement();
}
@@ -474,8 +465,9 @@
binaryOperator = JBinaryOperator.OR;
}
- JBinaryOperation binaryOperation = new JBinaryOperation(sourceInfo,
- program.getTypeVoid(), binaryOperator, condExpr, thenExpression);
+ JBinaryOperation binaryOperation =
+ new JBinaryOperation(sourceInfo, program.getTypeVoid(), binaryOperator, condExpr,
+ thenExpression);
return binaryOperation.makeStatement();
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/TempLocalVisitor.java b/dev/core/src/com/google/gwt/dev/jjs/impl/TempLocalVisitor.java
index 1c4deec..c32eede 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/TempLocalVisitor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/TempLocalVisitor.java
@@ -86,8 +86,7 @@
if (target instanceof JLocal) {
String name = target.getName();
if (name.startsWith(PREFIX)) {
- curScope.recordTempAllocated(Integer.parseInt(
- name.substring(PREFIX.length()), 10));
+ curScope.recordTempAllocated(Integer.parseInt(name.substring(PREFIX.length()), 10));
}
}
}
@@ -211,7 +210,7 @@
* A set of statements we cannot insert declaration statements into. Currently
* this is just the "increments" list of a JForStatement.
*/
- private Set<JStatement> banList = new HashSet<JStatement>();
+ private final Set<JStatement> banList = new HashSet<JStatement>();
private JMethodBody curMethodBody = null;
private Scope curScope = null;
@@ -273,8 +272,7 @@
int tempNum = curScope.allocateNextFreeTemp();
String name = PREFIX + tempNum;
JLocal local = JProgram.createLocal(info, name, type, false, curMethodBody);
- JDeclarationStatement init = new JDeclarationStatement(info, new JLocalRef(
- info, local), null);
+ JDeclarationStatement init = new JDeclarationStatement(info, new JLocalRef(info, local), null);
insertionStack.peek().insertBefore(init);
return local;
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/ToStringGenerationVisitor.java b/dev/core/src/com/google/gwt/dev/jjs/impl/ToStringGenerationVisitor.java
index 4ca8593..399b749 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/ToStringGenerationVisitor.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/ToStringGenerationVisitor.java
@@ -347,6 +347,29 @@
}
@Override
+ public boolean visit(JConstructor x, Context ctx) {
+ // Modifiers
+ if (x.isPrivate()) {
+ print(CHARS_PRIVATE);
+ } else {
+ print(CHARS_PUBLIC);
+ }
+ printName(x);
+
+ // Parameters
+ printParameterList(x);
+
+ if (x.isAbstract() || !shouldPrintMethodBody()) {
+ semi();
+ newlineOpt();
+ } else {
+ accept(x.getBody());
+ }
+
+ return false;
+ }
+
+ @Override
public boolean visit(JContinueStatement x, Context ctx) {
print(CHARS_CONTINUE);
if (x.getLabel() != null) {
@@ -591,29 +614,6 @@
}
@Override
- public boolean visit(JConstructor x, Context ctx) {
- // Modifiers
- if (x.isPrivate()) {
- print(CHARS_PRIVATE);
- } else {
- print(CHARS_PUBLIC);
- }
- printName(x);
-
- // Parameters
- printParameterList(x);
-
- if (x.isAbstract() || !shouldPrintMethodBody()) {
- semi();
- newlineOpt();
- } else {
- accept(x.getBody());
- }
-
- return false;
- }
-
- @Override
public boolean visit(JMethod x, Context ctx) {
printMethodHeader(x);
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeLinker.java b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeLinker.java
index fd31093..fd4ff5b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeLinker.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeLinker.java
@@ -1,12 +1,12 @@
/*
* Copyright 2010 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -16,7 +16,7 @@
package com.google.gwt.dev.jjs.impl;
/**
- * Provides linking information for types for separate compilation.
+ * Provides linking information for types for separate compilation.
*/
public interface TypeLinker {
@@ -27,8 +27,8 @@
};
/**
- * Returns true if the type is external (source code not provided)
- * to the program.
+ * Returns true if the type is external (source code not provided) to the
+ * program.
*/
boolean isExternalType(String name);
}
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeMap.java b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeMap.java
index 784e2ff..cb2390d 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeMap.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeMap.java
@@ -55,7 +55,8 @@
*/
private final Map<Binding, JNode> crossRefMap = new IdentityHashMap<Binding, JNode>();
- private final Map<String, JDeclaredType> externalTypesByName = new HashMap<String, JDeclaredType>();
+ private final Map<String, JDeclaredType> externalTypesByName =
+ new HashMap<String, JDeclaredType>();
/**
* Centralizes creation and singleton management.
@@ -73,7 +74,7 @@
public JProgram getProgram() {
return program;
}
-
+
public void put(Binding binding, JNode to) {
if (binding == null) {
throw new InternalCompilerException("Trying to put null into typeMap.");
@@ -95,8 +96,8 @@
}
private boolean equals(MethodBinding binding, JMethod method) {
- if (!(method instanceof JConstructor && binding.isConstructor()) &&
- !method.getName().equals(String.valueOf(binding.constantPoolName()))) {
+ if (!(method instanceof JConstructor && binding.isConstructor())
+ && !method.getName().equals(String.valueOf(binding.constantPoolName()))) {
return false;
}
@@ -136,8 +137,7 @@
}
JNode result = internalGet(binding, failOnNull);
if (result == null && failOnNull) {
- InternalCompilerException ice = new InternalCompilerException(
- "Failed to get JNode");
+ InternalCompilerException ice = new InternalCompilerException("Failed to get JNode");
ice.addNode(binding.getClass().getName(), binding.toString(), null);
throw ice;
}
@@ -165,8 +165,8 @@
}
/**
- * Returns a list of JNodes that have the same name as the JDT Binding.
- * This method is only used during debugging sessions from the interactive
+ * Returns a list of JNodes that have the same name as the JDT Binding. This
+ * method is only used during debugging sessions from the interactive
* expression evaluator.
*/
@SuppressWarnings("unused")
@@ -179,7 +179,7 @@
}
return new ArrayList<JNode>(nodes);
}
-
+
private JNode internalGet(Binding binding, boolean failOnNull) {
JNode cached = crossRefMap.get(binding);
if (cached != null) {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeRemapper.java b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeRemapper.java
index d8298d6..94a2625 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeRemapper.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeRemapper.java
@@ -31,61 +31,61 @@
/**
* This class is a visitor which can find all sites where a JType can be updated
* from one type to another, and calls an overridable remap method for each
- * instance. An extending class can override the remap and return a new type
- * where it deems it necessary, such as to replace the type of all references
- * of a class.
+ * instance. An extending class can override the remap and return a new type
+ * where it deems it necessary, such as to replace the type of all references of
+ * a class.
*/
public class TypeRemapper extends JModVisitor {
-
+
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
x.setType(remap(x.getType()));
}
-
+
@Override
public void endVisit(JCastOperation x, Context ctx) {
// JCastOperation doesn't have a settable castType method, so need to
// create a new one and do a replacement.
JType remapCastType = remap(x.getCastType());
if (remapCastType != x.getCastType()) {
- JCastOperation newX = new JCastOperation(x.getSourceInfo(),
- remapCastType, x.getExpr());
+ JCastOperation newX = new JCastOperation(x.getSourceInfo(), remapCastType, x.getExpr());
ctx.replaceMe(newX);
}
}
-
+
@Override
public void endVisit(JConditional x, Context ctx) {
x.setType(remap(x.getType()));
}
-
+
@Override
public void endVisit(JConstructor x, Context ctx) {
x.setType(remap(x.getType()));
}
-
+
@Override
public void endVisit(JGwtCreate x, Context ctx) {
x.setType(remap(x.getType()));
}
-
+
@Override
public void endVisit(JMethod x, Context ctx) {
x.setType(remap(x.getType()));
}
-
+
@Override
public void endVisit(JNewArray x, Context ctx) {
x.setType((JNonNullType) remap(x.getType()));
}
-
+
@Override
public void endVisit(JVariable x, Context ctx) {
x.setType(remap(x.getType()));
}
-
+
/**
* An overriding method will be called for each detected JType element.
+ *
* @param type
*/
protected JType remap(JType type) {
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeTightener.java b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeTightener.java
index 3be1164..a477402 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/TypeTightener.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/TypeTightener.java
@@ -1,12 +1,12 @@
/*
* Copyright 2008 Google Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
@@ -70,37 +70,30 @@
* the information to infer places where "tighter" (that is, more specific)
* types can be inferred for locals, fields, parameters, and method return
* types. We also optimize dynamic casts and instanceof operations.
- *
+ *
* Type flow occurs automatically in most JExpressions. But locals, fields,
* parameters, and method return types serve as "way points" where type
* information is fixed based on the declared type. Type tightening can be done
* by analyzing the types "flowing" into each way point, and then updating the
* declared type of the way point to be a more specific type than it had before.
- *
+ *
* Oddly, it's quite possible to tighten a variable to the Null type, which
* means either the variable was never assigned, or it was only ever assigned
* null. This is great for two reasons:
- *
+ *
* 1) Once a variable has been tightened to null, it will no longer impact the
* variables that depend on it.
- *
+ *
* 2) It creates some very interesting opportunities to optimize later, since we
* know statically that the value of the variable is always null.
- *
+ *
* Open issue: we don't handle recursion where a method passes (some of) its own
* args to itself or returns its own call result. With our naive analysis, we
* can't figure out that tightening might occur.
- *
+ *
* Type flow is not supported for primitive types, only reference types.
*/
public class TypeTightener {
- private static final String NAME = TypeTightener.class.getSimpleName();
-
- /*
- * TODO(later): handle recursion, self-assignment, arrays, method tightening
- * on invocations from within JSNI blocks
- */
-
/**
* Replaces dangling null references with dummy calls.
*/
@@ -114,8 +107,8 @@
// this doesn't really belong here, but while we're here let's remove
// non-side-effect qualifiers to statics
if (!instance.hasSideEffects()) {
- JFieldRef fieldRef = new JFieldRef(x.getSourceInfo(), null,
- x.getField(), x.getEnclosingType());
+ JFieldRef fieldRef =
+ new JFieldRef(x.getSourceInfo(), null, x.getField(), x.getEnclosingType());
ctx.replaceMe(fieldRef);
}
} else if (!isStatic && instance.getType() == typeNull
@@ -136,8 +129,7 @@
// this doesn't really belong here, but while we're here let's remove
// non-side-effect qualifiers to statics
if (!instance.hasSideEffects()) {
- JMethodCall newCall = new JMethodCall(x.getSourceInfo(), null,
- x.getTarget());
+ JMethodCall newCall = new JMethodCall(x.getSourceInfo(), null, x.getTarget());
newCall.addArgs(x.getArgs());
ctx.replaceMe(newCall);
}
@@ -157,6 +149,11 @@
}
}
+ /*
+ * TODO(later): handle recursion, self-assignment, arrays, method tightening
+ * on invocations from within JSNI blocks
+ */
+
/**
* Record "type flow" information. Variables receive type flow via assignment.
* As a special case, Parameters also receive type flow based on the types of
@@ -164,7 +161,7 @@
* of assignment). Method return types receive type flow from their contained
* return statements, plus the return type of any methods that
* override/implement them.
- *
+ *
* Note that we only have to run this pass ONCE to record the relationships,
* because type tightening never changes any relationships, only the types of
* the things related. In my original implementation, I had naively mapped
@@ -260,10 +257,8 @@
// Fake an assignment-to-self on all args to prevent tightening
JMethod method = x.getTarget();
for (JParameter param : method.getParams()) {
- addAssignment(
- param,
- new JParameterRef(
- program.createSourceInfoSynthetic(RecordVisitor.class), param));
+ addAssignment(param, new JParameterRef(program
+ .createSourceInfoSynthetic(RecordVisitor.class), param));
}
}
@@ -318,8 +313,7 @@
*/
JMethod staticImplFor = program.staticImplFor(x);
if (staticImplFor == null
- || !staticImplFor.getEnclosingType().getMethods().contains(
- staticImplFor)) {
+ || !staticImplFor.getEnclosingType().getMethods().contains(staticImplFor)) {
// The instance method has already been pruned.
return true;
}
@@ -354,8 +348,7 @@
add(target, implementor, implementors);
}
- private void addInterfacesImplementorRecursive(JDeclaredType target,
- JClassType implementor) {
+ private void addInterfacesImplementorRecursive(JDeclaredType target, JClassType implementor) {
for (JInterfaceType implment : target.getImplements()) {
addImplementor(implment, implementor);
addInterfacesImplementorRecursive(implment, implementor);
@@ -375,16 +368,15 @@
* Wherever possible, use the type flow information recorded by RecordVisitor
* to change the declared type of a field, local, parameter, or method to a
* more specific type.
- *
+ *
* Also optimize dynamic casts and instanceof operations where possible.
*/
public class TightenTypesVisitor extends JModVisitor {
-
+
@Override
public void endVisit(JCastOperation x, Context ctx) {
JType argType = x.getExpr().getType();
- if (!(x.getCastType() instanceof JReferenceType)
- || !(argType instanceof JReferenceType)) {
+ if (!(x.getCastType() instanceof JReferenceType) || !(argType instanceof JReferenceType)) {
return;
}
@@ -414,16 +406,15 @@
ctx.replaceMe(x.getExpr());
} else if (triviallyFalse && toType != program.getTypeNull()) {
// replace with a magic NULL cast, unless it's already a cast to NULL
- JCastOperation newOp = new JCastOperation(x.getSourceInfo(),
- program.getTypeNull(), x.getExpr());
+ JCastOperation newOp =
+ new JCastOperation(x.getSourceInfo(), program.getTypeNull(), x.getExpr());
ctx.replaceMe(newOp);
} else {
// If possible, try to use a narrower cast
JReferenceType tighterType = getSingleConcreteType(toType);
if (tighterType != null && tighterType != toType) {
- JCastOperation newOp = new JCastOperation(x.getSourceInfo(),
- tighterType, x.getExpr());
+ JCastOperation newOp = new JCastOperation(x.getSourceInfo(), tighterType, x.getExpr());
ctx.replaceMe(newOp);
}
}
@@ -432,9 +423,9 @@
@Override
public void endVisit(JConditional x, Context ctx) {
if (x.getType() instanceof JReferenceType) {
- JReferenceType newType = program.generalizeTypes(
- (JReferenceType) x.getThenExpr().getType(),
- (JReferenceType) x.getElseExpr().getType());
+ JReferenceType newType =
+ program.generalizeTypes((JReferenceType) x.getThenExpr().getType(), (JReferenceType) x
+ .getElseExpr().getType());
if (newType != x.getType()) {
x.setType(newType);
madeChanges();
@@ -499,9 +490,9 @@
if (triviallyTrue) {
// replace with a simple null test
JNullLiteral nullLit = program.getLiteralNull();
- JBinaryOperation neq = new JBinaryOperation(x.getSourceInfo(),
- program.getTypePrimitiveBoolean(), JBinaryOperator.NEQ,
- x.getExpr(), nullLit);
+ JBinaryOperation neq =
+ new JBinaryOperation(x.getSourceInfo(), program.getTypePrimitiveBoolean(),
+ JBinaryOperator.NEQ, x.getExpr(), nullLit);
ctx.replaceMe(neq);
} else if (triviallyFalse) {
// replace with a false literal
@@ -510,8 +501,7 @@
// If possible, try to use a narrower cast
JReferenceType concreteType = getSingleConcreteType(toType);
if (concreteType != null) {
- JInstanceOf newOp = new JInstanceOf(x.getSourceInfo(), concreteType,
- x.getExpr());
+ JInstanceOf newOp = new JInstanceOf(x.getSourceInfo(), concreteType, x.getExpr());
ctx.replaceMe(newOp);
}
}
@@ -596,8 +586,7 @@
JMethod target = x.getTarget();
JMethod concreteMethod = getSingleConcreteMethod(target);
if (concreteMethod != null) {
- JMethodCall newCall = new JMethodCall(x.getSourceInfo(),
- x.getInstance(), concreteMethod);
+ JMethodCall newCall = new JMethodCall(x.getSourceInfo(), x.getInstance(), concreteMethod);
newCall.addArgs(x.getArgs());
ctx.replaceMe(newCall);
target = concreteMethod;
@@ -613,8 +602,7 @@
if (myOverriders != null) {
for (JMethod override : myOverriders) {
JReferenceType overrideType = override.getEnclosingType();
- if (program.typeOracle.canTheoreticallyCast(instanceType,
- overrideType)) {
+ if (program.typeOracle.canTheoreticallyCast(instanceType, overrideType)) {
// This call is truly polymorphic.
// TODO: composite types! :)
return;
@@ -675,14 +663,12 @@
if (type instanceof JReferenceType) {
JReferenceType refType = (JReferenceType) type;
if (refType.isAbstract()) {
- JClassType singleConcrete = getSingleConcrete(
- refType.getUnderlyingType(), implementors);
+ JClassType singleConcrete = getSingleConcrete(refType.getUnderlyingType(), implementors);
assert (singleConcrete == null || program.typeOracle.isInstantiatedType(singleConcrete));
if (singleConcrete == null) {
return null;
}
- return refType.canBeNull() ? singleConcrete
- : singleConcrete.getNonNull();
+ return refType.canBeNull() ? singleConcrete : singleConcrete.getNonNull();
}
}
return null;
@@ -696,8 +682,7 @@
return program.getTypeArray(JNullType.INSTANCE);
} else if (elementType instanceof JArrayType) {
JArrayType newElementType = nullifyArrayType((JArrayType) elementType);
- return program.getTypeArray(newElementType.getLeafType(),
- newElementType.getDims() + 1);
+ return program.getTypeArray(newElementType.getLeafType(), newElementType.getDims() + 1);
}
}
return arrayType;
@@ -797,9 +782,10 @@
}
}
+ private static final String NAME = TypeTightener.class.getSimpleName();
+
public static OptimizerStats exec(JProgram program) {
- Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE,
- "optimizer", NAME);
+ Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "optimizer", NAME);
OptimizerStats stats = new TypeTightener(program).execImpl();
optimizeEvent.end("didChange", "" + stats.didChange());
return stats;
@@ -818,8 +804,7 @@
* Find exactly one concrete element for a key in a Map of Sets. If there are
* none or more than one concrete element, return <code>null</code>.
*/
- private static <B, T extends CanBeAbstract> T getSingleConcrete(B x,
- Map<? super B, Set<T>> map) {
+ private static <B, T extends CanBeAbstract> T getSingleConcrete(B x, Map<? super B, Set<T>> map) {
Set<T> set = map.get(x);
// No set, then no concrete version
@@ -844,12 +829,17 @@
return toReturn;
}
- private final Map<JVariable, Set<JExpression>> assignments = new IdentityHashMap<JVariable, Set<JExpression>>();
- private final Map<JReferenceType, Set<JClassType>> implementors = new IdentityHashMap<JReferenceType, Set<JClassType>>();
- private final Map<JMethod, Set<JMethod>> overriders = new IdentityHashMap<JMethod, Set<JMethod>>();
- private final Map<JParameter, Set<JParameter>> paramUpRefs = new IdentityHashMap<JParameter, Set<JParameter>>();
+ private final Map<JVariable, Set<JExpression>> assignments =
+ new IdentityHashMap<JVariable, Set<JExpression>>();
+ private final Map<JReferenceType, Set<JClassType>> implementors =
+ new IdentityHashMap<JReferenceType, Set<JClassType>>();
+ private final Map<JMethod, Set<JMethod>> overriders =
+ new IdentityHashMap<JMethod, Set<JMethod>>();
+ private final Map<JParameter, Set<JParameter>> paramUpRefs =
+ new IdentityHashMap<JParameter, Set<JParameter>>();
private final JProgram program;
- private final Map<JMethod, Set<JExpression>> returns = new IdentityHashMap<JMethod, Set<JExpression>>();
+ private final Map<JMethod, Set<JExpression>> returns =
+ new IdentityHashMap<JMethod, Set<JExpression>>();
private final JNullType typeNull;
@@ -867,11 +857,11 @@
* We must iterate multiple times because each way point we tighten creates
* more opportunities to do additional tightening for the things that depend
* on it.
+ *
+ * TODO(zundel): See if we can remove this loop, or otherwise run to less
+ * than completion if we compile with an option for less than 100% optimized
+ * output.
*/
-
- // TODO(zundel): See if we can remove this loop, or otherwise run to less
- // than completion if we compile with an option for less than 100%
- // optimized output.
while (true) {
TightenTypesVisitor tightener = new TightenTypesVisitor();
tightener.accept(program);