barty/D4J-Repair huggingface dataset:
File: src/com/google/javascript/jscomp/ReferenceCollectingCallback.java
Issue: Overzealous optimization confuses variables
The following code:

	// ==ClosureCompiler==
	// @compilation_level ADVANCED_OPTIMIZATIONS
	// ==/ClosureCompiler==
	var uid;
	function reset() {
		uid = Math.random();
	}
	function doStuff() {
		reset();
		var _uid = uid;

		if (uid < 0.5) {
			doStuff();
		}

		if (_uid !== uid) {
			throw 'reset() was called';
		}
	}
	doStuff();

...gets optimized to:

	var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b();

Notice how _uid gets optimized away and (uid!==_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from _uid.

As an aside, replacing the declaration with "var _uid = +uid;" fixes it, as does adding an extra "uid = _uid" after "var _uid = uid".

Buggy code:
boolean isAssignedOnceInLifetime() {
  Reference ref = getOneAndOnlyAssignment();
  if (ref == null) {
    return false;
  }

  // Make sure this assignment is not in a loop.
  for (BasicBlock block = ref.getBasicBlock();
       block != null; block = block.getParent()) {
    if (block.isFunction) {
      break;
    } else if (block.isLoop) {
      return false;
    }
  }

  return true;
}

Fixed code:
boolean isAssignedOnceInLifetime() {
  Reference ref = getOneAndOnlyAssignment();
  if (ref == null) {
    return false;
  }

  // Make sure this assignment is not in a loop.
  for (BasicBlock block = ref.getBasicBlock();
       block != null; block = block.getParent()) {
    if (block.isFunction) {
      if (ref.getSymbol().getScope() != ref.scope) {
        return false;
      }
      break;
    } else if (block.isLoop) {
      return false;
    }
  }

  return true;
}
File: src/com/google/javascript/jscomp/parsing/IRFactory.java
Issue: Inconsistent handling of non-JSDoc comments
What steps will reproduce the problem?
1.
2.
3.
What is the expected output? What do you see instead?

When given:

    /* @preserve Foo License */
    alert("foo");

It spits out:

    stdin:1: WARNING - Parse error. Non-JSDoc comment has annotations. Did you mean to start it with '/**'?
    /* @license Foo License */
    ^

    0 error(s), 1 warning(s)
    alert("foo");

If I take the suggestion and change the opening of the comment to '/**', everything is great.  However, if I change it to '/*!', the warning goes away, but it doesn't preserve the comment either.

I expect it to print the above warning, or preserve the comment.  That it does neither when starting with "/*!" (and every other character I tried) is confusing.

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

Tested with my compilation of the "v20130603" tag:

    Closure Compiler (http://code.google.com/closure/compiler)
    Version: v20130603
    Built on: 2013/07/07 15:04

And with the provided binary:

    Closure Compiler (http://code.google.com/closure/compiler)
    Version: v20130411-90-g4e19b4e
    Built on: 2013/06/03 12:07

I'm on Parabola GNU/Linux-libre with Java:

    java version "1.7.0_40"
    OpenJDK Runtime Environment (IcedTea 2.4.0) (ArchLinux build 7.u40_2.4.0-1-i686)
    OpenJDK Server VM (build 24.0-b40, mixed mode)

Please provide any additional information below.

Buggy code:
private void handleBlockComment(Comment comment) {
  if (comment.getValue().indexOf("/* @") != -1 || comment.getValue().indexOf("\n * @") != -1) {
    errorReporter.warning(
        SUSPICIOUS_COMMENT_WARNING,
        sourceName,
        comment.getLineno(), "", 0);
  }
}

Fixed code:
private void handleBlockComment(Comment comment) {
  Pattern p = Pattern.compile("(/|(\n[ \t]*))\\*[ \t]*@[a-zA-Z]");
  if (p.matcher(comment.getValue()).find()) {
    errorReporter.warning(
        SUSPICIOUS_COMMENT_WARNING,
        sourceName,
        comment.getLineno(), "", 0);
  }
}
File: src/com/google/javascript/jscomp/ExploitAssigns.java
Issue: Different output from RestAPI and command line jar
When I compile using the jar file from the command line I get a result that is not correct. However, when I test it via the REST API or the Web UI I get a correct output. I've attached a file with the code that we are compiling.

What steps will reproduce the problem?
1. Compile the attached file with "java -jar compiler.jar --js test.js"
2. Compile the content of the attached file on http://closure-compiler.appspot.com/home
3. Compare the output, note how the following part is converted in the two cases:

"var foreignObject = gfx.parentNode.parentNode;
var parentContainer = foreignObject.parentNode.parentNode;"

What is the expected output? What do you see instead?
The Web UI converts the lines into: if(b){if(a=b.parentNode.parentNode,b=a.parentNode.parentNode,null!==b)
The command line converts it into: var b=a=a.parentNode.parentNode;
The Web UI results in correct code, the other results in code that tries to do "c.appendChild(b)" with c = b (c=a=a.parentNode.parentNode)

What version of the product are you using? On what operating system?
compiler.jar: v20130411-90-g4e19b4e
Mac OSX 10.8.3
Java: java 1.6.0_45

Please provide any additional information below.
We are also using the compiler form within our java code, with the same result.
Web UI was called with:
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

Buggy code:
private boolean isSafeReplacement(Node node, Node replacement) {
  // No checks are needed for simple names.
  if (node.isName()) {
    return true;
  }
  Preconditions.checkArgument(node.isGetProp());

    node = node.getFirstChild();
  if (node.isName()
      && isNameAssignedTo(node.getString(), replacement)) {
    return false;
  }

  return true;
}

Fixed code:
private boolean isSafeReplacement(Node node, Node replacement) {
  // No checks are needed for simple names.
  if (node.isName()) {
    return true;
  }
  Preconditions.checkArgument(node.isGetProp());

  while (node.isGetProp()) {
    node = node.getFirstChild();
  }
  if (node.isName()
      && isNameAssignedTo(node.getString(), replacement)) {
    return false;
  }

  return true;
}
File: src/com/google/javascript/jscomp/CodeGenerator.java
Issue: The compiler quotes the "0" keys in object literals
What steps will reproduce the problem?
1. Compile alert({0:0, 1:1});

What is the expected output?
alert({0:0, 1:1});

What do you see instead?
alert({"0":0, 1:1});

What version of the product are you using? On what operating system?
Latest version on Goobuntu.

Buggy code:
static boolean isSimpleNumber(String s) {
  int len = s.length();
  for (int index = 0; index < len; index++) {
    char c = s.charAt(index);
    if (c < '0' || c > '9') {
      return false;
    }
  }
  return len > 0 && s.charAt(0) != '0';
}

Fixed code:
static boolean isSimpleNumber(String s) {
  int len = s.length();
  if (len == 0) {
    return false;
  }
  for (int index = 0; index < len; index++) {
    char c = s.charAt(index);
    if (c < '0' || c > '9') {
      return false;
    }
  }
  return len == 1 || s.charAt(0) != '0';
}
File: src/com/google/javascript/jscomp/PrepareAst.java
Issue: Casting a function before calling it produces bad code and breaks plugin code
1. Compile this code with ADVANCED_OPTIMIZATIONS:
console.log( /** @type {function(!string):!string} */ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable'])( '$version' ) );

produces:

'use strict';console.log((0,(new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable)("$version"));

2. Compare with this code:
console.log( /** @type {!string} */ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable']( '$version' )) )

produces:

'use strict';console.log((new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version"));

Notice the (0,...) wrapping around the GetVariable function in the first example. This causes the call to fail in every browser (this code is IE-only but it's just for a minimal example). The second version produces a warning that the type of GetVariable could not be determined (I enabled type warnings), and it wouldn't be possible to define these in an externs file without making a horrible mess.

This applies to all cases where functions are cast, but only causes problems (other than bloat) with plugins like this. It seems to serve no purpose whatsoever, so I assume it is a bug.

Running on a mac, not sure what version but it reports Built on: 2013/02/12 17:00, so will have been downloaded about that time.

Buggy code:
private void annotateCalls(Node n) {
  Preconditions.checkState(n.isCall());

  // Keep track of of the "this" context of a call.  A call without an
  // explicit "this" is a free call.
  Node first = n.getFirstChild();

  // ignore cast nodes.

  if (!NodeUtil.isGet(first)) {
    n.putBooleanProp(Node.FREE_CALL, true);
  }

  // Keep track of the context in which eval is called. It is important
  // to distinguish between "(0, eval)()" and "eval()".
  if (first.isName() &&
      "eval".equals(first.getString())) {
    first.putBooleanProp(Node.DIRECT_EVAL, true);
  }
}

Fixed code:
private void annotateCalls(Node n) {
  Preconditions.checkState(n.isCall());

  // Keep track of of the "this" context of a call.  A call without an
  // explicit "this" is a free call.
  Node first = n.getFirstChild();

  // ignore cast nodes.
  while (first.isCast()) {
    first = first.getFirstChild();
  }

  if (!NodeUtil.isGet(first)) {
    n.putBooleanProp(Node.FREE_CALL, true);
  }

  // Keep track of the context in which eval is called. It is important
  // to distinguish between "(0, eval)()" and "eval()".
  if (first.isName() &&
      "eval".equals(first.getString())) {
    first.putBooleanProp(Node.DIRECT_EVAL, true);
  }
}
File: src/com/google/javascript/jscomp/PeepholeOptimizationsPass.java
Issue: true/false are not always replaced for !0/!1
What steps will reproduce the problem?

function some_function() {
  var fn1;
  var fn2;

  if (any_expression) {
    fn2 = external_ref;
    fn1 = function (content) {
      return fn2();
    }
  }

  return {
    method1: function () {
      if (fn1) fn1();
      return true;
    },
    method2: function () {
      return false;
    }
  }
}

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

We expect that true/false will be replaced for !0/!1, but it doesn't happend.

function some_function() {
  var a, b;
  any_expression && (b = external_ref, a = function () {
    return b()
  });
  return {
    method1: function () {
      a && a();
      return true
    },
    method2: function () {
      return false
    }
  }
};

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

This is output for latest official build.
I also got the same output for 20120430, 20120305. But 20111117 is OK.

Please provide any additional information below.

Here is just one of example. I found too many non-replaced true/false in compiler output. Replacement non-replaced true/false to !1/!0 in conpiler output saves 1-2 kb for 850 kb js file.

Buggy code:
private void traverse(Node node) {
  // The goal here is to avoid retraversing
  // the entire AST to catch newly created opportunities.
  // So we track whether a "unit of code" has changed,
  // and revisit immediately.
  if (!shouldVisit(node)) {
    return;
  }

  int visits = 0;
  do {
    Node c = node.getFirstChild();
    while(c != null) {
      traverse(c);
      Node next = c.getNext();
      c = next;
    }

    visit(node);
    visits++;

    Preconditions.checkState(visits < 10000, "too many interations");
  } while (shouldRetraverse(node));

  exitNode(node);
}

Fixed code:
private void traverse(Node node) {
  // The goal here is to avoid retraversing
  // the entire AST to catch newly created opportunities.
  // So we track whether a "unit of code" has changed,
  // and revisit immediately.
  if (!shouldVisit(node)) {
    return;
  }

  int visits = 0;
  do {
    Node c = node.getFirstChild();
    while(c != null) {
      Node next = c.getNext();
      traverse(c);
      c = next;
    }

    visit(node);
    visits++;

    Preconditions.checkState(visits < 10000, "too many interations");
  } while (shouldRetraverse(node));

  exitNode(node);
}
File: src/com/google/javascript/rhino/TokenStream.java
Issue: unicode characters in property names result in invalid output
What steps will reproduce the problem?
1. use unicode characters in a property name for an object, like this:
var test={"a\u0004b":"c"};

2. compile

What is the expected output? What do you see instead?
Because unicode characters are not allowed in property names without quotes, the output should be the same as the input. However, the compiler converts the string \u0004 to the respective unicode character, and the output is: 
var test={ab:"c"}; // unicode character between a and b can not be displayed here

What version of the product are you using? On what operating system?
newest current snapshot on multiple os (OSX/linux)

Please provide any additional information below.

Buggy code:
public static boolean isJSIdentifier(String s) {
  int length = s.length();

  if (length == 0 ||
      !Character.isJavaIdentifierStart(s.charAt(0))) {
    return false;
  }

  for (int i = 1; i < length; i++) {
    if (
        !Character.isJavaIdentifierPart(s.charAt(i))) {
      return false;
    }
  }

  return true;
}

Fixed code:
public static boolean isJSIdentifier(String s) {
  int length = s.length();

  if (length == 0 ||
      Character.isIdentifierIgnorable(s.charAt(0)) ||
      !Character.isJavaIdentifierStart(s.charAt(0))) {
    return false;
  }

  for (int i = 1; i < length; i++) {
    if (Character.isIdentifierIgnorable(s.charAt(i)) ||
        !Character.isJavaIdentifierPart(s.charAt(i))) {
      return false;
    }
  }

  return true;
}
File: src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java
Issue: Exception when parsing erroneous jsdoc: /**@return {@code foo} bar   *    baz. */
The following causes an exception in JSDocInfoParser.

/** 
 * @return {@code foo} bar 
 *    baz. */
var x;

Fix to follow.

Buggy code:
private String getRemainingJSDocLine() {
  String result = stream.getRemainingJSDocLine();
  return result;
}

Fixed code:
private String getRemainingJSDocLine() {
  String result = stream.getRemainingJSDocLine();
  unreadToken = NO_UNREAD_TOKEN;
  return result;
}
File: src/com/google/javascript/jscomp/CodeGenerator.java
Issue: Bug with labeled loops and breaks
What steps will reproduce the problem?
Try to compile this code with the closure compiler : 
var i = 0; 
lab1: do{ 
    lab2: do{ 
        i++; 
        if (1) { 
            break lab2; 
        } else { 
            break lab1; 
        } 
    } while(false); 
} while(false); 

console.log(i); 

What is the expected output? What do you see instead?
The generated code produced is :
var a=0;do b:do{a++;break b}while(0);while(0);console.log(a); 

Which works on all browsers except IE (Looks like IE doesn't like 
the missing brackets just after the first do instruction).

What version of the product are you using? On what operating system?
I am using the version of Jun 16 (latest) on ubuntu 10

Please provide any additional information below.
Strangely, this bug doesn't happen when I use PRETTY_PRINT formatting option.

Buggy code:
private boolean isOneExactlyFunctionOrDo(Node n) {
      // For labels with block children, we need to ensure that a
      // labeled FUNCTION or DO isn't generated when extraneous BLOCKs 
      // are skipped. 
        // Either a empty statement or an block with more than one child,
        // way it isn't a FUNCTION or DO.
    return (n.getType() == Token.FUNCTION || n.getType() == Token.DO);
}

Fixed code:
private boolean isOneExactlyFunctionOrDo(Node n) {
  if (n.getType() == Token.LABEL) {
    Node labeledStatement = n.getLastChild();
    if (labeledStatement.getType() != Token.BLOCK) {
      return isOneExactlyFunctionOrDo(labeledStatement);
    } else {
      // For labels with block children, we need to ensure that a
      // labeled FUNCTION or DO isn't generated when extraneous BLOCKs 
      // are skipped. 
      if (getNonEmptyChildCount(n, 2) == 1) { 
        return isOneExactlyFunctionOrDo(getFirstNonEmptyChild(n));
      } else {
        // Either a empty statement or an block with more than one child,
        // way it isn't a FUNCTION or DO.
        return false;
      }
    }
  } else {
    return (n.getType() == Token.FUNCTION || n.getType() == Token.DO);
  }
}
File: src/com/google/javascript/rhino/jstype/JSType.java
Issue: bad type inference for != undefined
What steps will reproduce the problem?

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

/** @param {string} x */
function g(x) {}

/** @param {undefined} x */
function f(x) {
  if (x != undefined) { g(x); }
}

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

JSC_DETERMINISTIC_TEST: condition always evaluates to false
left : undefined
right: undefined at line 6 character 6
if (x != undefined) { g(x); }
      ^
JSC_TYPE_MISMATCH: actual parameter 1 of g does not match formal parameter
found   : undefined
required: string at line 6 character 24
if (x != undefined) { g(x); }
                        ^

the second warning is bogus.

Buggy code:
public TypePair getTypesUnderInequality(JSType that) {
  // unions types
  if (that instanceof UnionType) {
    TypePair p = that.getTypesUnderInequality(this);
    return new TypePair(p.typeB, p.typeA);
  }

  // other types
  switch (this.testForEquality(that)) {
    case TRUE:
      return new TypePair(null, null);

    case FALSE:
    case UNKNOWN:
      return new TypePair(this, that);
  }

  // switch case is exhaustive
  throw new IllegalStateException();
}

Fixed code:
public TypePair getTypesUnderInequality(JSType that) {
  // unions types
  if (that instanceof UnionType) {
    TypePair p = that.getTypesUnderInequality(this);
    return new TypePair(p.typeB, p.typeA);
  }

  // other types
  switch (this.testForEquality(that)) {
    case TRUE:
      JSType noType = getNativeType(JSTypeNative.NO_TYPE);
      return new TypePair(noType, noType);

    case FALSE:
    case UNKNOWN:
      return new TypePair(this, that);
  }

  // switch case is exhaustive
  throw new IllegalStateException();
}
File: src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java
Issue: Switched order of "delete key" and "key in" statements changes semantic
// Input:

var customData = { key: 'value' };

function testRemoveKey( key ) {
	var dataSlot = customData,
		retval = dataSlot && dataSlot[ key ],
		hadKey = dataSlot && ( key in dataSlot );

	if ( dataSlot )
		delete dataSlot[ key ];

	return hadKey ? retval : null;
};

console.log( testRemoveKey( 'key' ) ); // 'value'
console.log( 'key' in customData ); // false

// Compiled version:

var customData={key:"value"};function testRemoveKey(b){var a=customData,c=a&&a[b];a&&delete a[b];return a&&b in a?c:null}console.log(testRemoveKey("key"));console.log("key"in customData);

// null
// false

"b in a" is executed after "delete a[b]" what obviously doesn't make sense in this case.

Reproducible on: http://closure-compiler.appspot.com/home and in "Version: 20120430 (revision 1918) Built on: 2012/04/30 18:02"

Buggy code:
public boolean apply(Node n) {
  // When the node is null it means, we reached the implicit return
  // where the function returns (possibly without an return statement)
  if (n == null) {
    return false;
  }

  // TODO(user): We only care about calls to functions that
  // passes one of the dependent variable to a non-side-effect free
  // function.
  if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {
    return true;
  }

  if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {
    return true;
  }


  for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
    if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {
      return true;
    }
  }
  return false;
}

Fixed code:
public boolean apply(Node n) {
  // When the node is null it means, we reached the implicit return
  // where the function returns (possibly without an return statement)
  if (n == null) {
    return false;
  }

  // TODO(user): We only care about calls to functions that
  // passes one of the dependent variable to a non-side-effect free
  // function.
  if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {
    return true;
  }

  if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {
    return true;
  }

  if (n.isDelProp()) {
    return true;
  }

  for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
    if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {
      return true;
    }
  }
  return false;
}
File: src/com/google/javascript/jscomp/TypedScopeCreator.java
Issue: Type checker misses annotations on functions defined within functions
What steps will reproduce the problem?
1. Compile the following code under --warning_level VERBOSE

var ns = {};

/** @param {string=} b */
ns.a = function(b) {}

function d() {
    ns.a();
    ns.a(123);
}

2. Observe that the type checker correctly emits one warning, as 123 
doesn't match the type {string}

3. Now compile the code with ns.a defined within an anonymous function, 
like so:

var ns = {};

(function() {
    /** @param {string=} b */
    ns.a = function(b) {}
})();

function d() {
    ns.a();
    ns.a(123);
}

4. Observe that a warning is emitted for calling ns.a with 0 parameters, and 
not for the type error, as though the @param declaration were ignored. 

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

Please provide any additional information below.

This sort of module pattern is common enough that it strikes me as worth 
supporting.

One last note to make matters stranger: if the calling code isn't itself within 
a function, no warnings are emitted at all:

var ns = {};

(function() {
    /** @param {string=} b */
    ns.a = function(b) {}
})();

ns.a();
ns.a(123);

Buggy code:
@Override public void visit(NodeTraversal t, Node n, Node parent) {
  if (n == scope.getRootNode()) return;

  if (n.getType() == Token.LP && parent == scope.getRootNode()) {
    handleFunctionInputs(parent);
    return;
  }

  attachLiteralTypes(n);
  switch (n.getType()) {
    case Token.FUNCTION:
      if (parent.getType() == Token.NAME) {
        return;
      }
      defineDeclaredFunction(n, parent);
      break;
    case Token.CATCH:
      defineCatch(n, parent);
      break;
    case Token.VAR:
      defineVar(n, parent);
      break;
  }
}

Fixed code:
@Override public void visit(NodeTraversal t, Node n, Node parent) {
  if (n == scope.getRootNode()) return;

  if (n.getType() == Token.LP && parent == scope.getRootNode()) {
    handleFunctionInputs(parent);
    return;
  }

  super.visit(t, n, parent);
}