Skip to content

Commit

Permalink
Make more use of Java8 features in the non-rhino part of our codebase.
Browse files Browse the repository at this point in the history
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=188536568
  • Loading branch information
blickly committed Mar 12, 2018
1 parent d8aaa67 commit 29c21ec
Show file tree
Hide file tree
Showing 40 changed files with 336 additions and 554 deletions.
4 changes: 1 addition & 3 deletions src/com/google/javascript/jscomp/AbstractScope.java
Expand Up @@ -248,9 +248,7 @@ public final Iterable<V> getAllAccessibleVariables() {


while (s != null) { while (s != null) {
for (V v : s.getVarIterable()) { for (V v : s.getVarIterable()) {
if (!accessibleVars.containsKey(v.getName())){ accessibleVars.putIfAbsent(v.getName(), v);
accessibleVars.put(v.getName(), v);
}
} }
s = s.getParent(); s = s.getParent();
} }
Expand Down
29 changes: 5 additions & 24 deletions src/com/google/javascript/jscomp/ControlFlowAnalysis.java
Expand Up @@ -19,6 +19,7 @@
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static java.util.Comparator.comparingInt;


import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
Expand Down Expand Up @@ -70,13 +71,7 @@ public final class ControlFlowAnalysis implements Callback, CompilerPass {
// CFG nodes that come first lexically should be visited first, because // CFG nodes that come first lexically should be visited first, because
// they will often be executed first in the source program. // they will often be executed first in the source program.
private final Comparator<DiGraphNode<Node, Branch>> priorityComparator = private final Comparator<DiGraphNode<Node, Branch>> priorityComparator =
new Comparator<DiGraphNode<Node, Branch>>() { comparingInt(digraphNode -> astPosition.get(digraphNode.getValue()));
@Override
public int compare(
DiGraphNode<Node, Branch> a, DiGraphNode<Node, Branch> b) {
return astPosition.get(a.getValue()) - astPosition.get(b.getValue());
}
};


private int astPositionCounter; private int astPositionCounter;
private int priorityCounter; private int priorityCounter;
Expand Down Expand Up @@ -186,9 +181,7 @@ public void process(Node externs, Node root) {
// Presumably, it doesn't really matter what priority they get, since // Presumably, it doesn't really matter what priority they get, since
// this shouldn't happen in real code. // this shouldn't happen in real code.
for (DiGraphNode<Node, Branch> candidate : cfg.getDirectedGraphNodes()) { for (DiGraphNode<Node, Branch> candidate : cfg.getDirectedGraphNodes()) {
if (!nodePriorities.containsKey(candidate)) { nodePriorities.computeIfAbsent(candidate, k -> ++priorityCounter);
nodePriorities.put(candidate, ++priorityCounter);
}
} }


// Again, the implicit return node is always last. // Again, the implicit return node is always last.
Expand Down Expand Up @@ -1077,21 +1070,9 @@ private AstControlFlowGraph(Node entry,
public Comparator<DiGraphNode<Node, Branch>> getOptionalNodeComparator( public Comparator<DiGraphNode<Node, Branch>> getOptionalNodeComparator(
boolean isForward) { boolean isForward) {
if (isForward) { if (isForward) {
return new Comparator<DiGraphNode<Node, Branch>>() { return comparingInt(this::getPosition);
@Override
public int compare(
DiGraphNode<Node, Branch> n1, DiGraphNode<Node, Branch> n2) {
return getPosition(n1) - getPosition(n2);
}
};
} else { } else {
return new Comparator<DiGraphNode<Node, Branch>>() { return comparingInt(this::getPosition).reversed();
@Override
public int compare(
DiGraphNode<Node, Branch> n1, DiGraphNode<Node, Branch> n2) {
return getPosition(n2) - getPosition(n1);
}
};
} }
} }


Expand Down
10 changes: 2 additions & 8 deletions src/com/google/javascript/jscomp/JSModuleGraph.java
Expand Up @@ -390,11 +390,7 @@ List<JSModule> getTransitiveDepsDeepestFirst(JSModule m) {


/** Returns the transitive dependencies of the module. */ /** Returns the transitive dependencies of the module. */
private Set<JSModule> getTransitiveDeps(JSModule m) { private Set<JSModule> getTransitiveDeps(JSModule m) {
Set<JSModule> deps = dependencyMap.get(m); Set<JSModule> deps = dependencyMap.computeIfAbsent(m, JSModule::getAllDependencies);
if (deps == null) {
deps = m.getAllDependencies();
dependencyMap.put(m, deps);
}
return deps; return deps;
} }


Expand All @@ -420,9 +416,7 @@ public ImmutableList<CompilerInput> manageDependencies(
inputsByProvide.put(provide, input); inputsByProvide.put(provide, input);
} }
String moduleName = input.getPath().toModuleName(); String moduleName = input.getPath().toModuleName();
if (!inputsByProvide.containsKey(moduleName)) { inputsByProvide.putIfAbsent(moduleName, input);
inputsByProvide.put(moduleName, input);
}
} }


// Dynamically imported files must be added to the module graph, but // Dynamically imported files must be added to the module graph, but
Expand Down
18 changes: 2 additions & 16 deletions src/com/google/javascript/jscomp/NodeUtil.java
Expand Up @@ -1729,13 +1729,6 @@ public static boolean isNullOrUndefined(Node n) {
return n.isNull() || isUndefined(n); return n.isNull() || isUndefined(n);
} }


static final Predicate<Node> IMMUTABLE_PREDICATE = new Predicate<Node>() {
@Override
public boolean apply(Node n) {
return isImmutableValue(n);
}
};

static boolean isImmutableResult(Node n) { static boolean isImmutableResult(Node n) {
return allResultsMatch(n, NodeUtil::isImmutableValue); return allResultsMatch(n, NodeUtil::isImmutableValue);
} }
Expand Down Expand Up @@ -4015,9 +4008,7 @@ public void visit(Node n) {
Node parent = n.getParent(); Node parent = n.getParent();
if (parent != null && parent.isVar()) { if (parent != null && parent.isVar()) {
String name = n.getString(); String name = n.getString();
if (!vars.containsKey(name)) { vars.putIfAbsent(name, n);
vars.put(name, n);
}
} }
} }
} }
Expand Down Expand Up @@ -4374,12 +4365,7 @@ public boolean apply(Node n) {


static final Predicate<Node> MATCH_NOT_FUNCTION = n -> !n.isFunction(); static final Predicate<Node> MATCH_NOT_FUNCTION = n -> !n.isFunction();


static final Predicate<Node> MATCH_NOT_THIS_BINDING = new Predicate<Node>() { static final Predicate<Node> MATCH_NOT_THIS_BINDING = n -> !NodeUtil.isVanillaFunction(n);
@Override
public boolean apply(Node n) {
return !NodeUtil.isVanillaFunction(n);
}
};


/** /**
* A predicate for matching statements without exiting the current scope. * A predicate for matching statements without exiting the current scope.
Expand Down
4 changes: 1 addition & 3 deletions src/com/google/javascript/jscomp/PersistentInputStore.java
Expand Up @@ -55,9 +55,7 @@ CompilerInput getCachedZipEntry(SourceFile zipEntry) {
if (zipEntries.isEmpty()) { if (zipEntries.isEmpty()) {
zipEntries = new HashMap<>(); zipEntries = new HashMap<>();
} }
if (!zipEntries.containsKey(originalPath)) { zipEntries.computeIfAbsent(originalPath, k -> CompilerInput.makePersistentInput(zipEntry));
zipEntries.put(originalPath, CompilerInput.makePersistentInput(zipEntry));
}
return zipEntries.get(originalPath); return zipEntries.get(originalPath);
} }


Expand Down
Expand Up @@ -351,11 +351,8 @@ private static boolean isBlockBoundary(Node n, Node parent) {


private void addReference(Var v, Reference reference) { private void addReference(Var v, Reference reference) {
// Create collection if none already // Create collection if none already
ReferenceCollection referenceInfo = referenceMap.get(v); ReferenceCollection referenceInfo =
if (referenceInfo == null) { referenceMap.computeIfAbsent(v, k -> new ReferenceCollection());
referenceInfo = new ReferenceCollection();
referenceMap.put(v, referenceInfo);
}


// Add this particular reference // Add this particular reference
referenceInfo.add(reference); referenceInfo.add(reference);
Expand Down
21 changes: 8 additions & 13 deletions src/com/google/javascript/jscomp/TypedScope.java
Expand Up @@ -18,7 +18,6 @@


import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;


import com.google.common.base.Predicate;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Node;
Expand Down Expand Up @@ -57,17 +56,6 @@ public class TypedScope extends AbstractScope<TypedScope, TypedVar>
// Scope.java contains an arguments field. // Scope.java contains an arguments field.
// We haven't added it here because it's unused by the passes that need typed scopes. // We haven't added it here because it's unused by the passes that need typed scopes.


private static final Predicate<TypedVar> DECLARATIVELY_UNBOUND_VARS_WITHOUT_TYPES =
new Predicate<TypedVar>() {
@Override
public boolean apply(TypedVar var) {
return var.getParentNode() != null
&& var.getType() == null
&& var.getParentNode().isVar()
&& !var.isExtern();
}
};

TypedScope(TypedScope parent, Node rootNode) { TypedScope(TypedScope parent, Node rootNode) {
super(rootNode); super(rootNode);
checkChildScope(parent); checkChildScope(parent);
Expand Down Expand Up @@ -155,7 +143,14 @@ TypedVar makeArgumentsVar() {
} }


public Iterable<TypedVar> getDeclarativelyUnboundVarsWithoutTypes() { public Iterable<TypedVar> getDeclarativelyUnboundVarsWithoutTypes() {
return Iterables.filter(getVarIterable(), DECLARATIVELY_UNBOUND_VARS_WITHOUT_TYPES); return Iterables.filter(
getVarIterable(),
var ->
// declaratively unbound vars without types
var.getParentNode() != null
&& var.getType() == null
&& var.getParentNode().isVar()
&& !var.isExtern());
} }


static interface TypeResolver { static interface TypeResolver {
Expand Down
13 changes: 2 additions & 11 deletions src/com/google/javascript/jscomp/VariableMap.java
Expand Up @@ -17,6 +17,7 @@
package com.google.javascript.jscomp; package com.google.javascript.jscomp;


import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Map.Entry.comparingByKey;


import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
Expand All @@ -32,9 +33,7 @@
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Writer; import java.io.Writer;
import java.text.ParseException; import java.text.ParseException;
import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;


/** /**
* Stores the mapping from original variable name to new variable names. * Stores the mapping from original variable name to new variable names.
Expand All @@ -44,14 +43,6 @@ public final class VariableMap {


private static final char SEPARATOR = ':'; private static final char SEPARATOR = ':';


private static final Comparator<Map.Entry<String, String>> ENTRY_COMPARATOR =
new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> e1, Entry<String, String> e2) {
return e1.getKey().compareTo(e2.getKey());
}
};

/** Maps between original source name to new name */ /** Maps between original source name to new name */
private final ImmutableBiMap<String, String> map; private final ImmutableBiMap<String, String> map;


Expand Down Expand Up @@ -116,7 +107,7 @@ public byte[] toBytes() {
try { try {
// The output order should be stable. // The output order should be stable.
for (Map.Entry<String, String> entry : for (Map.Entry<String, String> entry :
ImmutableSortedSet.copyOf(ENTRY_COMPARATOR, map.entrySet())) { ImmutableSortedSet.copyOf(comparingByKey(), map.entrySet())) {
writer.write(escape(entry.getKey())); writer.write(escape(entry.getKey()));
writer.write(SEPARATOR); writer.write(SEPARATOR);
writer.write(escape(entry.getValue())); writer.write(escape(entry.getValue()));
Expand Down
Expand Up @@ -31,7 +31,7 @@ public class CachedTransformer implements Source.Transformer {


public CachedTransformer( public CachedTransformer(
Source.Transformer delegate, CacheBuilder<? super Source, ? super Source> builder) { Source.Transformer delegate, CacheBuilder<? super Source, ? super Source> builder) {
this.cache = builder.build(CacheLoader.from(source -> delegate.transform(source))); this.cache = builder.build(CacheLoader.from(delegate::transform));
} }


public CachedTransformer(Source.Transformer delegate, String spec) { public CachedTransformer(Source.Transformer delegate, String spec) {
Expand Down
4 changes: 2 additions & 2 deletions src/com/google/javascript/jscomp/bundle/Source.java
Expand Up @@ -155,7 +155,7 @@ public interface Transformer {
Source transform(Source input); Source transform(Source input);


static Transformer of(Function<Source, Source> function) { static Transformer of(Function<Source, Source> function) {
return x -> function.apply(x); return function::apply;
} }


/** Returns an identity transformer. */ /** Returns an identity transformer. */
Expand All @@ -165,7 +165,7 @@ static Transformer identity() {


/** Converts this Transformer to a Function. */ /** Converts this Transformer to a Function. */
default Function<Source, Source> asFunction() { default Function<Source, Source> asFunction() {
return x -> transform(x); return this::transform;
} }


/** Concatenates two Transformers. */ /** Concatenates two Transformers. */
Expand Down
Expand Up @@ -16,6 +16,8 @@


package com.google.javascript.jscomp.debugger.common; package com.google.javascript.jscomp.debugger.common;


import static java.util.Comparator.comparing;

import com.google.javascript.jscomp.AnonymousFunctionNamingPolicy; import com.google.javascript.jscomp.AnonymousFunctionNamingPolicy;
import com.google.javascript.jscomp.CheckLevel; import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CompilerOptions; import com.google.javascript.jscomp.CompilerOptions;
Expand Down Expand Up @@ -1040,14 +1042,7 @@ private static String diagGroupWarningInfo(String diagGroupsMember) {
static CompilationParam[] getSortedValues() { static CompilationParam[] getSortedValues() {
ArrayList<CompilationParam> values = new ArrayList<>(Arrays.asList(CompilationParam.values())); ArrayList<CompilationParam> values = new ArrayList<>(Arrays.asList(CompilationParam.values()));


Collections.sort( Collections.sort(values, comparing(CompilationParam::toString));
values,
new java.util.Comparator<CompilationParam>() {
@Override
public int compare(CompilationParam o1, CompilationParam o2) {
return o1.toString().compareTo(o2.toString());
}
});


return values.toArray(new CompilationParam[0]); return values.toArray(new CompilationParam[0]);
} }
Expand Down
22 changes: 5 additions & 17 deletions src/com/google/javascript/jscomp/deps/DependencyInfo.java
Expand Up @@ -16,12 +16,14 @@


package com.google.javascript.jscomp.deps; package com.google.javascript.jscomp.deps;


import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.auto.value.AutoValue; import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.Immutable;
import java.io.IOException; import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
Expand Down Expand Up @@ -62,15 +64,7 @@ public enum Type {
} }


public static ImmutableList<String> asSymbolList(Iterable<Require> requires) { public static ImmutableList<String> asSymbolList(Iterable<Require> requires) {
return ImmutableList.copyOf( return Streams.stream(requires).map(Require::getSymbol).collect(toImmutableList());
Iterables.transform(
requires,
new Function<Require, String>() {
@Override
public String apply(Require input) {
return input.getSymbol();
}
}));
} }


public static Require googRequireSymbol(String symbol) { public static Require googRequireSymbol(String symbol) {
Expand Down Expand Up @@ -217,13 +211,7 @@ private static void writeJsObject(Appendable out, Map<String, String> map) throw
/** Prints a list of strings formatted as a JavaScript array of string literals. */ /** Prints a list of strings formatted as a JavaScript array of string literals. */
private static void writeJsArray(Appendable out, Collection<String> values) throws IOException { private static void writeJsArray(Appendable out, Collection<String> values) throws IOException {
Iterable<String> quoted = Iterable<String> quoted =
Iterables.transform( Iterables.transform(values, arg -> "'" + arg.replace("'", "\\'") + "'");
values,
new Function<String, String>() {
@Override public String apply(String arg) {
return "'" + arg.replace("'", "\\'") + "'";
}
});
out.append("["); out.append("[");
out.append(Joiner.on(", ").join(quoted)); out.append(Joiner.on(", ").join(quoted));
out.append("]"); out.append("]");
Expand Down
18 changes: 6 additions & 12 deletions src/com/google/javascript/jscomp/deps/DepsFileParser.java
Expand Up @@ -16,13 +16,13 @@


package com.google.javascript.jscomp.deps; package com.google.javascript.jscomp.deps;


import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Functions; import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.ErrorManager;
import com.google.javascript.jscomp.deps.DependencyInfo.Require; import com.google.javascript.jscomp.deps.DependencyInfo.Require;
Expand All @@ -38,7 +38,6 @@
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.annotation.Nullable;


/** /**
* A parser that can extract dependency information from existing deps.js files. * A parser that can extract dependency information from existing deps.js files.
Expand Down Expand Up @@ -173,15 +172,10 @@ protected boolean parseLine(String line) throws ParseException {
SimpleDependencyInfo.builder(path, filePath) SimpleDependencyInfo.builder(path, filePath)
.setProvides(parseJsStringArray(depArgsMatch.group(2))) .setProvides(parseJsStringArray(depArgsMatch.group(2)))
.setRequires( .setRequires(
ImmutableList.copyOf( parseJsStringArray(depArgsMatch.group(3))
Iterables.transform( .stream()
parseJsStringArray(depArgsMatch.group(3)), .map(Require::parsedFromDeps)
new Function<String, Require>() { .collect(toImmutableList()))
@Override
public Require apply(@Nullable String input) {
return Require.parsedFromDeps(input);
}
})))
.setLoadFlags(parseLoadFlags(depArgsMatch.group(4))) .setLoadFlags(parseLoadFlags(depArgsMatch.group(4)))
.build(); .build();


Expand Down

0 comments on commit 29c21ec

Please sign in to comment.