barty/D4J-Repair huggingface dataset:
File: src/com/google/javascript/jscomp/CodeConsumer.java
Issue: alert(/ / / / /)
alert(/ / / / /);
output: alert(/ /// /);
should be: alert(/ // / /);

Buggy code:
void add(String newcode) {
  maybeEndStatement();

  if (newcode.length() == 0) {
    return;
  }

  char c = newcode.charAt(0);
  if ((isWordChar(c) || c == '\\') &&
      isWordChar(getLastChar())) {
    // need space to separate. This is not pretty printing.
    // For example: "return foo;"
    append(" ");
    // Do not allow a forward slash to appear after a DIV.
    // For example,
    // REGEXP DIV REGEXP
    // is valid and should print like
    // / // / /
  }

  append(newcode);
}

Fixed code:
void add(String newcode) {
  maybeEndStatement();

  if (newcode.length() == 0) {
    return;
  }

  char c = newcode.charAt(0);
  if ((isWordChar(c) || c == '\\') &&
      isWordChar(getLastChar())) {
    // need space to separate. This is not pretty printing.
    // For example: "return foo;"
    append(" ");
  } else if (c == '/' && getLastChar() == '/') {
    // Do not allow a forward slash to appear after a DIV.
    // For example,
    // REGEXP DIV REGEXP
    // is valid and should print like
    // / // / /
    append(" ");
  }

  append(newcode);
}
File: src/com/google/javascript/jscomp/CodeConsumer.java
Issue: -0.0 becomes 0 even in whitespace mode
Affects dart: http://code.google.com/p/dart/issues/detail?id=146

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();
  if (x < 0 && prev == '-') {
    add(" ");
  }

  if ((long) x == x) {
    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();
  if (x < 0 && prev == '-') {
    add(" ");
  }

  if ((long) x == x && !isNegativeZero(x)) {
    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/jscomp/ClosureCodingConvention.java
Issue: compiler crashes when  goog.provide used with non string
What steps will reproduce the problem?
1. insert  goog.provide(some.function);
2. compile.
3.
What is the expected output? What do you see instead?

This should give an error diagnostic. What it gives is:

java.lang.RuntimeException: java.lang.RuntimeException: INTERNAL COMPILER ERROR.
Please email js-compiler@google.com with this stack trace.
GETPROP 17 [originalname: Spike] [source_file: file.js] is not a string node
 Node(CALL): file.js:17:12
goog.provide(mine.Spike);
...
[stack traces...]

I think this is the current build as of the day of this report.

Buggy code:
private static String extractClassNameIfGoog(Node node, Node parent,
    String functionName){
  String className = null;
  if (NodeUtil.isExprCall(parent)) {
    Node callee = node.getFirstChild();
    if (callee != null && callee.getType() == Token.GETPROP) {
      String qualifiedName = callee.getQualifiedName();
      if (functionName.equals(qualifiedName)) {
        Node target = callee.getNext();
        if (target != null) {
          className = target.getString();
        }
      }
    }
  }
  return className;
}

Fixed code:
private static String extractClassNameIfGoog(Node node, Node parent,
    String functionName){
  String className = null;
  if (NodeUtil.isExprCall(parent)) {
    Node callee = node.getFirstChild();
    if (callee != null && callee.getType() == Token.GETPROP) {
      String qualifiedName = callee.getQualifiedName();
      if (functionName.equals(qualifiedName)) {
        Node target = callee.getNext();
        if (target != null && target.getType() == Token.STRING) {
          className = target.getString();
        }
      }
    }
  }
  return className;
}
File: src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java
Issue: Advanced compilations renames a function and then deletes it, leaving a reference to a renamed but non-existent function
If we provide the below code to advanced:

function A() {
this._x = 1;
}

A.prototype['func1'] = // done to save public reference to func1
A.prototype.func1 = function() {
  this._x = 2;
  this.func2();
}

A.prototype.func2 = function() {
  this._x = 3;
  this.func3();
}

window['A'] = A;

We get the output:

function a() {
  this.a = 1
}
a.prototype.func1 = a.prototype.b = function() {
  this.a = 2;
  this.c() // Problem!
};
window.A = a;

So the compiler emits no errors, and renames 'func2' to 'c' but ends up throwing away the definition of that function!

The problem arises when I use:

A.prototype['func1'] = // done to save public reference to func1
A.prototype.func1 = function() {
...
}

The ['func1'] line is apparently enough to save the reference correctly, but also has the side effect of causing the function innards to do the wrong thing.

I can of course instead write it as:

A.prototype['func1'] = A.prototype.func1;
A.prototype.func1 = function() {
  this._x = 2;
  this.func2();
}

In which case Advanced will compile correctly and the results will also be valid.

function a() {
  this.a = 1
}
a.prototype.func1 = a.prototype.b;
a.prototype.b = function() {
  this.a = 2;
  this.a = 3 // func2, correctly minified
};
window.A = a;

For now I can just use the expected way of declaring that func1 export, but since the compiler returns with no errors or warnings and creates a function with no definition, it seems worth reporting.

Buggy code:
private boolean isPrototypePropertyAssign(Node assign) {
  Node n = assign.getFirstChild();
  if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)
      && n.getType() == Token.GETPROP
      ) {
    // We want to exclude the assignment itself from the usage list
    boolean isChainedProperty =
        n.getFirstChild().getType() == Token.GETPROP;

    if (isChainedProperty) {
      Node child = n.getFirstChild().getFirstChild().getNext();

      if (child.getType() == Token.STRING &&
          child.getString().equals("prototype")) {
        return true;
      }
    }
  }

  return false;
}

Fixed code:
private boolean isPrototypePropertyAssign(Node assign) {
  Node n = assign.getFirstChild();
  if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)
      && n.getType() == Token.GETPROP
      && assign.getParent().getType() == Token.EXPR_RESULT) {
    // We want to exclude the assignment itself from the usage list
    boolean isChainedProperty =
        n.getFirstChild().getType() == Token.GETPROP;

    if (isChainedProperty) {
      Node child = n.getFirstChild().getFirstChild().getNext();

      if (child.getType() == Token.STRING &&
          child.getString().equals("prototype")) {
        return true;
      }
    }
  }

  return false;
}
File: src/com/google/javascript/jscomp/type/ChainableReverseAbstractInterpreter.java
Issue: Bad type inference with goog.isFunction and friends
experimental/johnlenz/typeerror/test.js:16: WARNING - Property length
never defined on Number
      var i = object.length;

