barty/D4J-Repair huggingface dataset:
File: src/com/google/javascript/jscomp/InlineFunctions.java
Issue: Closure Compiler failed to translate all instances of a function name
What steps will reproduce the problem?
1. Compile the attached jQuery Multicheck plugin using SIMPLE optimization.

What is the expected output? What do you see instead?
You expect that the function preload_check_all() gets its name translated appropriately. In fact, the Closure Compiler breaks the code by changing the function declaration but NOT changing the call to the function on line 76.

Buggy code:
private void findCalledFunctions(
    Node node, Set<String> changed) {
  Preconditions.checkArgument(changed != null);
  // For each referenced function, add a new reference
  if (node.getType() == Token.CALL) {
    Node child = node.getFirstChild();
    if (child.getType() == Token.NAME) {
      changed.add(child.getString());
    }
  }

  for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
    findCalledFunctions(c, changed);
  }
}

Fixed code:
private void findCalledFunctions(
    Node node, Set<String> changed) {
  Preconditions.checkArgument(changed != null);
  // For each referenced function, add a new reference
  if (node.getType() == Token.NAME) {
    if (isCandidateUsage(node)) {
      changed.add(node.getString());
    }
  }

  for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
    findCalledFunctions(c, changed);
  }
}
File: src/com/google/javascript/jscomp/PeepholeFoldConstants.java
Issue: peephole constants folding pass is trying to fold [][11] as if it were a property lookup instead of a property assignment
What steps will reproduce the problem?
1.Try on line CC with Advance
2.On the following 2-line code
3.
What is the expected output? What do you see instead?
// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==

var Mdt=[];
Mdt[11] = ['22','19','19','16','21','18','16','20','17','17','21','17'];

The error:
JSC_INDEX_OUT_OF_BOUNDS_ERROR: Array index out of bounds: NUMBER 11.0
2 [sourcename: Input_0] : number at line 2 character 4

What version of the product are you using? On what operating system?
The online version on 201.07.27

Buggy code:
private Node tryFoldArrayAccess(Node n, Node left, Node right) {
  Node parent = n.getParent();
  // If GETPROP/GETELEM is used as assignment target the array literal is
  // acting as a temporary we can't fold it here:
  //    "[][0] += 1"

  if (right.getType() != Token.NUMBER) {
    // Sometimes people like to use complex expressions to index into
    // arrays, or strings to index into array methods.
    return n;
  }

  double index = right.getDouble();
  int intIndex = (int) index;
  if (intIndex != index) {
    error(INVALID_GETELEM_INDEX_ERROR, right);
    return n;
  }

  if (intIndex < 0) {
    error(INDEX_OUT_OF_BOUNDS_ERROR, right);
    return n;
  }

  Node elem = left.getFirstChild();
  for (int i = 0; elem != null && i < intIndex; i++) {
    elem = elem.getNext();
  }

  if (elem == null) {
    error(INDEX_OUT_OF_BOUNDS_ERROR, right);
    return n;
  }

  if (elem.getType() == Token.EMPTY) {
    elem = NodeUtil.newUndefinedNode(elem);
  } else {
    left.removeChild(elem);
  }

  // Replace the entire GETELEM with the value
  n.getParent().replaceChild(n, elem);
  reportCodeChange();
  return elem;
}

