Skip to content

Commit

Permalink
Group overloads together
Browse files Browse the repository at this point in the history
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=182281037
  • Loading branch information
blickly authored and dimvar committed Jan 18, 2018
1 parent cc7d341 commit 91f3cca
Show file tree
Hide file tree
Showing 51 changed files with 975 additions and 1,015 deletions.
112 changes: 57 additions & 55 deletions src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
Expand Up @@ -590,63 +590,15 @@ protected List<SourceFile> createInputs(
return createInputs(files, jsonFiles, false, jsModuleSpecs);
}

/**
* Check that relative paths inside zip files are unique, since multiple files with the same path
* inside different zips are considered duplicate inputs. Parameter {@code sourceFiles} may be
* modified if duplicates are removed.
*/
public static ImmutableList<JSError> removeDuplicateZipEntries(
List<SourceFile> sourceFiles, List<JsModuleSpec> jsModuleSpecs) throws IOException {
ImmutableList.Builder<JSError> errors = ImmutableList.builder();
Map<String, SourceFile> sourceFilesByName = new HashMap<>();
Iterator<SourceFile> fileIterator = sourceFiles.iterator();
int currentFileIndex = 0;
Iterator<JsModuleSpec> moduleIterator = jsModuleSpecs.iterator();
// Tracks the total number of js files for current module and all the previous modules.
int cumulatedJsFileNum = 0;
JsModuleSpec currentModule = null;
while (fileIterator.hasNext()) {
SourceFile sourceFile = fileIterator.next();
currentFileIndex++;
// Check whether we reached the next module.
if (moduleIterator.hasNext() && currentFileIndex > cumulatedJsFileNum) {
currentModule = moduleIterator.next();
cumulatedJsFileNum += currentModule.numJsFiles;
}
String fullPath = sourceFile.getName();
if (!fullPath.contains("!/")) {
// Not a zip file
continue;
}
String relativePath = fullPath.split("!")[1];
if (!sourceFilesByName.containsKey(relativePath)) {
sourceFilesByName.put(relativePath, sourceFile);
} else {
SourceFile firstSourceFile = sourceFilesByName.get(relativePath);
if (firstSourceFile.getCode().equals(sourceFile.getCode())) {
fileIterator.remove();
if (currentModule != null) {
currentModule.numJsFiles--;
}
} else {
errors.add(JSError.make(
CONFLICTING_DUPLICATE_ZIP_CONTENTS, firstSourceFile.getName(), sourceFile.getName()));
}
}
}
return errors.build();
}

/**
* Creates inputs from a list of source files, zips and json files.
*
* Can be overridden by subclasses who want to pull files from different
* places.
* <p>Can be overridden by subclasses who want to pull files from different places.
*
* @param files A list of flag entries indicates js and zip file names
* @param jsonFiles A list of json encoded files.
* @param allowStdIn Whether '-' is allowed appear as a filename to represent
* stdin. If true, '-' is only allowed to appear once.
* @param allowStdIn Whether '-' is allowed appear as a filename to represent stdin. If true, '-'
* is only allowed to appear once.
* @param jsModuleSpecs A list js module specs.
* @return An array of inputs
*/
Expand Down Expand Up @@ -696,12 +648,12 @@ protected List<SourceFile> createInputs(
}

if (!config.outputManifests.isEmpty()) {
throw new FlagUsageException("Manifest files cannot be generated " +
"when the input is from stdin.");
throw new FlagUsageException(
"Manifest files cannot be generated when the input is from stdin.");
}
if (!config.outputBundles.isEmpty()) {
throw new FlagUsageException("Bundle files cannot be generated " +
"when the input is from stdin.");
throw new FlagUsageException(
"Bundle files cannot be generated when the input is from stdin.");
}

this.err.println(WAITING_FOR_INPUT_WARNING);
Expand All @@ -727,6 +679,56 @@ protected List<SourceFile> createInputs(
return inputs;
}

/**
* Check that relative paths inside zip files are unique, since multiple files with the same path
* inside different zips are considered duplicate inputs. Parameter {@code sourceFiles} may be
* modified if duplicates are removed.
*/
public static ImmutableList<JSError> removeDuplicateZipEntries(
List<SourceFile> sourceFiles, List<JsModuleSpec> jsModuleSpecs) throws IOException {
ImmutableList.Builder<JSError> errors = ImmutableList.builder();
Map<String, SourceFile> sourceFilesByName = new HashMap<>();
Iterator<SourceFile> fileIterator = sourceFiles.iterator();
int currentFileIndex = 0;
Iterator<JsModuleSpec> moduleIterator = jsModuleSpecs.iterator();
// Tracks the total number of js files for current module and all the previous modules.
int cumulatedJsFileNum = 0;
JsModuleSpec currentModule = null;
while (fileIterator.hasNext()) {
SourceFile sourceFile = fileIterator.next();
currentFileIndex++;
// Check whether we reached the next module.
if (moduleIterator.hasNext() && currentFileIndex > cumulatedJsFileNum) {
currentModule = moduleIterator.next();
cumulatedJsFileNum += currentModule.numJsFiles;
}
String fullPath = sourceFile.getName();
if (!fullPath.contains("!/")) {
// Not a zip file
continue;
}
String relativePath = fullPath.split("!")[1];
if (!sourceFilesByName.containsKey(relativePath)) {
sourceFilesByName.put(relativePath, sourceFile);
} else {
SourceFile firstSourceFile = sourceFilesByName.get(relativePath);
if (firstSourceFile.getCode().equals(sourceFile.getCode())) {
fileIterator.remove();
if (currentModule != null) {
currentModule.numJsFiles--;
}
} else {
errors.add(
JSError.make(
CONFLICTING_DUPLICATE_ZIP_CONTENTS,
firstSourceFile.getName(),
sourceFile.getName()));
}
}
}
return errors.build();
}