This is the reduced test case:

/**
 * @param {*} object Any object.
 * @return {boolean}
 */
test.isMatched = function(object) {
  if (goog.isDef(object)) {
    if (goog.isFunction(object)) {
      // return object();
    } else if (goog.isBoolean(object)) {
      // return object;
    } else if (goog.isString(object)) {
      // return test.isDef(object);
    } else if (goog.isArray(object)) {
      var i = object.length;
    }
  }
  return false;
};

Buggy code:
public JSType caseObjectType(ObjectType type) {
  if (value.equals("function")) {
    JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);
    return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null;
      // Objects are restricted to "Function", subtypes are left
      // Only filter out subtypes of "function"
  }
  return matchesExpectation("object") ? type : null;
}

Fixed code:
public JSType caseObjectType(ObjectType type) {
  if (value.equals("function")) {
    JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);
    if (resultEqualsValue) {
      // Objects are restricted to "Function", subtypes are left
      return ctorType.getGreatestSubtype(type);
    } else {
      // Only filter out subtypes of "function"
      return type.isSubtype(ctorType) ? null : type;
    }
  }
  return matchesExpectation("object") ? type : null;
}
File: src/com/google/javascript/jscomp/TypedScopeCreator.java
Issue: unexpected typed coverage of less than 100%
What steps will reproduce the problem?
1. Create JavaScript file:
/*global window*/
/*jslint sub: true*/
/**
 * @constructor
 * @param {!Element} element
 */
function Example(element) {
    /**
     * @param {!string} ns
     * @param {!string} name
     * @return {undefined}
     */
    this.appendElement = function appendElement(ns, name) {
        var e = element.ownerDocument.createElementNS(ns, name);
        element.appendChild(e);
    };
}
window["Example"] = Example;
2. compile it:
java -jar compiler.jar --jscomp_error checkTypes --summary_detail_level 3 --js v.js --js_output_file compiled.js
3. observe the outcome:
0 error(s), 0 warning(s), 73.7% typed

What is the expected output? What do you see instead?
This was expected:
0 error(s), 0 warning(s), 100% typed

What version of the product are you using? On what operating system?
Closure Compiler Version: 964, Built on: 2011/04/05 14:31 on GNU/Linux.

Please provide any additional information below.