Fixed code:
private Node tryFoldArrayAccess(Node n, Node left, Node right) {
  Node parent = n.getParent();
  // If GETPROP/GETELEM is used as assignment target the array literal is
  // acting as a temporary we can't fold it here:
  //    "[][0] += 1"
  if (isAssignmentTarget(n)) {
    return n;
  }

  if (right.getType() != Token.NUMBER) {
    // Sometimes people like to use complex expressions to index into
    // arrays, or strings to index into array methods.
    return n;
  }

  double index = right.getDouble();
  int intIndex = (int) index;
  if (intIndex != index) {
    error(INVALID_GETELEM_INDEX_ERROR, right);
    return n;
  }

  if (intIndex < 0) {
    error(INDEX_OUT_OF_BOUNDS_ERROR, right);
    return n;
  }

  Node elem = left.getFirstChild();
  for (int i = 0; elem != null && i < intIndex; i++) {
    elem = elem.getNext();
  }

  if (elem == null) {
    error(INDEX_OUT_OF_BOUNDS_ERROR, right);
    return n;
  }

  if (elem.getType() == Token.EMPTY) {
    elem = NodeUtil.newUndefinedNode(elem);
  } else {
    left.removeChild(elem);
  }

  // Replace the entire GETELEM with the value
  n.getParent().replaceChild(n, elem);
  reportCodeChange();
  return elem;
}
File: src/com/google/javascript/rhino/jstype/PrototypeObjectType.java
Issue: anonymous object type inference inconsistency when used in union
Code:
/** @param {{prop: string, prop2: (string|undefined)}} record */
var func = function(record) {
  window.console.log(record.prop);
}

/** @param {{prop: string, prop2: (string|undefined)}|string} record */
var func2 = function(record) {
  if (typeof record == 'string') {
    window.console.log(record);
  } else {
    window.console.log(record.prop);
  }
}

func({prop: 'a'});
func2({prop: 'a'});

errors with:
ERROR - actual parameter 1 of func2 does not match formal parameter
found   : {prop: string}
required: (string|{prop: string, prop2: (string|undefined)})
func2({prop: 'a'});

the type of the record input to func and func2 are identical but the parameters to func2 allow some other type.

Buggy code:
public void matchConstraint(JSType constraint) {
  // We only want to match constraints on anonymous types.
  if (hasReferenceName()) {
    return;
  }

  // Handle the case where the constraint object is a record type.
  //
  // param constraint {{prop: (number|undefined)}}
  // function f(constraint) {}
  // f({});
  //
  // We want to modify the object literal to match the constraint, by
  // taking any each property on the record and trying to match
  // properties on this object.
  if (constraint.isRecordType()) {
    matchRecordTypeConstraint(constraint.toObjectType());
  }
}

Fixed code:
public void matchConstraint(JSType constraint) {
  // We only want to match constraints on anonymous types.
  if (hasReferenceName()) {
    return;
  }

  // Handle the case where the constraint object is a record type.
  //
  // param constraint {{prop: (number|undefined)}}
  // function f(constraint) {}
  // f({});
  //
  // We want to modify the object literal to match the constraint, by
  // taking any each property on the record and trying to match
  // properties on this object.
  if (constraint.isRecordType()) {
    matchRecordTypeConstraint(constraint.toObjectType());
  } else if (constraint.isUnionType()) {
    for (JSType alt : constraint.toMaybeUnionType().getAlternates()) {
      if (alt.isRecordType()) {
        matchRecordTypeConstraint(alt.toObjectType());
      }
    }
  }
}
File: src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
Issue: String conversion optimization is incorrect
What steps will reproduce the problem?

var f = {
  valueOf: function() { return undefined; }
}
String(f)

What is the expected output? What do you see instead?

Expected output: "[object Object]"
Actual output: "undefined"

What version of the product are you using? On what operating system?

