barty/D4J-Repair huggingface dataset:
File: src/main/java/org/apache/commons/cli/TypeHandler.java
Issue: TypeHandler should throw ParseException for an unsupported class
JavaDoc for TypeHandler states that createValue will

* @throws ParseException if the value creation for the given object type failedtype

 However createValue(String str, Class<?> clazz) will return null if the clazz is unknown.

Buggy code:
public static <T> T createValue(final String str, final Class<T> clazz) throws ParseException
{
    if (PatternOptionBuilder.STRING_VALUE == clazz)
    {
        return (T) str;
    }
    else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
    {
        return (T) createObject(str);
    }
    else if (PatternOptionBuilder.NUMBER_VALUE == clazz)
    {
        return (T) createNumber(str);
    }
    else if (PatternOptionBuilder.DATE_VALUE == clazz)
    {
        return (T) createDate(str);
    }
    else if (PatternOptionBuilder.CLASS_VALUE == clazz)
    {
        return (T) createClass(str);
    }
    else if (PatternOptionBuilder.FILE_VALUE == clazz)
    {
        return (T) createFile(str);
    }
    else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)
    {
        return (T) openFile(str);
    }
    else if (PatternOptionBuilder.FILES_VALUE == clazz)
    {
        return (T) createFiles(str);
    }
    else if (PatternOptionBuilder.URL_VALUE == clazz)
    {
        return (T) createURL(str);
    }
    else
    {
        return null;
    }
}

Fixed code:
public static <T> T createValue(final String str, final Class<T> clazz) throws ParseException
{
    if (PatternOptionBuilder.STRING_VALUE == clazz)
    {
        return (T) str;
    }
    else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
    {
        return (T) createObject(str);
    }
    else if (PatternOptionBuilder.NUMBER_VALUE == clazz)
    {
        return (T) createNumber(str);
    }
    else if (PatternOptionBuilder.DATE_VALUE == clazz)
    {
        return (T) createDate(str);
    }
    else if (PatternOptionBuilder.CLASS_VALUE == clazz)
    {
        return (T) createClass(str);
    }
    else if (PatternOptionBuilder.FILE_VALUE == clazz)
    {
        return (T) createFile(str);
    }
    else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)
    {
        return (T) openFile(str);
    }
    else if (PatternOptionBuilder.FILES_VALUE == clazz)
    {
        return (T) createFiles(str);
    }
    else if (PatternOptionBuilder.URL_VALUE == clazz)
    {
        return (T) createURL(str);
    }
    else
    {
        throw new ParseException("Unable to handle the class: " + clazz);
    }
}
File: src/java/org/apache/commons/cli/Util.java
Issue: NullPointerException in Util.stripLeadingHyphens when passed a null argument
If you try to do a hasOption(null), you get a NPE:
java.lang.NullPointerException
	at org.apache.commons.cli.Util.stripLeadingHyphens(Util.java:39)
	at org.apache.commons.cli.CommandLine.resolveOption(CommandLine.java:166)
	at org.apache.commons.cli.CommandLine.hasOption(CommandLine.java:68)
Either hasOption should reject the null argument, or the function should simply return false.  I think the latter makes more since, as this is how Java collections generally work.

Buggy code:
static String stripLeadingHyphens(String str)
{
    if (str.startsWith("--"))
    {
        return str.substring(2, str.length());
    }
    else if (str.startsWith("-"))
    {
        return str.substring(1, str.length());
    }

    return str;
}