Buggy code:
private void declareArguments(Node functionNode) {
  Node astParameters = functionNode.getFirstChild().getNext();
  Node body = astParameters.getNext();
  FunctionType functionType = (FunctionType) functionNode.getJSType();
  if (functionType != null) {
    Node jsDocParameters = functionType.getParametersNode();
    if (jsDocParameters != null) {
      Node jsDocParameter = jsDocParameters.getFirstChild();
      for (Node astParameter : astParameters.children()) {
        if (jsDocParameter != null) {
          defineSlot(astParameter, functionNode,
              jsDocParameter.getJSType(), true);
          jsDocParameter = jsDocParameter.getNext();
        } else {
          defineSlot(astParameter, functionNode, null, true);
        }
      }
    }
  }
} // end declareArguments

Fixed code:
private void declareArguments(Node functionNode) {
  Node astParameters = functionNode.getFirstChild().getNext();
  Node body = astParameters.getNext();
  FunctionType functionType = (FunctionType) functionNode.getJSType();
  if (functionType != null) {
    Node jsDocParameters = functionType.getParametersNode();
    if (jsDocParameters != null) {
      Node jsDocParameter = jsDocParameters.getFirstChild();
      for (Node astParameter : astParameters.children()) {
        if (jsDocParameter != null) {
          defineSlot(astParameter, functionNode,
              jsDocParameter.getJSType(), false);
          jsDocParameter = jsDocParameter.getNext();
        } else {
          defineSlot(astParameter, functionNode, null, true);
        }
      }
    }
  }
} // end declareArguments
File: src/com/google/javascript/rhino/jstype/JSType.java
Issue: .indexOf fails to produce missing property warning
The following code compiled with VERBOSE warnings or with the missingProperties check enabled fails to produce a warning or error:

var s = new String("hello");
alert(s.toLowerCase.indexOf("l"));

However, other string functions do properly produce the warning:

var s = new String("hello");
alert(s.toLowerCase.substr(0, 1));

Buggy code:
public final boolean isEmptyType() {
  return isNoType() || isNoObjectType() || isNoResolvedType();
}

Fixed code:
public final boolean isEmptyType() {
  return isNoType() || isNoObjectType() || isNoResolvedType() ||
      (registry.getNativeFunctionType(
           JSTypeNative.LEAST_FUNCTION_TYPE) == this);
}
File: src/com/google/javascript/jscomp/CommandLineRunner.java
Issue: Cannot see version with --version
What steps will reproduce the problem?
1. Download sources of latest (r698) command-line version of closure compiler.
2. Build (with ant from command line).
3. Run compiler (java -jar compiler.jar --version).