/**
* Creates JS source code inputs from a list of files.
*/
Expand Down
31 changes: 15 additions & 16 deletions src/com/google/javascript/jscomp/CodeGenerator.java
Expand Up @@ -62,13 +62,7 @@ private CodeGenerator(CodeConsumer consumer) {
this.jsDocInfoPrinter = new JSDocInfoPrinter(false);
}

static CodeGenerator forCostEstimation(CodeConsumer consumer) {
return new CodeGenerator(consumer);
}

protected CodeGenerator(
CodeConsumer consumer,
CompilerOptions options) {
protected CodeGenerator(CodeConsumer consumer, CompilerOptions options) {
cc = consumer;

this.outputCharsetEncoder = new OutputCharsetEncoder(options.getOutputCharset());
Expand All @@ -80,6 +74,10 @@ protected CodeGenerator(
this.jsDocInfoPrinter = new JSDocInfoPrinter(useOriginalName);
}

static CodeGenerator forCostEstimation(CodeConsumer consumer) {
return new CodeGenerator(consumer);
}

/** Insert a top-level identifying file as .i.js generated typing file. */
void tagAsTypeSummary() {
add("/** @fileoverview @typeSummary */\n");
Expand All @@ -102,10 +100,6 @@ protected void add(String str) {
cc.add(str);
}

private void addIdentifier(String identifier) {
cc.addIdentifier(identifierEscape(identifier));
}

protected void add(Node n) {
add(n, Context.OTHER);
}
Expand Down Expand Up @@ -134,7 +128,8 @@ protected void add(Node n, Context context) {
Preconditions.checkState(
childCount == 2,
"Bad binary operator \"%s\": expected 2 arguments but got %s",
opstr, childCount);
opstr,
childCount);
int p = precedence(n);

// For right-hand-side of operations, only pass context if it's
Expand Down Expand Up @@ -641,9 +636,7 @@ protected void add(Node n, Context context) {

boolean preferLineBreaks =
type == Token.SCRIPT
|| (type == Token.BLOCK
&& !preserveBlock
&& n.getParent().isScript());
|| (type == Token.BLOCK && !preserveBlock && n.getParent().isScript());
for (Node c = first; c != null; c = c.getNext()) {
add(c, Context.STATEMENT);

Expand Down Expand Up @@ -780,7 +773,9 @@ protected void add(Node n, Context context) {
case GETELEM:
Preconditions.checkState(
childCount == 2,
"Bad GETELEM node: Expected 2 children but got %s. For node: %s", childCount, n);
"Bad GETELEM node: Expected 2 children but got %s. For node: %s",
childCount,
n);
addExpr(first, NodeUtil.precedence(type), context);
add("[");
add(first.getNext());
Expand Down Expand Up @@ -1271,6 +1266,10 @@ protected void add(Node n, Context context) {
cc.endSourceMapping(n);
}

private void addIdentifier(String identifier) {
cc.addIdentifier(identifierEscape(identifier));
}

private int precedence(Node n) {
if (n.isCast()) {
return precedence(n.getFirstChild());
Expand Down
8 changes: 4 additions & 4 deletions src/com/google/javascript/jscomp/CodingConventions.java
Expand Up @@ -128,13 +128,13 @@ public boolean isExported(String name, boolean local) {
}

@Override
public String getPackageName(StaticSourceFile source) {
return nextConvention.getPackageName(source);
public final boolean isExported(String name) {
return isExported(name, false) || isExported(name, true);
}

@Override
public final boolean isExported(String name) {
return isExported(name, false) || isExported(name, true);
public String getPackageName(StaticSourceFile source) {
return nextConvention.getPackageName(source);
}

@Override
Expand Down
22 changes: 11 additions & 11 deletions src/com/google/javascript/jscomp/CompilerOptions.java
Expand Up @@ -1604,13 +1604,6 @@ public void setIdGenerators(Set<String> idGenerators) {
this.idGenerators = builder.build();
}

/**
* Sets the hash function to use for Xid
*/
public void setXidHashFunction(Xid.HashFunction xidHashFunction) {
this.xidHashFunction = xidHashFunction;
}

/**
* Sets the id generators to replace.
*/
Expand All @@ -1627,6 +1620,13 @@ public void setIdGeneratorsMap(String previousMappings) {
this.idGeneratorsMapSerialized = previousMappings;
}

/**
* Sets the hash function to use for Xid
*/
public void setXidHashFunction(Xid.HashFunction xidHashFunction) {
this.xidHashFunction = xidHashFunction;
}

private Reach inlineFunctionsLevel;

/** Use {@link #setInlineFunctions(Reach)} instead */
Expand Down Expand Up @@ -1654,6 +1654,10 @@ public void setMaxFunctionSizeAfterInlining(int funAstSize) {
this.maxFunctionSizeAfterInlining = funAstSize;
}

public void setInlineVariables(boolean inlineVariables) {
this.inlineVariables = inlineVariables;
}

/**
* Set the variable inlining policy for the compiler.
*/
Expand Down Expand Up @@ -2244,10 +2248,6 @@ public void setCrossModuleMethodMotion(boolean crossModuleMethodMotion) {
this.crossModuleMethodMotion = crossModuleMethodMotion;
}

public void setInlineVariables(boolean inlineVariables) {
this.inlineVariables = inlineVariables;
}

public void setInlineLocalVariables(boolean inlineLocalVariables) {
this.inlineLocalVariables = inlineLocalVariables;
}
Expand Down
19 changes: 8 additions & 11 deletions src/com/google/javascript/jscomp/ConformanceRules.java
Expand Up @@ -866,24 +866,17 @@ && matchesProp(n.getFirstChild(), r)) {
return ConformanceResult.CONFORMANCE;
}

private boolean matchesProp(Node n, Restriction r) {
return n.isGetProp() && n.getLastChild().getString().equals(r.property);
}

private ConformanceResult checkConformance(
NodeTraversal t, Node n, Restriction r, boolean isCallInvocation) {
TypeIRegistry registry = t.getCompiler().getTypeIRegistry();
TypeI methodClassType = registry.getType(r.type);
Node lhs = isCallInvocation
? n.getFirstFirstChild()
: n.getFirstChild();
Node lhs = isCallInvocation ? n.getFirstFirstChild() : n.getFirstChild();
if (methodClassType != null && lhs.getTypeI() != null) {
TypeI targetType = lhs.getTypeI().restrictByNotNullOrUndefined();
if (targetType.isUnknownType()
|| targetType.isUnresolved()
|| targetType.isTop()
|| targetType.isEquivalentTo(
registry.getNativeType(JSTypeNative.OBJECT_TYPE))) {
|| targetType.isUnresolved()
|| targetType.isTop()
|| targetType.isEquivalentTo(registry.getNativeType(JSTypeNative.OBJECT_TYPE))) {
if (reportLooseTypeViolations
&& !ConformanceUtil.validateCall(
compiler, n.getParent(), r.restrictedCallType, isCallInvocation)) {
Expand All @@ -899,6 +892,10 @@ private ConformanceResult checkConformance(
return ConformanceResult.CONFORMANCE;
}

private boolean matchesProp(Node n, Restriction r) {
return n.isGetProp() && n.getLastChild().getString().equals(r.property);
}

/**
* From a provide name extract the method name.
*/
Expand Down
35 changes: 15 additions & 20 deletions src/com/google/javascript/jscomp/DiagnosticGroup.java
Expand Up @@ -60,29 +60,13 @@ private DiagnosticGroup(DiagnosticType type) {
this.types = ImmutableSet.of(type);
}

// DiagnosticGroups with only a single DiagnosticType.
private static final Map<DiagnosticType, DiagnosticGroup> singletons =
new HashMap<>();

/** Create a diagnostic group that matches only the given type. */
public static synchronized DiagnosticGroup forType(DiagnosticType type) {
if (!singletons.containsKey(type)) {
singletons.put(type, new DiagnosticGroup(type));
}
return singletons.get(type);
}

/**
* Create a composite group.
*/
public DiagnosticGroup(DiagnosticGroup ...groups) {
/** Create a composite group. */
public DiagnosticGroup(DiagnosticGroup... groups) {
this(null, groups);
}

/**
* Create a composite group.
*/
public DiagnosticGroup(String name, DiagnosticGroup ...groups) {
/** Create a composite group. */
public DiagnosticGroup(String name, DiagnosticGroup... groups) {
ImmutableSet.Builder<DiagnosticType> set = ImmutableSet.builder();

for (DiagnosticGroup group : groups) {
Expand All @@ -93,6 +77,17 @@ public DiagnosticGroup(String name, DiagnosticGroup ...groups) {
this.types = set.build();
}

// DiagnosticGroups with only a single DiagnosticType.
private static final Map<DiagnosticType, DiagnosticGroup> singletons = new HashMap<>();

/** Create a diagnostic group that matches only the given type. */
public static synchronized DiagnosticGroup forType(DiagnosticType type) {
if (!singletons.containsKey(type)) {
singletons.put(type, new DiagnosticGroup(type));
}
return singletons.get(type);
}

/**
* Returns whether the given error's type matches a type
* in this group.
Expand Down

0 comments on commit 91f3cca

Please sign in to comment.