All versions (http://closure-compiler.appspot.com/ as well).

Please provide any additional information below.

The compiler optimizes String(x) calls by replacing them with x + ''. This is correct in most cases, but incorrect in corner cases like the one mentioned above.

Buggy code:
private Node tryFoldSimpleFunctionCall(Node n) {
  Preconditions.checkState(n.isCall());
  Node callTarget = n.getFirstChild();
  if (callTarget != null && callTarget.isName() &&
        callTarget.getString().equals("String")) {
    // Fold String(a) to '' + (a) on immutable literals,
    // which allows further optimizations
    //
    // We can't do this in the general case, because String(a) has
    // slightly different semantics than '' + (a). See
    // http://code.google.com/p/closure-compiler/issues/detail?id=759
    Node value = callTarget.getNext();
    if (value != null) {
      Node addition = IR.add(
          IR.string("").srcref(callTarget),
          value.detachFromParent());
      n.getParent().replaceChild(n, addition);
      reportCodeChange();
      return addition;
    }
  }
  return n;
}

Fixed code:
private Node tryFoldSimpleFunctionCall(Node n) {
  Preconditions.checkState(n.isCall());
  Node callTarget = n.getFirstChild();
  if (callTarget != null && callTarget.isName() &&
        callTarget.getString().equals("String")) {
    // Fold String(a) to '' + (a) on immutable literals,
    // which allows further optimizations
    //
    // We can't do this in the general case, because String(a) has
    // slightly different semantics than '' + (a). See
    // http://code.google.com/p/closure-compiler/issues/detail?id=759
    Node value = callTarget.getNext();
    if (value != null && value.getNext() == null &&
        NodeUtil.isImmutableValue(value)) {
      Node addition = IR.add(
          IR.string("").srcref(callTarget),
          value.detachFromParent());
      n.getParent().replaceChild(n, addition);
      reportCodeChange();
      return addition;
    }
  }
  return n;
}
File: src/com/google/javascript/jscomp/ScopedAliases.java
Issue: goog.scope doesn't properly check declared functions
The following code is a compiler error:

goog.scope(function() {
  var x = function(){};
});

but the following code is not:

goog.scope(function() {
  function x() {}
});

Both code snippets should be a compiler error, because they prevent the goog.scope from being unboxed.

Buggy code:
private void findAliases(NodeTraversal t) {
  Scope scope = t.getScope();
  for (Var v : scope.getVarIterable()) {
    Node n = v.getNode();
    int type = n.getType();
    Node parent = n.getParent();
    if (parent.isVar()) {
      if (n.hasChildren() && n.getFirstChild().isQualifiedName()) {
      String name = n.getString();
      Var aliasVar = scope.getVar(name);
      aliases.put(name, aliasVar);

      String qualifiedName =
          aliasVar.getInitialValue().getQualifiedName();
      transformation.addAlias(name, qualifiedName);
      // Bleeding functions already get a BAD_PARAMETERS error, so just
      // do nothing.
      // Parameters of the scope function also get a BAD_PARAMETERS
      // error.
    } else {
      // TODO(robbyw): Support using locals for private variables.
      report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
    }
    }
  }
}

Fixed code:
private void findAliases(NodeTraversal t) {
  Scope scope = t.getScope();
  for (Var v : scope.getVarIterable()) {
    Node n = v.getNode();
    int type = n.getType();
    Node parent = n.getParent();
    if (parent.isVar() &&
        n.hasChildren() && n.getFirstChild().isQualifiedName()) {
      String name = n.getString();
      Var aliasVar = scope.getVar(name);
      aliases.put(name, aliasVar);

      String qualifiedName =
          aliasVar.getInitialValue().getQualifiedName();
      transformation.addAlias(name, qualifiedName);
    } else if (v.isBleedingFunction()) {
      // Bleeding functions already get a BAD_PARAMETERS error, so just
      // do nothing.
    } else if (parent.getType() == Token.LP) {
      // Parameters of the scope function also get a BAD_PARAMETERS
      // error.
    } else {
      // TODO(robbyw): Support using locals for private variables.
      report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
    }
  }
}
File: src/com/google/javascript/jscomp/TypeInference.java
Issue: anonymous object type inference behavior is different when calling constructors
The following compiles fine with:
java -jar build/compiler.jar --compilation_level=ADVANCED_OPTIMIZATIONS --jscomp_error=accessControls --jscomp_error=checkTypes --jscomp_error=checkVars --js ~/Desktop/reverse.js

reverse.js:
/**
 * @param {{prop1: string, prop2: (number|undefined)}} parry
 */
function callz(parry) {
  if (parry.prop2 && parry.prop2 < 5) alert('alright!');
  alert(parry.prop1);
}

callz({prop1: 'hi'});

However, the following does not:
/**
 * @param {{prop1: string, prop2: (number|undefined)}} parry
 * @constructor
 */
function callz(parry) {
  if (parry.prop2 && parry.prop2 < 5) alert('alright!');
  alert(parry.prop1);
}

new callz({prop1: 'hi'});

/Users/dolapo/Desktop/reverse.js:10: ERROR - actual parameter 1 of callz does not match formal parameter
found   : {prop1: string}
required: {prop1: string, prop2: (number|undefined)}
new callz({prop1: 'hi'});

Thanks!

Buggy code:
private FlowScope traverseNew(Node n, FlowScope scope) {

  Node constructor = n.getFirstChild();
  scope = traverse(constructor, scope);
  JSType constructorType = constructor.getJSType();
  JSType type = null;
  if (constructorType != null) {
    constructorType = constructorType.restrictByNotNullOrUndefined();
    if (constructorType.isUnknownType()) {
      type = getNativeType(UNKNOWN_TYPE);
    } else {
      FunctionType ct = constructorType.toMaybeFunctionType();
      if (ct == null && constructorType instanceof FunctionType) {
        // If constructorType is a NoObjectType, then toMaybeFunctionType will
        // return null. But NoObjectType implements the FunctionType
        // interface, precisely because it can validly construct objects.
        ct = (FunctionType) constructorType;
      }
      if (ct != null && ct.isConstructor()) {
        type = ct.getInstanceType();
      }
    }
  }
  n.setJSType(type);
  for (Node arg = constructor.getNext(); arg != null; arg = arg.getNext()) {
    scope = traverse(arg, scope);
  }
  return scope;
}

Fixed code:
private FlowScope traverseNew(Node n, FlowScope scope) {
  scope = traverseChildren(n, scope);

  Node constructor = n.getFirstChild();
  JSType constructorType = constructor.getJSType();
  JSType type = null;
  if (constructorType != null) {
    constructorType = constructorType.restrictByNotNullOrUndefined();
    if (constructorType.isUnknownType()) {
      type = getNativeType(UNKNOWN_TYPE);
    } else {
      FunctionType ct = constructorType.toMaybeFunctionType();
      if (ct == null && constructorType instanceof FunctionType) {
        // If constructorType is a NoObjectType, then toMaybeFunctionType will
        // return null. But NoObjectType implements the FunctionType
        // interface, precisely because it can validly construct objects.
        ct = (FunctionType) constructorType;
      }
      if (ct != null && ct.isConstructor()) {
        type = ct.getInstanceType();
        backwardsInferenceFromCallSite(n, ct);
      }
    }
  }
  n.setJSType(type);
  return scope;
}
File: src/com/google/javascript/jscomp/TypeInference.java
Issue: assignment to object in conditional causes type error on function w/ record type return type
slightly dodgy code :)