What is the expected output?
Closure Compiler (http://code.google.com/closure/compiler)
Version: 698
Built on: 2011/01/17 12:16

What do you see instead?
Опция "--version" требует операнд
(Option "--version" requires operand)
and full list of options with description.

What version of the product are you using? On what operating system?
Latest source of command-line compiler from SVN (r698). OS Linux Mint 7, Sun Java 1.6.0_22.

Please provide any additional information below.
When running compiler with
java -jar compiler.jar --version ?
it shows error message, then version info, then full list of options.

Buggy code:
public int parseArguments(Parameters params) throws CmdLineException {
  String param = params.getParameter(0);

  if (param == null) {
    setter.addValue(true);
    return 0;
  } else {
    String lowerParam = param.toLowerCase();
    if (TRUES.contains(lowerParam)) {
      setter.addValue(true);
    } else if (FALSES.contains(lowerParam)) {
      setter.addValue(false);
    } else {
      setter.addValue(true);
      return 0;
    }
    return 1;
  }
}

Fixed code:
public int parseArguments(Parameters params) throws CmdLineException {
  String param = null;
  try {
    param = params.getParameter(0);
  } catch (CmdLineException e) {}

  if (param == null) {
    setter.addValue(true);
    return 0;
  } else {
    String lowerParam = param.toLowerCase();
    if (TRUES.contains(lowerParam)) {
      setter.addValue(true);
    } else if (FALSES.contains(lowerParam)) {
      setter.addValue(false);
    } else {
      setter.addValue(true);
      return 0;
    }
    return 1;
  }
}
File: src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
Issue: IE8 error: Object doesn't support this action
What steps will reproduce the problem?
1. Use script with fragment like
    if (e.onchange) {
      e.onchange({
        _extendedByPrototype: Prototype.emptyFunction,
        target: e
      });
    }
2. Compile with Compiler (command-line, latest version)
3. Use in IE8

What is the expected output?
Script:
if(b.onchange){b.onchange({_extendedByPrototype:Prototype.emptyFunction,target
:b})}

What do you see instead?
Script:
b.onchange&&b.onchange({_extendedByPrototype:Prototype.emptyFunction,target
:b})
IE8:
Error message "Object doesn't support this action"

What version of the product are you using? On what operating system?
Version: 20100917 (revision 440)
Built on: 2010/09/17 17:55

Buggy code:
private boolean isFoldableExpressBlock(Node n) {
  if (n.getType() == Token.BLOCK) {
    if (n.hasOneChild()) {
      Node maybeExpr = n.getFirstChild();
        // IE has a bug where event handlers behave differently when
        // their return value is used vs. when their return value is in
        // an EXPR_RESULT. It's pretty freaking weird. See:
        // http://code.google.com/p/closure-compiler/issues/detail?id=291
        // We try to detect this case, and not fold EXPR_RESULTs
        // into other expressions.

          // We only have to worry about methods with an implicit 'this'
          // param, or this doesn't happen.

        return NodeUtil.isExpressionNode(maybeExpr);
    }
  }

  return false;
}

Fixed code:
private boolean isFoldableExpressBlock(Node n) {
  if (n.getType() == Token.BLOCK) {
    if (n.hasOneChild()) {
      Node maybeExpr = n.getFirstChild();
      if (maybeExpr.getType() == Token.EXPR_RESULT) {
        // IE has a bug where event handlers behave differently when
        // their return value is used vs. when their return value is in
        // an EXPR_RESULT. It's pretty freaking weird. See:
        // http://code.google.com/p/closure-compiler/issues/detail?id=291
        // We try to detect this case, and not fold EXPR_RESULTs
        // into other expressions.
        if (maybeExpr.getFirstChild().getType() == Token.CALL) {
          Node calledFn = maybeExpr.getFirstChild().getFirstChild();

          // We only have to worry about methods with an implicit 'this'
          // param, or this doesn't happen.
          if (calledFn.getType() == Token.GETELEM) {
            return false;
          } else if (calledFn.getType() == Token.GETPROP &&
                     calledFn.getLastChild().getString().startsWith("on")) {
            return false;
          }
        }

        return true;
      }
      return false;
    }
  }

  return false;
}
File: src/com/google/javascript/jscomp/DeadAssignmentsElimination.java
Issue: Incorrect assignment removal from expression in simple mode.
function closureCompilerTest(someNode) {
   var nodeId;
   return ((nodeId=someNode.id) && (nodeId=parseInt(nodeId.substr(1))) && nodeId>0);
}

COMPILES TO:

function closureCompilerTest(b){var a;return b.id&&(a=parseInt(a.substr(1)))&&a>0};

"nodeId=someNode.id" is replaced with simply "b.id" which is incorrect as the value of "nodeId" is used.

Buggy code:
private VariableLiveness isVariableReadBeforeKill(
    Node n, String variable) {
  if (NodeUtil.isName(n) && variable.equals(n.getString())) {
    if (NodeUtil.isLhs(n, n.getParent())) {
      // The expression to which the assignment is made is evaluated before
      // the RHS is evaluated (normal left to right evaluation) but the KILL
      // occurs after the RHS is evaluated.
      return VariableLiveness.KILL;
    } else {
      return VariableLiveness.READ;
    }
  }

  // Expressions are evaluated left-right, depth first.
  for (Node child = n.getFirstChild();
      child != null; child = child.getNext()) {
    if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION
      VariableLiveness state = isVariableReadBeforeKill(child, variable);
      if (state != VariableLiveness.MAYBE_LIVE) {
        return state;
      }
    }
  }
  return VariableLiveness.MAYBE_LIVE;
}

Fixed code:
private VariableLiveness isVariableReadBeforeKill(
    Node n, String variable) {
  if (NodeUtil.isName(n) && variable.equals(n.getString())) {
    if (NodeUtil.isLhs(n, n.getParent())) {
      Preconditions.checkState(n.getParent().getType() == Token.ASSIGN);
      // The expression to which the assignment is made is evaluated before
      // the RHS is evaluated (normal left to right evaluation) but the KILL
      // occurs after the RHS is evaluated.
      Node rhs = n.getNext();
      VariableLiveness state = isVariableReadBeforeKill(rhs, variable);
      if (state == VariableLiveness.READ) {
        return state;
      }
      return VariableLiveness.KILL;
    } else {
      return VariableLiveness.READ;
    }
  }

  // Expressions are evaluated left-right, depth first.
  for (Node child = n.getFirstChild();
      child != null; child = child.getNext()) {
    if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION
      VariableLiveness state = isVariableReadBeforeKill(child, variable);
      if (state != VariableLiveness.MAYBE_LIVE) {
        return state;
      }
    }
  }
  return VariableLiveness.MAYBE_LIVE;
}
File: src/com/google/javascript/jscomp/NodeUtil.java
Issue: closure-compiler @define annotation does not allow line to be split on 80 characters.
What steps will reproduce the problem?
1.  Create a JavaScript file with the followiing:
/** @define {string} */
var CONSTANT = "some very long string name that I want to wrap " +
               "and so break using a + since I don't want to " +
               "introduce a newline into the string."