Fixed code:
static String stripLeadingHyphens(String str)
{
    if (str == null) {
        return null;
    }
    if (str.startsWith("--"))
    {
        return str.substring(2, str.length());
    }
    else if (str.startsWith("-"))
    {
        return str.substring(1, str.length());
    }

    return str;
}
File: src/java/org/apache/commons/cli/Parser.java
Issue: MissingOptionException.getMessage() changed from CLI 1.0 > 1.1
The MissingOptionException.getMessage() string changed from CLI 1.0 > 1.1. 
CLI 1.0 was poorly formatted but readable:
Missing required options: -format-source-properties
CLI 1.1 is almost unreadable:
Missing required options: formatsourceproperties
In CLI 1.0 Options.addOption(Option) prefixed the stored options with a "-" and in CLI 1.1 it doesn't.
I would suggest changing Parser.checkRequiredOptions() to add the options to the error message with a prefix of " -":
OLD: 
            // loop through the required options
            while (iter.hasNext())
            {
                buff.append(iter.next());
            }

NEW: 
            // loop through the required options
            while (iter.hasNext())
            {
                buff.append(" -" + iter.next());
            }

Resulting in:
Missing required options: -format -source -properties

Buggy code:
protected void checkRequiredOptions()
    throws MissingOptionException
{
    // if there are required options that have not been
    // processsed
    if (getRequiredOptions().size() > 0)
    {
        Iterator iter = getRequiredOptions().iterator();
        StringBuffer buff = new StringBuffer("Missing required option");
        buff.append(getRequiredOptions().size() == 1 ? "" : "s");
        buff.append(": ");


        // loop through the required options
        while (iter.hasNext())
        {
            buff.append(iter.next());
        }

        throw new MissingOptionException(buff.toString());
    }
}

Fixed code:
protected void checkRequiredOptions()
    throws MissingOptionException
{
    // if there are required options that have not been
    // processsed
    if (getRequiredOptions().size() > 0)
    {
        Iterator iter = getRequiredOptions().iterator();
        StringBuffer buff = new StringBuffer("Missing required option");
        buff.append(getRequiredOptions().size() == 1 ? "" : "s");
        buff.append(": ");


        // loop through the required options
        while (iter.hasNext())
        {
            buff.append(iter.next());
            buff.append(", ");
        }

        throw new MissingOptionException(buff.substring(0, buff.length() - 2));
    }
}
File: src/com/google/javascript/jscomp/NodeUtil.java
Issue: Wrong code generated if mixing types in ternary operator
What steps will reproduce the problem?
1. Use Google Closure Compiler to compile this code:

    var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;

You can either simple or advanced. It doesn't matter

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

I'm seeing this as a result:
    var a = (0.5 < Math.random() ? 1 : 2) + 7;

This is obviously wrong as the '1' string literal got converted to a number, and 3+4 got combined into 7 while that's not ok as '1' + 3 + 4 = '134', not '17'.

What version of the product are you using? On what operating system?
Please provide any additional information below.

Seems like this issue happens only when you are mixing types together. If both 1 and 2 are string literals or if they are both numbers it won't happen. I was also a little surprised to see this happening in simple mode as it actually breaks the behavior.

Buggy code:
static boolean mayBeString(Node n, boolean recurse) {
  if (recurse) {
    return allResultsMatch(n, MAY_BE_STRING_PREDICATE);
  } else {
    return mayBeStringHelper(n);
  }
}

Fixed code:
static boolean mayBeString(Node n, boolean recurse) {
  if (recurse) {
    return anyResultsMatch(n, MAY_BE_STRING_PREDICATE);
  } else {
    return mayBeStringHelper(n);
  }
}
File: src/com/google/javascript/jscomp/CommandLineRunner.java
Issue: --process_closure_primitives can't be set to false
What steps will reproduce the problem?
1. compile a file with "--process_closure_primitives false"
2. compile a file with "--process_closure_primitives true" (default)
3. result: primitives are processed in both cases.

What is the expected output? What do you see instead?
The file should still have its goog.provide/require tags in place.
Instead they are processed.

What version of the product are you using? On what operating system?
current SVN (also tried two of the preceding binary releases with same 
result)

Please provide any additional information below.
Flag can't be set to false due to a missing "else" in the command-line 
parser.