/** @returns {{prop1: (Object|undefined), prop2: (string|undefined), prop3: (string|undefined)}} */
function func(a, b) {
  var results;
  if (a) {
    results = {};
    results.prop1 = {a: 3};
  }
  if (b) {
    results = results || {};
    results.prop2 = 'prop2';
  } else {
    results = results || {};
    results.prop3 = 'prop3';
  }
  return results;
}
results in this error:

JSC_TYPE_MISMATCH: inconsistent return type
found   : ({prop1: {a: number}}|{})
required: {prop1: (Object|null|undefined), prop2: (string|undefined), prop3: (string|undefined)} at line 18 character 7
return results;

defining results on the first line on the function causes it the world.
the still dodgy, but slightly less so, use of this is if the function return type were that record type|undefined and not all branches were guaranteed to be executed.

Buggy code:
private void inferPropertyTypesToMatchConstraint(
    JSType type, JSType constraint) {
  if (type == null || constraint == null) {
    return;
  }

  ObjectType constraintObj =
      ObjectType.cast(constraint.restrictByNotNullOrUndefined());
  if (constraintObj != null && constraintObj.isRecordType()) {
    ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined());
    if (objType != null) {
      for (String prop : constraintObj.getOwnPropertyNames()) {
        JSType propType = constraintObj.getPropertyType(prop);
        if (!objType.isPropertyTypeDeclared(prop)) {
          JSType typeToInfer = propType;
          if (!objType.hasProperty(prop)) {
            typeToInfer =
                getNativeType(VOID_TYPE).getLeastSupertype(propType);
          }
          objType.defineInferredProperty(prop, typeToInfer, null);
        }
      }
    }
  }
}