2.  Run closure-compiler on the .js file.
3.  See it generate an error on the '+'.

What is the expected output? What do you see instead?
It should work, since the line is assigning a constant value to the var.

Please provide any additional information below.
Removing the '+' and making the string all one line does work correctly.

Buggy code:
static boolean isValidDefineValue(Node val, Set<String> defines) {
  switch (val.getType()) {
    case Token.STRING:
    case Token.NUMBER:
    case Token.TRUE:
    case Token.FALSE:
      return true;

    // Binary operators are only valid if both children are valid.
    case Token.BITAND:
    case Token.BITNOT:
    case Token.BITOR:
    case Token.BITXOR:

    // Uniary operators are valid if the child is valid.
    case Token.NOT:
    case Token.NEG:
      return isValidDefineValue(val.getFirstChild(), defines);

    // Names are valid if and only if they are defines themselves.
    case Token.NAME:
    case Token.GETPROP:
      if (val.isQualifiedName()) {
        return defines.contains(val.getQualifiedName());
      }
  }
  return false;
}

Fixed code:
static boolean isValidDefineValue(Node val, Set<String> defines) {
  switch (val.getType()) {
    case Token.STRING:
    case Token.NUMBER:
    case Token.TRUE:
    case Token.FALSE:
      return true;

    // Binary operators are only valid if both children are valid.
    case Token.ADD:
    case Token.BITAND:
    case Token.BITNOT:
    case Token.BITOR:
    case Token.BITXOR:
    case Token.DIV:
    case Token.EQ:
    case Token.GE:
    case Token.GT:
    case Token.LE:
    case Token.LSH:
    case Token.LT:
    case Token.MOD:
    case Token.MUL:
    case Token.NE:
    case Token.RSH:
    case Token.SHEQ:
    case Token.SHNE:
    case Token.SUB:
    case Token.URSH:
      return isValidDefineValue(val.getFirstChild(), defines)
          && isValidDefineValue(val.getLastChild(), defines);

    // Uniary operators are valid if the child is valid.
    case Token.NOT:
    case Token.NEG:
    case Token.POS:
      return isValidDefineValue(val.getFirstChild(), defines);

    // Names are valid if and only if they are defines themselves.
    case Token.NAME:
    case Token.GETPROP:
      if (val.isQualifiedName()) {
        return defines.contains(val.getQualifiedName());
      }
  }
  return false;
}
File: src/main/java/org/apache/commons/codec/language/Soundex.java
Issue: Bug in HW rule in Soundex
The Soundex algorithm says that if two characters that map to the same code are separated by H or W, the second one is not encoded.
However, in the implementation (in Soundex.getMappingCode() line 191), a character that is preceded by two characters that are either H or W, is not encoded, regardless of what the last consonant was.
Source: http://en.wikipedia.org/wiki/Soundex#American_Soundex

Buggy code:
private char getMappingCode(final String str, final int index) {
    // map() throws IllegalArgumentException
    final char mappedChar = this.map(str.charAt(index));
    // HW rule check
    if (index > 1 && mappedChar != '0') {
        final char hwChar = str.charAt(index - 1);
        if ('H' == hwChar || 'W' == hwChar) {
            final char preHWChar = str.charAt(index - 2);
            final char firstCode = this.map(preHWChar);
            if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) {
                return 0;
            }
        }
    }
    return mappedChar;
}

Fixed code:
private char getMappingCode(final String str, final int index) {
    // map() throws IllegalArgumentException
    final char mappedChar = this.map(str.charAt(index));
    // HW rule check
    if (index > 1 && mappedChar != '0') {
        for (int i=index-1 ; i>=0 ; i--) {
            final char prevChar = str.charAt(i);
            if (this.map(prevChar)==mappedChar) {
                return 0;
            }
            if ('H'!=prevChar && 'W'!=prevChar) {
                break;
            }
        }
    }
    return mappedChar;
}