Buggy code:
protected CompilerOptions createOptions() {
  CompilerOptions options = new CompilerOptions();
  options.setCodingConvention(new ClosureCodingConvention());
  CompilationLevel level = flags.compilation_level;
  level.setOptionsForCompilationLevel(options);
  if (flags.debug) {
    level.setDebugOptionsForCompilationLevel(options);
  }

  WarningLevel wLevel = flags.warning_level;
  wLevel.setOptionsForWarningLevel(options);
  for (FormattingOption formattingOption : flags.formatting) {
    formattingOption.applyToOptions(options);
  }
  if (flags.process_closure_primitives) {
    options.closurePass = true;
  }

  initOptionsFromFlags(options);
  return options;
}

Fixed code:
protected CompilerOptions createOptions() {
  CompilerOptions options = new CompilerOptions();
  options.setCodingConvention(new ClosureCodingConvention());
  CompilationLevel level = flags.compilation_level;
  level.setOptionsForCompilationLevel(options);
  if (flags.debug) {
    level.setDebugOptionsForCompilationLevel(options);
  }

  WarningLevel wLevel = flags.warning_level;
  wLevel.setOptionsForWarningLevel(options);
  for (FormattingOption formattingOption : flags.formatting) {
    formattingOption.applyToOptions(options);
  }

  options.closurePass = flags.process_closure_primitives;
  initOptionsFromFlags(options);
  return options;
}
File: src/com/google/javascript/jscomp/Normalize.java
Issue: compiler assumes that 'arguments' can be shadowed
The code:
function name() {
   var arguments = Array.prototype.slice.call(arguments, 0);
}

gets compiled to:
function name(){ var c=Array.prototype.slice.call(c,0); }

Thanks to tescosquirrel for the report.

Buggy code:
public void process(Node externs, Node root) {
  NodeTraversal.traverse(compiler, root, this);
  if (MAKE_LOCAL_NAMES_UNIQUE) {
    MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
    NodeTraversal t = new NodeTraversal(compiler, renamer);
    t.traverseRoots(externs, root);
  }
  removeDuplicateDeclarations(root);
  new PropogateConstantAnnotations(compiler, assertOnChange)
      .process(externs, root);
}

Fixed code:
public void process(Node externs, Node root) {
  NodeTraversal.traverse(compiler, root, this);
  removeDuplicateDeclarations(root);
  if (MAKE_LOCAL_NAMES_UNIQUE) {
    MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
    NodeTraversal t = new NodeTraversal(compiler, renamer);
    t.traverseRoots(externs, root);
  }
  new PropogateConstantAnnotations(compiler, assertOnChange)
      .process(externs, root);
}
File: src/com/google/javascript/rhino/jstype/UnionType.java
Issue: Typos in externs/html5.js
Line 354:
CanvasRenderingContext2D.prototype.globalCompositingOperation;

Line 366:
CanvasRenderingContext2D.prototype.mitreLimit;

They should be globalCompositeOperation and miterLimit, respectively.

Buggy code:
JSType meet(JSType that) {
  UnionTypeBuilder builder = new UnionTypeBuilder(registry);
  for (JSType alternate : alternates) {
    if (alternate.isSubtype(that)) {
      builder.addAlternate(alternate);
    }
  }

  if (that instanceof UnionType) {
    for (JSType otherAlternate : ((UnionType) that).alternates) {
      if (otherAlternate.isSubtype(this)) {
        builder.addAlternate(otherAlternate);
      }
    }
  } else if (that.isSubtype(this)) {
    builder.addAlternate(that);
  }
  JSType result = builder.build();
  if (result != null) {
    return result;
  } else if (this.isObject() && that.isObject()) {
    return getNativeType(JSTypeNative.NO_OBJECT_TYPE);
  } else {
    return getNativeType(JSTypeNative.NO_TYPE);
  }
}