Fixed code:
private void inferPropertyTypesToMatchConstraint(
    JSType type, JSType constraint) {
  if (type == null || constraint == null) {
    return;
  }

  ObjectType constraintObj =
      ObjectType.cast(constraint.restrictByNotNullOrUndefined());
  if (constraintObj != null) {
    type.matchConstraint(constraintObj);
  }
}
File: src/com/google/javascript/jscomp/CodeConsumer.java
Issue: Identifier minus a negative number needs a space between the "-"s
What steps will reproduce the problem?
1. Compile the attached file with      java -jar build/compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js bulletfail.js --js_output_file cc.js
2. Try to run the file in a JS engine, for example           node cc.js

What is the expected output? What do you see instead?

The file does not parse properly, because it contains

  g--0.0

This is subtraction of a negative number, but it looks like JS engines interpret it as decrementing g, and then fail to parse the 0.0. (g- -0.0, with a space, would parse ok.)

What version of the product are you using? On what operating system?

Trunk closure compiler on Ubuntu

Please provide any additional information below.

Buggy code:
void addNumber(double x) {
  // This is not pretty printing. This is to prevent misparsing of x- -4 as
  // x--4 (which is a syntax error).
  char prev = getLastChar();
  boolean negativeZero = isNegativeZero(x);
  if (x < 0 && prev == '-') {
    add(" ");
  }

  if ((long) x == x && !negativeZero) {
    long value = (long) x;
    long mantissa = value;
    int exp = 0;
    if (Math.abs(x) >= 100) {
      while (mantissa / 10 * Math.pow(10, exp + 1) == value) {
        mantissa /= 10;
        exp++;
      }
    }
    if (exp > 2) {
      add(Long.toString(mantissa) + "E" + Integer.toString(exp));
    } else {
      add(Long.toString(value));
    }
  } else {
    add(String.valueOf(x));
  }
}

Fixed code:
void addNumber(double x) {
  // This is not pretty printing. This is to prevent misparsing of x- -4 as
  // x--4 (which is a syntax error).
  char prev = getLastChar();
  boolean negativeZero = isNegativeZero(x);
  if ((x < 0 || negativeZero) && prev == '-') {
    add(" ");
  }

  if ((long) x == x && !negativeZero) {
    long value = (long) x;
    long mantissa = value;
    int exp = 0;
    if (Math.abs(x) >= 100) {
      while (mantissa / 10 * Math.pow(10, exp + 1) == value) {
        mantissa /= 10;
        exp++;
      }
    }
    if (exp > 2) {
      add(Long.toString(mantissa) + "E" + Integer.toString(exp));
    } else {
      add(Long.toString(value));
    }
  } else {
    add(String.valueOf(x));
  }
}
File: src/com/google/javascript/rhino/jstype/NamedType.java
Issue: Converting from an interface type to a constructor which @implements itself causes stack overflow.
// Options: --externs externs/es3.js --property_renaming OFF --variable_renaming OFF --jscomp_warning=checkTypes --js=t.js

// File: t.js
/**
 * @interface
 */
var OtherType = function() {}

/**
 * @implements {MyType}
 * @constructor
 */
var MyType = function() {}

/**
 * @type {MyType}
 */
