Skip to content

Commit

Permalink
Miscellaneous code simplifications
Browse files Browse the repository at this point in the history
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=165460941
  • Loading branch information
blickly authored and Tyler Breisacher committed Aug 16, 2017
1 parent 6b963c8 commit b33fc4f
Show file tree
Hide file tree
Showing 35 changed files with 109 additions and 118 deletions.
5 changes: 2 additions & 3 deletions src/com/google/javascript/jscomp/BasicErrorManager.java
Expand Up @@ -36,7 +36,7 @@
*/
public abstract class BasicErrorManager implements ErrorManager {
private final PriorityQueue<ErrorWithLevel> messages =
new PriorityQueue<ErrorWithLevel>(1, new LeveledJSErrorComparator());
new PriorityQueue<>(1, new LeveledJSErrorComparator());
private final Set<ErrorWithLevel> alreadyAdded = new HashSet<>();
private int errorCount = 0;
private int warningCount = 0;
Expand All @@ -45,8 +45,7 @@ public abstract class BasicErrorManager implements ErrorManager {
@Override
public void report(CheckLevel level, JSError error) {
ErrorWithLevel e = new ErrorWithLevel(error, level);
if (!alreadyAdded.contains(e)) {
alreadyAdded.add(e);
if (alreadyAdded.add(e)) {
messages.add(e);
if (level == CheckLevel.ERROR) {
errorCount++;
Expand Down
6 changes: 2 additions & 4 deletions src/com/google/javascript/jscomp/SourceFile.java
Expand Up @@ -616,10 +616,8 @@ public synchronized String getCode() throws IOException {
String cachedCode = super.getCode();

if (cachedCode == null) {
try {
try (Reader r = getCodeReader()) {
cachedCode = CharStreams.toString(r);
}
try (Reader r = getCodeReader()) {
cachedCode = CharStreams.toString(r);
} catch (java.nio.charset.MalformedInputException e) {
throw new IOException("Failed to read: " + path + ", is this input UTF-8 encoded?", e);
}
Expand Down
16 changes: 5 additions & 11 deletions src/com/google/javascript/jscomp/ant/CompileTask.java
Expand Up @@ -386,15 +386,14 @@ public void execute() {

if (this.outputWrapperFile != null) {
try {
this.outputWrapper = Files.toString(this.outputWrapperFile, UTF_8);
this.outputWrapper = Files.asCharSource(this.outputWrapperFile, UTF_8).read();
} catch (Exception e) {
throw new BuildException("Invalid output_wrapper_file specified.");
}
}

if (this.outputWrapper != null) {
int pos = -1;
pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER);
int pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER);
if (pos > -1) {
String prefix = this.outputWrapper.substring(0, pos);
source.insert(0, prefix);
Expand Down Expand Up @@ -422,10 +421,8 @@ public void execute() {
}

private void flushSourceMap(SourceMap sourceMap) {
try {
FileWriter out = new FileWriter(sourceMapOutputFile);
try (FileWriter out = new FileWriter(sourceMapOutputFile)) {
sourceMap.appendTo(out, outputFile.getName());
out.close();
} catch (IOException e) {
throw new BuildException("Cannot write sourcemap to file.", e);
}
Expand Down Expand Up @@ -683,12 +680,9 @@ private void writeResult(String source) {
this.outputFile.getParentFile(), Project.MSG_DEBUG);
}

try {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(this.outputFile), outputEncoding);
try (OutputStreamWriter out =
new OutputStreamWriter(new FileOutputStream(this.outputFile), outputEncoding)) {
out.append(source);
out.flush();
out.close();
} catch (IOException e) {
throw new BuildException(e);
}
Expand Down
Expand Up @@ -1458,7 +1458,7 @@ public StringBuilder appendTo(StringBuilder builder, ToStringContext ctx) {
}
if (!this.typeParameters.isEmpty()) {
builder.append("<");
builder.append(Joiner.on(",").join(getPrettyTypeParams(this.typeParameters.asList(), ctx)));
Joiner.on(",").appendTo(builder, getPrettyTypeParams(this.typeParameters.asList(), ctx));
builder.append(">");
}
builder.append("function(");
Expand Down
Expand Up @@ -610,13 +610,13 @@ private void fillInFunTypeBuilder(
Node jsdocNode, RawNominalType ownerType, DeclaredTypeRegistry registry,
ImmutableList<String> typeParameters, FunctionTypeBuilder builder) {
Node child = jsdocNode.getFirstChild();
if (child.getToken() == Token.THIS) {
if (child.isThis()) {
if (ownerType == null) {
builder.addReceiverType(
getThisOrNewType(child.getFirstChild(), registry, typeParameters));
}
child = child.getNext();
} else if (child.getToken() == Token.NEW) {
} else if (child.isNew()) {
Node newTypeNode = child.getFirstChild();
JSType t = getThisOrNewType(newTypeNode, registry, typeParameters);
if (!t.isSubtypeOf(this.commonTypes.getTopObject())
Expand All @@ -627,7 +627,7 @@ private void fillInFunTypeBuilder(
builder.addNominalType(t);
child = child.getNext();
}
if (child.getToken() == Token.PARAM_LIST) {
if (child.isParamList()) {
for (Node arg = child.getFirstChild(); arg != null; arg = arg.getNext()) {
try {
switch (arg.getToken()) {
Expand Down Expand Up @@ -998,7 +998,7 @@ private NominalType getMaybeHigherOrderParentClass(Node docNode, String function
Node funNode, JSType extendedType, DeclaredTypeRegistry registry) {
if (extendedType.isUnknown()
&& docNode.getToken() == Token.BANG
&& docNode.getFirstChild().getToken() == Token.STRING) {
&& docNode.getFirstChild().isString()) {
String varname = docNode.getFirstChild().getString();
Declaration decl = registry.getDeclaration(QualifiedName.fromQualifiedString(varname), false);
if (decl != null) {
Expand Down
Expand Up @@ -50,9 +50,7 @@ static TypeParameters make(List<String> ordinaryTypeParams, Map<String, Node> tt
for (String typeParam : ordinaryTypeParams) {
builder.put(typeParam, IR.empty());
}
for (Map.Entry<String, Node> entry : ttlParams.entrySet()) {
builder.put(entry);
}
builder.putAll(ttlParams);
return new TypeParameters(builder.build());
}

Expand Down
Expand Up @@ -56,7 +56,7 @@ private static String trimLeft(String str) {
private static int findDelimiter(String line) {
if (line.contains(":") || line.contains("=")) {
if (line.indexOf(':') == -1) {
return line.indexOf("=");
return line.indexOf('=');
}
if (line.indexOf('=') == -1) {
return line.indexOf(':');
Expand Down
Expand Up @@ -31,7 +31,7 @@
public final class BasicErrorManagerTest extends TestCase {
private static final String NULL_SOURCE = null;

private LeveledJSErrorComparator comparator = new LeveledJSErrorComparator();
private final LeveledJSErrorComparator comparator = new LeveledJSErrorComparator();

static final CheckLevel E = CheckLevel.ERROR;

Expand Down
Expand Up @@ -23,7 +23,7 @@
*/
public final class ClosureCodeRemovalTest extends CompilerTestCase {

private static String EXTERNS = "var window;";
private static final String EXTERNS = "var window;";

public ClosureCodeRemovalTest() {
super(EXTERNS);
Expand Down
Expand Up @@ -28,7 +28,7 @@
* Test class for {@link GoogleCodingConvention}.
*/
public final class ClosureCodingConventionTest extends TestCase {
private ClosureCodingConvention conv = new ClosureCodingConvention();
private final ClosureCodingConvention conv = new ClosureCodingConvention();

public void testVarAndOptionalParams() {
Node args = new Node(Token.PARAM_LIST,
Expand Down
12 changes: 6 additions & 6 deletions test/com/google/javascript/jscomp/CombinedCompilerPassTest.java
Expand Up @@ -93,9 +93,9 @@ public void setUp() throws Exception {
* rooted with specified strings.
*/
private static class ConcatTraversal implements Callback {
private StringBuilder visited = new StringBuilder();
private StringBuilder shouldTraversed = new StringBuilder();
private Set<String> ignoring = new HashSet<>();
private final StringBuilder visited = new StringBuilder();
private final StringBuilder shouldTraversed = new StringBuilder();
private final Set<String> ignoring = new HashSet<>();

ConcatTraversal ignore(String s) {
ignoring.add(s);
Expand Down Expand Up @@ -135,9 +135,9 @@ Collection<String> getIgnoring() {
* and the expected pre- and post-order traversal results.
*/
private static class TestHelper {
private ConcatTraversal traversal;
private String expectedVisited;
private String shouldTraverseExpected;
private final ConcatTraversal traversal;
private final String expectedVisited;
private final String shouldTraverseExpected;

TestHelper(ConcatTraversal traversal, String expectedVisited,
String shouldTraverseExpected) {
Expand Down
20 changes: 10 additions & 10 deletions test/com/google/javascript/jscomp/CompilerTest.java
Expand Up @@ -218,14 +218,14 @@ public void testResolveRelativeSourceMap() throws Exception {
File tempDir = Files.createTempDir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=foo.js.map";
File jsFile = new File(tempDir, "foo.js");
Files.write(code, jsFile, Charsets.UTF_8);
Files.asCharSink(jsFile, Charsets.UTF_8).write(code);
File sourceMapFile = new File(tempDir, "foo.js.map");
Files.write(SOURCE_MAP, sourceMapFile, Charsets.UTF_8);
Files.asCharSink(sourceMapFile, Charsets.UTF_8).write(SOURCE_MAP);

CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
// The source map is still
assertThat(compiler.inputSourceMaps.size()).isEqualTo(1);
assertThat(compiler.inputSourceMaps).hasSize(1);

for (SourceMapInput inputSourceMap : compiler.inputSourceMaps.values()) {
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(null);
Expand All @@ -242,14 +242,14 @@ public void testResolveRelativeDirSourceMap() throws Exception {
relativedir.mkdir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=relativedir/foo.js.map";
File jsFile = new File(tempDir, "foo.js");
Files.write(code, jsFile, Charsets.UTF_8);
Files.asCharSink(jsFile, Charsets.UTF_8).write(code);
File sourceMapFile = new File(relativedir, "foo.js.map");
Files.write(SOURCE_MAP, sourceMapFile, Charsets.UTF_8);
Files.asCharSink(sourceMapFile, Charsets.UTF_8).write(SOURCE_MAP);

CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
// The source map is still
assertThat(compiler.inputSourceMaps.size()).isEqualTo(1);
assertThat(compiler.inputSourceMaps).hasSize(1);

for (SourceMapInput inputSourceMap : compiler.inputSourceMaps.values()) {
SourceMapConsumerV3 sourceMap = inputSourceMap.getSourceMap(null);
Expand All @@ -263,11 +263,11 @@ public void testMissingSourceMapFile() throws Exception {
File tempDir = Files.createTempDir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=foo-does-not-exist.js.map";
File jsFile = new File(tempDir, "foo2.js");
Files.write(code, jsFile, Charsets.UTF_8);
Files.asCharSink(jsFile, Charsets.UTF_8).write(code);

CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
assertThat(compiler.inputSourceMaps.size()).isEqualTo(1);
assertThat(compiler.inputSourceMaps).hasSize(1);

TestErrorManager errorManager = new TestErrorManager();
for (SourceMapInput inputSourceMap : compiler.inputSourceMaps.values()) {
Expand All @@ -286,12 +286,12 @@ public void testNoWarningMissingAbsoluteSourceMap() throws Exception {
File tempDir = Files.createTempDir();
String code = SOURCE_MAP_TEST_CODE + "\n//# sourceMappingURL=/some/missing/path/foo.js.map";
File jsFile = new File(tempDir, "foo.js");
Files.write(code, jsFile, Charsets.UTF_8);
Files.asCharSink(jsFile, Charsets.UTF_8).write(code);

CompilerInput input = new CompilerInput(SourceFile.fromFile(jsFile.getAbsolutePath()));
input.getAstRoot(compiler);
// The source map is still
assertThat(compiler.inputSourceMaps.size()).isEqualTo(0);
assertThat(compiler.inputSourceMaps).isEmpty();

// No warnings for unresolved absolute paths.
assertEquals(0, errorManager.getWarningCount());
Expand Down
4 changes: 2 additions & 2 deletions test/com/google/javascript/jscomp/CompilerTestCase.java
Expand Up @@ -562,7 +562,7 @@ protected int getNumRepetitions() {
/** Adds the given DiagnosticTypes to the set of warnings to ignore. */
protected final void ignoreWarnings(DiagnosticType... warnings) {
checkState(this.setUpRan, "Attempted to configure before running setUp().");
ignoredWarnings.addAll(Arrays.asList(warnings));
Collections.addAll(ignoredWarnings, warnings);
}

/** Adds the given DiagnosticGroups to the set of warnings to ignore. */
Expand Down Expand Up @@ -1916,7 +1916,7 @@ protected final List<Node> findQualifiedNameNodes(final String name, Node root)
new NodeUtil.Visitor() {
@Override
public void visit(Node n) {
if (name.equals(n.getQualifiedName())) {
if (n.matchesQualifiedName(name)) {
matches.add(n);
}
}
Expand Down
4 changes: 3 additions & 1 deletion test/com/google/javascript/jscomp/DataFlowAnalysisTest.java
Expand Up @@ -951,7 +951,9 @@ public int compare(
constProp.analyze(MAX_STEP);
fail("Expected MaxIterationsExceededException to be thrown.");
} catch (MaxIterationsExceededException e) {
assertEquals("Analysis did not terminate after " + MAX_STEP + " iterations", e.getMessage());
assertThat(e)
.hasMessageThat()
.isEqualTo("Analysis did not terminate after " + MAX_STEP + " iterations");
}
}

Expand Down
Expand Up @@ -22,14 +22,13 @@
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.StaticSourceFile;
import com.google.javascript.rhino.Token;

import junit.framework.TestCase;

/**
* Test class for the default {@link CodingConvention}.
*/
public final class DefaultCodingConventionTest extends TestCase {
private CodingConvention conv = CodingConventions.getDefault();
private final CodingConvention conv = CodingConventions.getDefault();

public void testVarAndOptionalParams() {
Node args = new Node(Token.PARAM_LIST,
Expand Down
Expand Up @@ -33,7 +33,7 @@

public final class DisambiguatePropertiesTest extends TypeICompilerTestCase {
private DisambiguateProperties lastPass;
private static String renameFunctionDefinition =
private static final String RENAME_FUNCTION_DEFINITION =
"/** @const */ var goog = {};\n"
+ "/** @const */ goog.reflect = {};\n"
+ "/** @return {string} */\n"
Expand Down Expand Up @@ -84,7 +84,7 @@ public void testOneType1() {
testSets(js, js, "{a=[[Foo.prototype]]}");

js =
renameFunctionDefinition
RENAME_FUNCTION_DEFINITION
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype.a = 0;\n"
+ "/** @type {Foo} */\n"
Expand All @@ -104,7 +104,7 @@ public void testOneType2() {
testSets(js, js, expected);

js =
renameFunctionDefinition
RENAME_FUNCTION_DEFINITION
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = {a: 0};\n"
+ "/** @type {Foo} */\n"
Expand All @@ -125,7 +125,7 @@ public void testOneType3() {
testSets(js, js, expected);

js =
renameFunctionDefinition
RENAME_FUNCTION_DEFINITION
+ "/** @constructor */ function Foo() {}\n"
+ "Foo.prototype = { get a() {return 0},"
+ " set a(b) {} };\n"
Expand Down
Expand Up @@ -856,7 +856,7 @@ public void testFunctionName() {
assertTrue(globalScope.isDeclared("f", false));
assertFalse(globalScope.isDeclared("foo", false));

Node fNode = root.getFirstChild().getFirstChild().getFirstChild();
Node fNode = root.getFirstChild().getFirstFirstChild();
Scope fScope = scopeCreator.createScope(fNode, globalScope);
assertFalse(fScope.isDeclared("f", false));
assertTrue(fScope.isDeclared("foo", false));
Expand All @@ -869,7 +869,7 @@ public void testClassName() {
assertTrue(globalScope.isDeclared("Clazz", false));
assertFalse(globalScope.isDeclared("Foo", false));

Node classNode = root.getFirstChild().getFirstChild().getFirstChild();
Node classNode = root.getFirstChild().getFirstFirstChild();
Scope classScope = scopeCreator.createScope(classNode, globalScope);
assertFalse(classScope.isDeclared("Clazz", false));
assertTrue(classScope.isDeclared("Foo", false));
Expand Down
Expand Up @@ -16,6 +16,8 @@

package com.google.javascript.jscomp;

import static com.google.common.truth.Truth.assertThat;

import com.google.javascript.jscomp.graph.DiGraph;
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal;
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal.EdgeCallback;
Expand Down Expand Up @@ -48,7 +50,7 @@ public boolean traverseEdge(Counter source, String e, Counter dest) {
private DiGraph<Counter, String> graph;

private Counter A, B, C, D, E;
private CounterIncrementer callback = new CounterIncrementer();
private final CounterIncrementer callback = new CounterIncrementer();
private FixedPointGraphTraversal<Counter, String> traversal =
new FixedPointGraphTraversal<>(callback);

Expand Down Expand Up @@ -169,7 +171,7 @@ public boolean traverseEdge(Counter source, String e, Counter dest) {
fail("Expecting Error: " +
FixedPointGraphTraversal.NON_HALTING_ERROR_MSG);
} catch (IllegalStateException e) {
assertEquals(FixedPointGraphTraversal.NON_HALTING_ERROR_MSG, e.getMessage());
assertThat(e).hasMessageThat().isEqualTo(FixedPointGraphTraversal.NON_HALTING_ERROR_MSG);
}
}

Expand Down
Expand Up @@ -39,7 +39,7 @@ public final class FunctionInjectorTest extends TestCase {
static final InliningMode INLINE_DIRECT = InliningMode.DIRECT;
static final InliningMode INLINE_BLOCK = InliningMode.BLOCK;
private boolean assumeStrictThis = false;
private boolean assumeMinimumCapture = false;
private final boolean assumeMinimumCapture = false;

@Override
protected void setUp() throws Exception {
Expand Down

0 comments on commit b33fc4f

Please sign in to comment.