Fixed code:
JSType meet(JSType that) {
  UnionTypeBuilder builder = new UnionTypeBuilder(registry);
  for (JSType alternate : alternates) {
    if (alternate.isSubtype(that)) {
      builder.addAlternate(alternate);
    }
  }

  if (that instanceof UnionType) {
    for (JSType otherAlternate : ((UnionType) that).alternates) {
      if (otherAlternate.isSubtype(this)) {
        builder.addAlternate(otherAlternate);
      }
    }
  } else if (that.isSubtype(this)) {
    builder.addAlternate(that);
  }
  JSType result = builder.build();
  if (!result.isNoType()) {
    return result;
  } else if (this.isObject() && that.isObject()) {
    return getNativeType(JSTypeNative.NO_OBJECT_TYPE);
  } else {
    return getNativeType(JSTypeNative.NO_TYPE);
  }
}
File: src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java
Issue: Constructor types that return all or unknown fail to parse
Constructor types that return the all type or the unknown type currently fail to parse:

/** @type {function(new:?)} */ var foo = function() {};
/** @type {function(new:*)} */ var bar = function() {};

foo.js:1: ERROR - Bad type annotation. type not recognized due to syntax error
/** @type {function(new:?)} */ var foo = function() {};
                        ^

foo.js:2: ERROR - Bad type annotation. type not recognized due to syntax error
/** @type {function(new:*)} */ var bar = function() {};
                        ^

This is an issue for a code generator that I'm working on.

Buggy code:
private Node parseContextTypeExpression(JsDocToken token) {
        return parseTypeName(token);
}

Fixed code:
private Node parseContextTypeExpression(JsDocToken token) {
  if (token == JsDocToken.QMARK) {
    return newNode(Token.QMARK);
  } else {
    return parseBasicTypeExpression(token);
  }
}
File: src/com/google/javascript/jscomp/TypeCheck.java
Issue: Record type invalid property not reported on function with @this annotation
Code:

var makeClass = function(protoMethods) {
  var clazz = function() {
    this.initialize.apply(this, arguments);
  }
  for (var i in protoMethods) {
    clazz.prototype[i] = protoMethods[i];
  }

  return clazz;
}

/**
 * @constructor
 * @param {{name: string, height: number}} options
 */
var Person = function(options){};
Person = makeClass(/** @lends Person.prototype */ {
  /**
   * @this {Person}
   * @param {{name: string, height: number}} options
   */
  initialize: function(options) {
    /** @type {string} */ this.name_ = options.thisPropDoesNotExist;
  },

  /**
   * @param {string} message
   * @this {Person}
   */
  say: function(message) {
    window.console.log(this.name_ + ' says: ' + message);
  }
});

var joe = new Person({name: 'joe', height: 300});
joe.say('hi');

compiled with:
java -jar build/compiler.jar --formatting=PRETTY_PRINT --jscomp_error=checkTypes --jscomp_error=externsValidation --compilation_level=SIMPLE_OPTIMIZATIONS repro.js

I would expect an error on this line:
    /** @type {string} */ this.name_ = options.thisPropDoesNotExist;

which works in other contexts.

Thanks!

Buggy code:
private void visitGetProp(NodeTraversal t, Node n, Node parent) {
  // obj.prop or obj.method()
  // Lots of types can appear on the left, a call to a void function can
  // never be on the left. getPropertyType will decide what is acceptable
  // and what isn't.
  Node property = n.getLastChild();
  Node objNode = n.getFirstChild();
  JSType childType = getJSType(objNode);

  if (childType.isDict()) {
    report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, "'.'", "dict");
  } else if (n.getJSType() != null && parent.isAssign()) {
    return;
  } else if (validator.expectNotNullOrUndefined(t, n, childType,
      "No properties on this expression", getNativeType(OBJECT_TYPE))) {
    checkPropertyAccess(childType, property.getString(), t, n);
  }
  ensureTyped(t, n);
}