var x = /** @type {!OtherType} */ (new Object());

Get Infinite recursion in:

PrototypeObjectType.isSubtype @ 350

Options:

- prevent cycles in the inheritance/implements graph
- detect cycles after they are created and exit compilation before any subsequent passes run
- detect and remove cycles after they are created but before any subsequent passes run
- make every subsequent pass robust against cycles in that graph

Buggy code:
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) {
  // TODO(user): Investigate whether it is really necessary to keep two
  // different mechanisms for resolving named types, and if so, which order
  // makes more sense. Now, resolution via registry is first in order to
  // avoid triggering the warnings built into the resolution via properties.
  boolean resolved = resolveViaRegistry(t, enclosing);
  if (detectImplicitPrototypeCycle()) {
    handleTypeCycle(t);
  }

  if (resolved) {
    super.resolveInternal(t, enclosing);
    finishPropertyContinuations();
    return registry.isLastGeneration() ?
        getReferencedType() : this;
  }

  resolveViaProperties(t, enclosing);
  if (detectImplicitPrototypeCycle()) {
    handleTypeCycle(t);
  }

  super.resolveInternal(t, enclosing);
  if (isResolved()) {
    finishPropertyContinuations();
  }
  return registry.isLastGeneration() ?
      getReferencedType() : this;
}

Fixed code:
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) {
  // TODO(user): Investigate whether it is really necessary to keep two
  // different mechanisms for resolving named types, and if so, which order
  // makes more sense. Now, resolution via registry is first in order to
  // avoid triggering the warnings built into the resolution via properties.
  boolean resolved = resolveViaRegistry(t, enclosing);
  if (detectInheritanceCycle()) {
    handleTypeCycle(t);
  }

  if (resolved) {
    super.resolveInternal(t, enclosing);
    finishPropertyContinuations();
    return registry.isLastGeneration() ?
        getReferencedType() : this;
  }

  resolveViaProperties(t, enclosing);
  if (detectInheritanceCycle()) {
    handleTypeCycle(t);
  }

  super.resolveInternal(t, enclosing);
  if (isResolved()) {
    finishPropertyContinuations();
  }
  return registry.isLastGeneration() ?
      getReferencedType() : this;
}
File: src/com/google/javascript/jscomp/parsing/IRFactory.java
Issue: Simple "Whitespace only" compression removing "each" keyword from "for each (var x in arr)" loop
What steps will reproduce the problem?
See below code snippet before after compression

---Before---
contactcenter.screenpop.updatePopStatus = function(stamp, status) {
for each ( var curTiming in this.timeLog.timings ) {
if ( curTiming.callId == stamp ) {
curTiming.flag = status;
break;
}
}
};
---After---
contactcenter.screenpop.updatePopStatus=function(stamp,status){for(var curTiming in this.timeLog.timings)if(curTiming.callId==stamp){curTiming.flag=status;break}};

What is the expected output? What do you see instead?
---each keyword should be preserved

What version of the product are you using? On what operating system?
Please provide any additional information below.
for each (** in **) --->  returns object value
for (** in **) --> returns index

Buggy code:
Node processForInLoop(ForInLoop loopNode) {

    // Return the bare minimum to put the AST in a valid state.
  return newNode(
      Token.FOR,
      transform(loopNode.getIterator()),
      transform(loopNode.getIteratedObject()),
      transformBlock(loopNode.getBody()));
}

Fixed code:
Node processForInLoop(ForInLoop loopNode) {
  if (loopNode.isForEach()) {
    errorReporter.error(
        "unsupported language extension: for each",
        sourceName,
        loopNode.getLineno(), "", 0);

    // Return the bare minimum to put the AST in a valid state.
    return newNode(Token.EXPR_RESULT, Node.newNumber(0));
  }
  return newNode(
      Token.FOR,
      transform(loopNode.getIterator()),
      transform(loopNode.getIteratedObject()),
      transformBlock(loopNode.getBody()));
}