Fixed code:
private void visitGetProp(NodeTraversal t, Node n, Node parent) {
  // obj.prop or obj.method()
  // Lots of types can appear on the left, a call to a void function can
  // never be on the left. getPropertyType will decide what is acceptable
  // and what isn't.
  Node property = n.getLastChild();
  Node objNode = n.getFirstChild();
  JSType childType = getJSType(objNode);

  if (childType.isDict()) {
    report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, "'.'", "dict");
  } else if (validator.expectNotNullOrUndefined(t, n, childType,
      "No properties on this expression", getNativeType(OBJECT_TYPE))) {
    checkPropertyAccess(childType, property.getString(), t, n);
  }
  ensureTyped(t, n);
}
File: src/com/google/javascript/jscomp/type/ClosureReverseAbstractInterpreter.java
Issue: goog.isArray doesn't hint compiler
What steps will reproduce the problem?
1.

/**
 * @param {*} object
 * @return {*}
 */
var test = function(object) {
  if (goog.isArray(object)) {
    /** @type {Array} */ var x = object;
    return x;
  }
};

2. ADVANCED_OPTIMIZATIONS

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

ERROR - initializing variable
found   : *
required: (Array|null)
    /** @type {Array} */ var x = object;
                                 ^
What version of the product are you using? On what operating system?

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

Please provide any additional information below.

goog.is* is supposed to help the compiler to check which type we're dealing with.

Buggy code:
protected JSType caseTopType(JSType topType) {
  return topType;
}

Fixed code:
protected JSType caseTopType(JSType topType) {
  return topType.isAllType() ?
      getNativeType(ARRAY_TYPE) : topType;
}
File: src/com/google/javascript/jscomp/TypeInference.java
Issue: Template types on methods incorrectly trigger inference of a template on the class if that template type is unknown
See i.e.

/**
  * @constructor
  * @template CLASS
  */
var Class = function() {};

/**
  * @param {function(CLASS):CLASS} a
  * @template T
  */
Class.prototype.foo = function(a) {
  return 'string';
};

/** @param {number} a
  * @return {string} */
var a = function(a) { return '' };

new Class().foo(a);

The CLASS type is never specified. If the @template T line is removed from the foo method, the block compiles with but with the @annotation on the method, the compiler seems to try to infer CLASS from the usage and fails compilation.

Buggy code:
private boolean inferTemplatedTypesForCall(
    Node n, FunctionType fnType) {
  final ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap()
      .getTemplateKeys();
  if (keys.isEmpty()) {
    return false;
  }

  // Try to infer the template types
  Map<TemplateType, JSType> inferred = 
      inferTemplateTypesFromParameters(fnType, n);


  // Replace all template types. If we couldn't find a replacement, we
  // replace it with UNKNOWN.
  TemplateTypeReplacer replacer = new TemplateTypeReplacer(
      registry, inferred);
  Node callTarget = n.getFirstChild();

  FunctionType replacementFnType = fnType.visit(replacer)
      .toMaybeFunctionType();
  Preconditions.checkNotNull(replacementFnType);

  callTarget.setJSType(replacementFnType);
  n.setJSType(replacementFnType.getReturnType());

  return replacer.madeChanges;
}

Fixed code:
private boolean inferTemplatedTypesForCall(
    Node n, FunctionType fnType) {
  final ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap()
      .getTemplateKeys();
  if (keys.isEmpty()) {
    return false;
  }

  // Try to infer the template types
  Map<TemplateType, JSType> inferred = Maps.filterKeys(
      inferTemplateTypesFromParameters(fnType, n),
      new Predicate<TemplateType>() {

        @Override
        public boolean apply(TemplateType key) {
          return keys.contains(key);
        }}
      );

  // Replace all template types. If we couldn't find a replacement, we
  // replace it with UNKNOWN.
  TemplateTypeReplacer replacer = new TemplateTypeReplacer(
      registry, inferred);
  Node callTarget = n.getFirstChild();

  FunctionType replacementFnType = fnType.visit(replacer)
      .toMaybeFunctionType();
  Preconditions.checkNotNull(replacementFnType);

  callTarget.setJSType(replacementFnType);
  n.setJSType(replacementFnType.getReturnType());

  return replacer.madeChanges;
}
File: src/com/google/javascript/jscomp/DisambiguateProperties.java
Issue: Prototype method incorrectly removed
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// ==/ClosureCompiler==

/** @const */
var foo = {};
foo.bar = {
  'bar1': function() { console.log('bar1'); }
}

/** @constructor */
function foobar() {}
foobar.prototype = foo.bar;

foo.foobar = new foobar;

console.log(foo.foobar['bar1']);

Buggy code:
private void handleObjectLit(NodeTraversal t, Node n) {
  for (Node child = n.getFirstChild();
      child != null;
      child = child.getNext()) {
    // Maybe STRING, GET, SET

    // We should never see a mix of numbers and strings.
    String name = child.getString();
    T type = typeSystem.getType(getScope(), n, name);

    Property prop = getProperty(name);
    if (!prop.scheduleRenaming(child,
                               processProperty(t, prop, type, null))) {
      // TODO(user): It doesn't look like the user can do much in this
      // case right now.
      if (propertiesToErrorFor.containsKey(name)) {
        compiler.report(JSError.make(
            t.getSourceName(), child, propertiesToErrorFor.get(name),
            Warnings.INVALIDATION, name,
            (type == null ? "null" : type.toString()), n.toString(), ""));
      }
    }
  }
}

Fixed code:
private void handleObjectLit(NodeTraversal t, Node n) {
  for (Node child = n.getFirstChild();
      child != null;
      child = child.getNext()) {
    // Maybe STRING, GET, SET
    if (child.isQuotedString()) {
      continue;
    }

    // We should never see a mix of numbers and strings.
    String name = child.getString();
    T type = typeSystem.getType(getScope(), n, name);

    Property prop = getProperty(name);
    if (!prop.scheduleRenaming(child,
                               processProperty(t, prop, type, null))) {
      // TODO(user): It doesn't look like the user can do much in this
      // case right now.
      if (propertiesToErrorFor.containsKey(name)) {
        compiler.report(JSError.make(
            t.getSourceName(), child, propertiesToErrorFor.get(name),
            Warnings.INVALIDATION, name,
            (type == null ? "null" : type.toString()), n.toString(), ""));
      }
    }
  }
}
File: src/com/google/javascript/jscomp/MaybeReachingVariableUse.java
Issue: Try/catch blocks incorporate code not inside original blocks
What steps will reproduce the problem?

Starting with this code:

-----
function a() {
 var x = '1';
 try {
  x += somefunction();
 } catch(e) {
 }
 x += "2";
 try {
  x += somefunction();
 } catch(e) {
 }
 document.write(x);
}

a();
a();
-----

It gets compiled to:

-----
function b() {
  var a;
  try {
    a = "1" + somefunction()
  }catch(c) {
  }
  try {
    a = a + "2" + somefunction()
  }catch(d) {
  }
  document.write(a)
}
b();
b();
-----

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

The problem is that it's including the constant "1" and "2" inside the try block when the shouldn't be. When executed uncompiled, the script prints "1212". When compiled, the script prints "undefinedundefined".

This behavior doesn't happen if the entire function gets inlined, or if the code between the two try blocks is sufficiently complex.

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

Closure Compiler (http://code.google.com/closure/compiler)
Version: 20120430 (revision 1918)
Built on: 2012/04/30 18:02
java version "1.6.0_33"
Java(TM) SE Runtime Environment (build 1.6.0_33-b03-424-11M3720)
Java HotSpot(TM) 64-Bit Server VM (build 20.8-b03-424, mixed mode)

Buggy code:
private boolean hasExceptionHandler(Node cfgNode) {
  return false;
}

Fixed code:
private boolean hasExceptionHandler(Node cfgNode) {
  List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(cfgNode);
  for (DiGraphEdge<Node, Branch> edge : branchEdges) {
    if (edge.getValue() == Branch.ON_EX) {
      return true;
    }
  }
  return false;
}