MORepair
Collection
A Collection of MORepair that includes the multi-objective fine-tuned CodeLlama-13B and all evaluation benchmarks. • 6 items • Updated • 1
task_id stringlengths 5 19 | buggy_code stringlengths 44 3.26k | fixed_code stringlengths 67 3.31k | file_path stringlengths 36 95 | issue_title stringlengths 0 150 | issue_description stringlengths 0 2.85k | start_line int64 9 4.43k | end_line int64 11 4.52k |
|---|---|---|---|---|---|---|---|
Chart-1 | public LegendItemCollection getLegendItems() {
LegendItemCollection result = new LegendItemCollection();
if (this.plot == null) {
return result;
}
int index = this.plot.getIndexOf(this);
CategoryDataset dataset = this.plot.getDataset(index);
if (dataset != null) {
return result;
... | public LegendItemCollection getLegendItems() {
LegendItemCollection result = new LegendItemCollection();
if (this.plot == null) {
return result;
}
int index = this.plot.getIndexOf(this);
CategoryDataset dataset = this.plot.getDataset(index);
if (dataset == null) {
return result;
... | source/org/jfree/chart/renderer/category/AbstractCategoryItemRenderer.java | #983 Potential NPE in AbstractCategoryItemRender.getLegendItems() | Setting up a working copy of the current JFreeChart trunk in Eclipse I got a warning about a null pointer access in this bit of code from AbstractCategoryItemRender.java:
public LegendItemCollection getLegendItems() {
LegendItemCollection result = new LegendItemCollection();
if (this.plot == null) {
return result;
}
in... | 1,790 | 1,822 |
Chart-10 | public String generateToolTipFragment(String toolTipText) {
return " title=\"" + toolTipText
+ "\" alt=\"\"";
} | public String generateToolTipFragment(String toolTipText) {
return " title=\"" + ImageMapUtilities.htmlEscape(toolTipText)
+ "\" alt=\"\"";
} | source/org/jfree/chart/imagemap/StandardToolTipTagFragmentGenerator.java | 64 | 67 | ||
Chart-11 | public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = p1.getPathIterator(null);
PathIterat... | public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = p1.getPathIterator(null);
PathIterat... | source/org/jfree/chart/util/ShapeUtilities.java | #868 JCommon 1.0.12 ShapeUtilities.equal(path1,path2) | The comparison of two GeneralPath objects uses the same PathIterator for both objects. equal(GeneralPath path1, GeneralPath path2) will thus return true for any pair of non-null GeneralPath instances having the same windingRule. | 264 | 296 |
Chart-12 | public MultiplePiePlot(CategoryDataset dataset) {
super();
this.dataset = dataset;
PiePlot piePlot = new PiePlot(null);
this.pieChart = new JFreeChart(piePlot);
this.pieChart.removeLegend();
this.dataExtractOrder = TableOrder.BY_COLUMN;
this.pieChart.setBackgroundPaint(null);
TextTitle s... | public MultiplePiePlot(CategoryDataset dataset) {
super();
setDataset(dataset);
PiePlot piePlot = new PiePlot(null);
this.pieChart = new JFreeChart(piePlot);
this.pieChart.removeLegend();
this.dataExtractOrder = TableOrder.BY_COLUMN;
this.pieChart.setBackgroundPaint(null);
TextTitle seri... | source/org/jfree/chart/plot/MultiplePiePlot.java | #213 Fix for MultiplePiePlot | When dataset is passed into constructor for MultiplePiePlot, the dataset is not wired to a listener, as it would be if setDataset is called. | 143 | 158 |
Chart-17 | public Object clone() throws CloneNotSupportedException {
Object clone = createCopy(0, getItemCount() - 1);
return clone;
} | public Object clone() throws CloneNotSupportedException {
TimeSeries clone = (TimeSeries) super.clone();
clone.data = (List) ObjectUtilities.deepClone(this.data);
return clone;
} | source/org/jfree/data/time/TimeSeries.java | #803 cloning of TimeSeries | It's just a minor bug!
When I clone a TimeSeries which has no items, I get an IllegalArgumentException ("Requires start <= end").
But I don't think the user should be responsible for checking whether the TimeSeries has any items or not. | 856 | 859 |
Chart-20 | public ValueMarker(double value, Paint paint, Stroke stroke,
Paint outlinePaint, Stroke outlineStroke, float alpha) {
super(paint, stroke, paint, stroke, alpha);
this.value = value;
} | public ValueMarker(double value, Paint paint, Stroke stroke,
Paint outlinePaint, Stroke outlineStroke, float alpha) {
super(paint, stroke, outlinePaint, outlineStroke, alpha);
this.value = value;
} | source/org/jfree/chart/plot/ValueMarker.java | 93 | 97 | ||
Chart-24 | public Paint getPaint(double value) {
double v = Math.max(value, this.lowerBound);
v = Math.min(v, this.upperBound);
int g = (int) ((value - this.lowerBound) / (this.upperBound
- this.lowerBound) * 255.0);
return new Color(g, g, g);
} | public Paint getPaint(double value) {
double v = Math.max(value, this.lowerBound);
v = Math.min(v, this.upperBound);
int g = (int) ((v - this.lowerBound) / (this.upperBound
- this.lowerBound) * 255.0);
return new Color(g, g, g);
} | source/org/jfree/chart/renderer/GrayPaintScale.java | 123 | 129 | ||
Chart-3 | public TimeSeries createCopy(int start, int end)
throws CloneNotSupportedException {
if (start < 0) {
throw new IllegalArgumentException("Requires start >= 0.");
}
if (end < start) {
throw new IllegalArgumentException("Requires start <= end.");
}
TimeSeries copy = (TimeSeries... | public TimeSeries createCopy(int start, int end)
throws CloneNotSupportedException {
if (start < 0) {
throw new IllegalArgumentException("Requires start >= 0.");
}
if (end < start) {
throw new IllegalArgumentException("Requires start <= end.");
}
TimeSeries copy = (TimeSeries... | source/org/jfree/data/time/TimeSeries.java | 1,048 | 1,072 | ||
Chart-4 | public Range getDataRange(ValueAxis axis) {
Range result = null;
List mappedDatasets = new ArrayList();
List includedAnnotations = new ArrayList();
boolean isDomainAxis = true;
// is it a domain axis?
int domainIndex = getDomainAxisIndex(axis);
if (domainIndex >= 0) {
isDomainAxis ... | public Range getDataRange(ValueAxis axis) {
Range result = null;
List mappedDatasets = new ArrayList();
List includedAnnotations = new ArrayList();
boolean isDomainAxis = true;
// is it a domain axis?
int domainIndex = getDomainAxisIndex(axis);
if (domainIndex >= 0) {
isDomainAxis ... | source/org/jfree/chart/plot/XYPlot.java | 4,425 | 4,519 | ||
Chart-6 | public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ShapeList)) {
return false;
}
return super.equals(obj);
} | public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ShapeList)) {
return false;
}
ShapeList that = (ShapeList) obj;
int listSize = size();
for (int i = 0; i < listSize; i++) {
if (!ShapeUtilities.equal((Shape) get(i), (Shape) tha... | source/org/jfree/chart/util/ShapeList.java | 103 | 113 | ||
Chart-7 | private void updateBounds(TimePeriod period, int index) {
long start = period.getStart().getTime();
long end = period.getEnd().getTime();
long middle = start + ((end - start) / 2);
if (this.minStartIndex >= 0) {
long minStart = getDataItem(this.minStartIndex).getPeriod()
.getSt... | private void updateBounds(TimePeriod period, int index) {
long start = period.getStart().getTime();
long end = period.getEnd().getTime();
long middle = start + ((end - start) / 2);
if (this.minStartIndex >= 0) {
long minStart = getDataItem(this.minStartIndex).getPeriod()
.getSt... | source/org/jfree/data/time/TimePeriodValues.java | 257 | 335 | ||
Chart-8 | public Week(Date time, TimeZone zone) {
// defer argument checking...
this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault());
} | public Week(Date time, TimeZone zone) {
// defer argument checking...
this(time, zone, Locale.getDefault());
} | source/org/jfree/data/time/Week.java | 173 | 176 | ||
Chart-9 | public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)
throws CloneNotSupportedException {
if (start == null) {
throw new IllegalArgumentException("Null 'start' argument.");
}
if (end == null) {
throw new IllegalArgumentException("Null 'end' argument.");
}
... | public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)
throws CloneNotSupportedException {
if (start == null) {
throw new IllegalArgumentException("Null 'start' argument.");
}
if (end == null) {
throw new IllegalArgumentException("Null 'end' argument.");
}
... | source/org/jfree/data/time/TimeSeries.java | #818 Error on TimeSeries createCopy() method | The test case at the end fails with :
java.lang.IllegalArgumentException: Requires start <= end.
The problem is in that the int start and end indexes corresponding to given timePeriod are computed incorectly. Here I would expect an empty serie to be returned, not an exception. This is with jfreechart 1.0.7
public class... | 918 | 956 |
Cli-10 | protected void setOptions(final Options options) {
this.options = options;
this.requiredOptions = options.getRequiredOptions();
} | protected void setOptions(final Options options) {
this.options = options;
this.requiredOptions = new ArrayList(options.getRequiredOptions());
} | src/java/org/apache/commons/cli/Parser.java | Missing required options not throwing MissingOptionException | When an Options object is used to parse a second set of command arguments it won't throw a MissingOptionException.
{code:java}
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.common... | 44 | 47 |
Cli-15 | public List getValues(final Option option,
List defaultValues) {
// initialize the return list
List valueList = (List) values.get(option);
// grab the correct default values
if ((valueList == null) || valueList.isEmpty()) {
valueList = defaultValues;
}
// augment ... | public List getValues(final Option option,
List defaultValues) {
// initialize the return list
List valueList = (List) values.get(option);
// grab the correct default values
if (defaultValues == null || defaultValues.isEmpty()) {
defaultValues = (List) this.defaultValues.g... | src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java | deafult arguments only works if no arguments are submitted | When using multple arguments and defaults, the behaviour is counter-intuitive and will only pick up a default if no args are passed in.
For instance in the code below I have set up so 0, 1, or 2 args may bve accepted, with defaults 100 and 1000.
I expect it to behave as follows.
1. for 2 args, 1 and 2 the values should... | 111 | 130 |
Cli-17 | protected void burstToken(String token, boolean stopAtNonOption)
{
for (int i = 1; i < token.length(); i++)
{
String ch = String.valueOf(token.charAt(i));
if (options.hasOption(ch))
{
tokens.add("-" + ch);
currentOption = options.getOption(ch);
if (c... | protected void burstToken(String token, boolean stopAtNonOption)
{
for (int i = 1; i < token.length(); i++)
{
String ch = String.valueOf(token.charAt(i));
if (options.hasOption(ch))
{
tokens.add("-" + ch);
currentOption = options.getOption(ch);
if (c... | src/java/org/apache/commons/cli/PosixParser.java | PosixParser keeps bursting tokens even if a non option character is found | PosixParser doesn't stop the bursting process of a token if stopAtNonOption is enabled and a non option character is encountered.
For example if the options a and b are defined, with stopAtNonOption=true the following command line:
-azb
is turned into:
-a zb -b
the right output should be:
-a zb | 282 | 310 |
Cli-19 | private void processOptionToken(String token, boolean stopAtNonOption)
{
if (options.hasOption(token))
{
currentOption = options.getOption(token);
tokens.add(token);
}
else if (stopAtNonOption)
{
eatTheRest = true;
tokens.add(token);
}
} | private void processOptionToken(String token, boolean stopAtNonOption)
{
if (options.hasOption(token))
{
currentOption = options.getOption(token);
}
else if (stopAtNonOption)
{
eatTheRest = true;
}
tokens.add(token);
} | src/java/org/apache/commons/cli/PosixParser.java | PosixParser ignores unrecognized tokens starting with '-' | PosixParser doesn't handle properly unrecognized tokens starting with '-' when stopAtNonOption is enabled, the token is simply ignored.
For example, if the option 'a' is defined, the following command line:
-z -a foo
is interpreted as:
-a foo | 227 | 239 |
Cli-2 | protected void burstToken(String token, boolean stopAtNonOption)
{
int tokenLength = token.length();
for (int i = 1; i < tokenLength; i++)
{
String ch = String.valueOf(token.charAt(i));
boolean hasOption = options.hasOption(ch);
if (hasOption)
... | protected void burstToken(String token, boolean stopAtNonOption)
{
int tokenLength = token.length();
for (int i = 1; i < tokenLength; i++)
{
String ch = String.valueOf(token.charAt(i));
boolean hasOption = options.hasOption(ch);
if (hasOption)
... | src/java/org/apache/commons/cli/PosixParser.java | [cli] Parameter value "-something" misinterpreted as a parameter | If a parameter value is passed that contains a hyphen as the (delimited) first
character, CLI parses this a parameter. For example using the call
java myclass -t "-something"
Results in the parser creating the invalid parameter -o (noting that it is
skipping the 's')
My code is using the Posix parser as follows
Opti... | 278 | 308 |
Cli-20 | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
init();
this.options = options;
// an iterator for the command line tokens
Iterator iter = Arrays.asList(arguments).iterator();
// process each command line token
while (iter.hasNext())
{
// ... | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
init();
this.options = options;
// an iterator for the command line tokens
Iterator iter = Arrays.asList(arguments).iterator();
// process each command line token
while (iter.hasNext())
{
// ... | src/java/org/apache/commons/cli/PosixParser.java | PosixParser keeps processing tokens after a non unrecognized long option | PosixParser keeps processing tokens after a non unrecognized long option when stopAtNonOption is enabled. The tokens after the unrecognized long option are burst, split around '=', etc.. instead of being kept as is.
For example, with the options 'a' and 'b' defined, 'b' having an argument, the following command line:
... | 97 | 159 |
Cli-23 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpFormatter();
... | 805 | 841 |
Cli-24 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpFormatter();
... | 809 | 852 |
Cli-25 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpFormatter();
... | 809 | 851 |
Cli-26 | public static Option create(String opt) throws IllegalArgumentException
{
// create the option
Option option = new Option(opt, description);
// set the option properties
option.setLongOpt(longopt);
option.setRequired(required);
option.setOptionalArg(optionalArg);
opt... | public static Option create(String opt) throws IllegalArgumentException
{
Option option = null;
try {
// create the option
option = new Option(opt, description);
// set the option properties
option.setLongOpt(longopt);
option.setRequired(required);
option.setOpti... | src/java/org/apache/commons/cli/OptionBuilder.java | OptionBuilder is not reseted in case of an IAE at create | If the call to OptionBuilder.create() fails with an IllegalArgumentException, the OptionBuilder is not resetted and its next usage may contain unwanted settings. Actually this let the CLI-1.2 RCs fail on IBM JDK 6 running on Maven 2.0.10. | 346 | 364 |
Cli-27 | public void setSelected(Option option) throws AlreadySelectedException
{
if (option == null)
{
// reset the option previously selected
selected = null;
return;
}
// if no option has already been selected or the
// same option is being reselected then set the
// sele... | public void setSelected(Option option) throws AlreadySelectedException
{
if (option == null)
{
// reset the option previously selected
selected = null;
return;
}
// if no option has already been selected or the
// same option is being reselected then set the
// sele... | src/java/org/apache/commons/cli/OptionGroup.java | Unable to select a pure long option in a group | OptionGroup doesn't play nice with options with a long name and no short name. If the selected option hasn't a short name, group.setSelected(option) has no effect. | 86 | 106 |
Cli-28 | protected void processProperties(Properties properties)
{
if (properties == null)
{
return;
}
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
{
String option = e.nextElement().toString();
if (!cmd.hasOption(option))
{
Option opt = ... | protected void processProperties(Properties properties)
{
if (properties == null)
{
return;
}
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
{
String option = e.nextElement().toString();
if (!cmd.hasOption(option))
{
Option opt = ... | src/java/org/apache/commons/cli/Parser.java | Default options may be partially processed | The Properties instance passed to the Parser.parse() method to initialize the default options may be partially processed. This happens when the properties contains an option that doesn't accept arguments and has a default value that isn't evaluated to "true". When this case occurs the processing of the properties is st... | 252 | 296 |
Cli-29 | static String stripLeadingAndTrailingQuotes(String str)
{
if (str.startsWith("\""))
{
str = str.substring(1, str.length());
}
int length = str.length();
if (str.endsWith("\""))
{
str = str.substring(0, length - 1);
}
return str;
} | static String stripLeadingAndTrailingQuotes(String str)
{
int length = str.length();
if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1)
{
str = str.substring(1, length - 1);
}
return str;
} | src/java/org/apache/commons/cli/Util.java | Commons CLI incorrectly stripping leading and trailing quotes | org.apache.commons.cli.Parser.processArgs() calls Util.stripLeadingAndTrailingQuotes() for all argument values. IMHO this is incorrect and totally broken.
It is trivial to create a simple test for this. Output:
$ java -cp target/clitest.jar Clitest --balloo "this is a \"test\""
Value of argument balloo is 'this... | 63 | 76 |
Cli-3 | public static Number createNumber(String str)
{
try
{
return NumberUtils.createNumber(str);
}
catch (NumberFormatException nfe)
{
System.err.println(nfe.getMessage());
}
return null;
} | public static Number createNumber(String str)
{
try
{
if( str != null )
{
if( str.indexOf('.') != -1 )
{
return Double.valueOf(str);
}
else
{
return Long.va... | src/java/org/apache/commons/cli/TypeHandler.java | PosixParser interupts "-target opt" as "-t arget opt" | This was posted on the Commons-Developer list and confirmed as a bug.
> Is this a bug? Or am I using this incorrectly?
> I have an option with short and long values. Given code that is
> essentially what is below, with a PosixParser I see results as
> follows:
>
> A command line with just "-t" prints out the resu... | 158 | 170 |
Cli-32 | protected int findWrapPos(String text, int width, int startPos)
{
int pos;
// the line ends before the max wrap pos or a new line char found
if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width)
|| ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width))
{
return... | protected int findWrapPos(String text, int width, int startPos)
{
int pos;
// the line ends before the max wrap pos or a new line char found
if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width)
|| ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width))
{
return... | src/main/java/org/apache/commons/cli/HelpFormatter.java | StringIndexOutOfBoundsException in HelpFormatter.findWrapPos | In the last while loop in HelpFormatter.findWrapPos, it can pass text.length() to text.charAt(int), which throws a StringIndexOutOfBoundsException. The first expression in that while loop condition should use a <, not a <=.
This is on line 908 in r779646:
http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/o... | 902 | 943 |
Cli-33 | public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text)
{
StringBuffer sb = new StringBuffer(text.length());
renderWrappedText(sb, width, nextLineTabStop, text);
pw.println(sb.toString());
} | public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text)
{
StringBuffer sb = new StringBuffer(text.length());
renderWrappedTextBlock(sb, width, nextLineTabStop, text);
pw.println(sb.toString());
} | src/main/java/org/apache/commons/cli/HelpFormatter.java | HelpFormatter strips leading whitespaces in the footer | I discovered a bug in Commons CLI while using it through Groovy's CliBuilder. See the following issue:
http://jira.codehaus.org/browse/GROOVY-4313?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
Copied:
The following code:
def cli = new CliBuilder(footer: "line1:\n line2:\n")
cli.usage()
Produces ... | 726 | 732 |
Cli-35 | public List<String> getMatchingOptions(String opt)
{
opt = Util.stripLeadingHyphens(opt);
List<String> matchingOpts = new ArrayList<String>();
// for a perfect match return the single option only
for (String longOpt : longOpts.keySet())
{
if (longOpt.startsWith(opt))
{
... | public List<String> getMatchingOptions(String opt)
{
opt = Util.stripLeadingHyphens(opt);
List<String> matchingOpts = new ArrayList<String>();
// for a perfect match return the single option only
if(longOpts.keySet().contains(opt)) {
return Collections.singletonList(opt);
}
for (S... | src/main/java/org/apache/commons/cli/Options.java | LongOpt falsely detected as ambiguous | Options options = new Options();
options.addOption(Option.builder().longOpt("importToOpen").hasArg().argName("FILE").build());
options.addOption(Option.builder("i").longOpt("import").hasArg().argName("FILE").build());
Parsing "--import=FILE" is not possible since 1.3 as it throws a AmbiguousOptionException stating that... | 233 | 250 |
Cli-37 | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
return token.startsWith("-") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2));
// remove leading "-" and "=value"
} | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = pos == -1 ? token.substring(1) : toke... | src/main/java/org/apache/commons/cli/DefaultParser.java | Optional argument picking up next regular option as its argument | I'm not sure if this is a complete fix. It seems to miss the case where short options are concatenated after an option that takes an optional argument.
A failing test case for this would be to modify {{setUp()}} in BugCLI265Test.java to include short options "a" and "b":
{code:java}
@Before
public void setUp... | 299 | 305 |
Cli-38 | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = pos == -1 ? token.substring(1) : toke... | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = pos == -1 ? token.substring(1) : toke... | src/main/java/org/apache/commons/cli/DefaultParser.java | Optional argument picking up next regular option as its argument | I have recently migrated a project from CLI 1.2 to 1.3.1 and have encountered what may be a bug or difference in the way optional arguments are being processed.
I have a command that opens several different kinds of databases by type, or alternately, the last opened database of that type.
Option TYPE1 = Option.builde... | 299 | 312 |
Cli-39 | public static Object createValue(final String str, final Class<?> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return createObject(str);
}
... | public static Object createValue(final String str, final Class<?> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return createObject(str);
}
... | src/main/java/org/apache/commons/cli/TypeHandler.java | Option parser type EXISTING_FILE_VALUE not check file existing | When the user pass option type FileInputStream.class, I think the expected behavior for the return value is the same type, which the user passed.
Options options = new Options();
options.addOption(Option.builder("f").hasArg().type(FileInputStream.class).build());
CommandLine cline = new DefaultParser().parse(options, ... | 64 | 106 |
Cli-4 | private void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (requiredOptions.size() > 0)
{
Iterator iter = requiredOptions.iterator();
StringBuffer buff = new StringBuffer();
// loop through the re... | private void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (requiredOptions.size() > 0)
{
Iterator iter = requiredOptions.iterator();
StringBuffer buff = new StringBuffer("Missing required option");
... | src/java/org/apache/commons/cli/Parser.java | PosixParser interupts "-target opt" as "-t arget opt" | This was posted on the Commons-Developer list and confirmed as a bug.
> Is this a bug? Or am I using this incorrectly?
> I have an option with short and long values. Given code that is
> essentially what is below, with a PosixParser I see results as
> follows:
>
> A command line with just "-t" prints out the resul... | 290 | 309 |
Cli-40 | 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 (PatternOptionBui... | 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 (PatternOptionBui... | src/main/java/org/apache/commons/cli/TypeHandler.java | 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. | 63 | 105 |
Cli-5 | 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;
} | 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;
} | src/java/org/apache/commons/cli/Util.java | 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 rej... | 34 | 46 |
Cli-8 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | HelpFormatter wraps incorrectly on every line beyond the first | The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width.
To see this, create an option with a long description, and then use the h... | 792 | 823 |
Cli-9 | 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 optio... | 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 optio... | src/java/org/apache/commons/cli/Parser.java | 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 ... | 303 | 324 |
Closure-1 | private void removeUnreferencedFunctionArgs(Scope fnScope) {
// Notice that removing unreferenced function args breaks
// Function.prototype.length. In advanced mode, we don't really care
// about this: we consider "length" the equivalent of reflecting on
// the function's lexical source.
//
// Rather than ... | private void removeUnreferencedFunctionArgs(Scope fnScope) {
// Notice that removing unreferenced function args breaks
// Function.prototype.length. In advanced mode, we don't really care
// about this: we consider "length" the equivalent of reflecting on
// the function's lexical source.
//
// Rather than ... | src/com/google/javascript/jscomp/RemoveUnusedVars.java | function arguments should not be optimized away | Function arguments should not be optimized away, as this comprimizes the function's length property.
What steps will reproduce the problem?
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==
function foo (bar, baz) {
return bar;
}
alert ... | 369 | 406 |
Closure-10 | static boolean mayBeString(Node n, boolean recurse) {
if (recurse) {
return allResultsMatch(n, MAY_BE_STRING_PREDICATE);
} else {
return mayBeStringHelper(n);
}
} | static boolean mayBeString(Node n, boolean recurse) {
if (recurse) {
return anyResultsMatch(n, MAY_BE_STRING_PREDICATE);
} else {
return mayBeStringHelper(n);
}
} | src/com/google/javascript/jscomp/NodeUtil.java | 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,415 | 1,421 |
Closure-101 | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new ClosureCodingConvention());
CompilationLevel level = flags.compilation_level;
level.setOptionsForCompilationLevel(options);
if (flags.debug) {
level.setDebugOptionsForCompilationLev... | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new ClosureCodingConvention());
CompilationLevel level = flags.compilation_level;
level.setOptionsForCompilationLevel(options);
if (flags.debug) {
level.setDebugOptionsForCompilationLev... | src/com/google/javascript/jscomp/CommandLineRunner.java | --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... | 419 | 439 |
Closure-102 | 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);
}
removeDuplicateDeclar... | 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(extern... | src/com/google/javascript/jscomp/Normalize.java | 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. | 87 | 97 |
Closure-104 | 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) {
... | 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) {
... | src/com/google/javascript/rhino/jstype/UnionType.java | Typos in externs/html5.js | Line 354:
CanvasRenderingContext2D.prototype.globalCompositingOperation;
Line 366:
CanvasRenderingContext2D.prototype.mitreLimit;
They should be globalCompositeOperation and miterLimit, respectively. | 273 | 298 |
Closure-107 | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
if (flags.processJqueryPrimitives) {
options.setCodingConvention(new JqueryCodingConvention());
} else {
options.setCodingConvention(new ClosureCodingConvention());
}
options.setExtraAnnotationNames(flags.ext... | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
if (flags.processJqueryPrimitives) {
options.setCodingConvention(new JqueryCodingConvention());
} else {
options.setCodingConvention(new ClosureCodingConvention());
}
options.setExtraAnnotationNames(flags.ext... | src/com/google/javascript/jscomp/CommandLineRunner.java | Variable names prefixed with MSG_ cause error with advanced optimizations | Variables named something with MSG_ seem to cause problems with the module system, even if no modules are used in the code.
$ echo "var MSG_foo='bar'" | closure --compilation_level ADVANCED_OPTIMIZATIONS
stdin:1: ERROR - message not initialized using goog.getMsg
var MSG_foo='bar'
^
It works fine with msg_foo... | 806 | 865 |
Closure-109 | private Node parseContextTypeExpression(JsDocToken token) {
return parseTypeName(token);
} | private Node parseContextTypeExpression(JsDocToken token) {
if (token == JsDocToken.QMARK) {
return newNode(Token.QMARK);
} else {
return parseBasicTypeExpression(token);
}
} | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | 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 ... | 1,907 | 1,909 |
Closure-11 | 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.g... | 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.g... | src/com/google/javascript/jscomp/TypeCheck.java | 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... | 1,303 | 1,321 |
Closure-111 | protected JSType caseTopType(JSType topType) {
return topType;
} | protected JSType caseTopType(JSType topType) {
return topType.isAllType() ?
getNativeType(ARRAY_TYPE) : topType;
} | src/com/google/javascript/jscomp/type/ClosureReverseAbstractInterpreter.java | 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 - initializ... | 53 | 55 |
Closure-112 | 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 =
inferTemplateT... | 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(
... | src/com/google/javascript/jscomp/TypeInference.java | 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... | 1,183 | 1,210 |
Closure-113 | private void processRequireCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node arg = left.getNext();
if (verifyLastArgumentIsString(t, left, arg)) {
String ns = arg.getString();
ProvidedName provided = providedNames.get(ns);
if (provided == null || !provided.isExplicitlyPr... | private void processRequireCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node arg = left.getNext();
if (verifyLastArgumentIsString(t, left, arg)) {
String ns = arg.getString();
ProvidedName provided = providedNames.get(ns);
if (provided == null || !provided.isExplicitlyPr... | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | Bug in require calls processing | The Problem
ProcessClosurePrimitives pass has a bug in processRequireCall method.
The method processes goog.require calls. If a require symbol is invalid i.e is not provided anywhere, the method collects it for further error reporting. If the require symbol is valid, the method removes it from the ast.
All invalid... | 295 | 334 |
Closure-117 | String getReadableJSTypeName(Node n, boolean dereference) {
// The best type name is the actual type name.
// If we're analyzing a GETPROP, the property may be inherited by the
// prototype chain. So climb the prototype chain and find out where
// the property was originally defined.
if (n.isGetProp()) {
... | String getReadableJSTypeName(Node n, boolean dereference) {
JSType type = getJSType(n);
if (dereference) {
ObjectType dereferenced = type.dereference();
if (dereferenced != null) {
type = dereferenced;
}
}
// The best type name is the actual type name.
if (type.isFunctionPrototypeType() ||
... | src/com/google/javascript/jscomp/TypeValidator.java | Wrong type name reported on missing property error. | /**
* @constructor
*/
function C2() {}
/**
* @constructor
*/
function C3(c2) {
/**
* @type {C2}
* @private
*/
this.c2_;
use(this.c2_.prop);
}
Produces:
Property prop never defined on C3.c2_
But should be:
Property prop never defined on C2 | 724 | 777 |
Closure-118 | 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,... | 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.get... | src/com/google/javascript/jscomp/DisambiguateProperties.java | 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.ba... | 490 | 513 |
Closure-12 | private boolean hasExceptionHandler(Node cfgNode) {
return false;
} | 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;
} | src/com/google/javascript/jscomp/MaybeReachingVariableUse.java | 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;
... | 159 | 161 |
Closure-120 | 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;
} ... | 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.getSy... | src/com/google/javascript/jscomp/ReferenceCollectingCallback.java | 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... | 421 | 438 |
Closure-122 | private void handleBlockComment(Comment comment) {
if (comment.getValue().indexOf("/* @") != -1 || comment.getValue().indexOf("\n * @") != -1) {
errorReporter.warning(
SUSPICIOUS_COMMENT_WARNING,
sourceName,
comment.getLineno(), "", 0);
}
} | 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);
}
} | src/com/google/javascript/jscomp/parsing/IRFactory.java | 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 Licen... | 251 | 258 |
Closure-124 | 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)) {
... | 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.... | src/com/google/javascript/jscomp/ExploitAssigns.java | 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 compi... | 206 | 220 |
Closure-128 | 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';
} | 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';
} | src/com/google/javascript/jscomp/CodeGenerator.java | 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. | 783 | 792 |
Closure-129 | 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)... | 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 (!N... | src/com/google/javascript/jscomp/PrepareAst.java | 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)("$ve... | 158 | 177 |
Closure-13 | 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.getFirstCh... | 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.getFirstCh... | src/com/google/javascript/jscomp/PeepholeOptimizationsPass.java | 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: functio... | 113 | 138 |
Closure-130 | private void inlineAliases(GlobalNamespace namespace) {
// Invariant: All the names in the worklist meet condition (a).
Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest());
while (!workList.isEmpty()) {
Name name = workList.pop();
// Don't attempt to inline a getter or setter property ... | private void inlineAliases(GlobalNamespace namespace) {
// Invariant: All the names in the worklist meet condition (a).
Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest());
while (!workList.isEmpty()) {
Name name = workList.pop();
// Don't attempt to inline a getter or setter property ... | src/com/google/javascript/jscomp/CollapseProperties.java | arguments is moved to another scope | Using ADVANCED_OPTIMIZATIONS with CompilerOptions.collapsePropertiesOnExternTypes = true a script I used broke, it was something like:
function () {
return function () {
var arg = arguments;
setTimeout(function() { alert(args); }, 0);
}
}
Unfortunately it was rewritten to:
function () {
return... | 161 | 197 |
Closure-131 | 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 tr... | 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)) ... | src/com/google/javascript/rhino/TokenStream.java | 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... | 190 | 206 |
Closure-133 | private String getRemainingJSDocLine() {
String result = stream.getRemainingJSDocLine();
return result;
} | private String getRemainingJSDocLine() {
String result = stream.getRemainingJSDocLine();
unreadToken = NO_UNREAD_TOKEN;
return result;
} | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | 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. | 2,399 | 2,402 |
Closure-145 | 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... | 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 ... | src/com/google/javascript/jscomp/CodeGenerator.java | 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 ... | 708 | 715 |
Closure-146 | 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);
... | 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(JST... | src/com/google/javascript/rhino/jstype/JSType.java | 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 ou... | 696 | 715 |
Closure-15 | 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 n... | 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 n... | src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java | 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' ) );... | 84 | 109 |
Closure-150 | @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.ge... | @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);
} | src/com/google/javascript/jscomp/TypedScopeCreator.java | 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}
... | 1,443 | 1,466 |
Closure-159 | 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.get... | 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.getF... | src/com/google/javascript/jscomp/InlineFunctions.java | 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 th... | 773 | 787 |
Closure-161 | 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 c... | 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() != Toke... | src/com/google/javascript/jscomp/PeepholeFoldConstants.java | 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... | 1,278 | 1,322 |
Closure-166 | 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({});
... | 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({});
... | src/com/google/javascript/rhino/jstype/PrototypeObjectType.java | 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);
... | 556 | 574 |
Closure-172 | private boolean isQualifiedNameInferred(
String qName, Node n, JSDocInfo info,
Node rhsValue, JSType valueType) {
if (valueType == null) {
return true;
}
// Prototypes of constructors and interfaces are always declared.
if (qName != null && qName.endsWith(".prototype")) {
return false;
}
... | private boolean isQualifiedNameInferred(
String qName, Node n, JSDocInfo info,
Node rhsValue, JSType valueType) {
if (valueType == null) {
return true;
}
// Prototypes of constructors and interfaces are always declared.
if (qName != null && qName.endsWith(".prototype")) {
String className = qNa... | src/com/google/javascript/jscomp/TypedScopeCreator.java | Type of prototype property incorrectly inferred to string | What steps will reproduce the problem?
1. Compile the following code:
/** @param {Object} a */
function f(a) {
a.prototype = '__proto';
}
/** @param {Object} a */
function g(a) {
a.prototype = function(){};
}
What is the expected output? What do you see instead?
Should type check. Instead, gives error:... | 1,661 | 1,709 |
Closure-20 | 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 optim... | 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 optim... | src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java | 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:... | 208 | 230 |
Closure-23 | 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.isNumber()) {
... | 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.isNumber()) {
... | src/com/google/javascript/jscomp/PeepholeFoldConstants.java | tryFoldArrayAccess does not check for side effects | What steps will reproduce the problem?
1. Compile the following program with simple or advanced optimization:
console.log([console.log('hello, '), 'world!'][1]);
What is the expected output? What do you see instead?
The expected output would preserve side effects. It would not transform the program at all or transfo... | 1,422 | 1,472 |
Closure-24 | 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.ge... | 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.getS... | src/com/google/javascript/jscomp/ScopedAliases.java | 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. | 272 | 297 |
Closure-25 | 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();
i... | 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 ... | src/com/google/javascript/jscomp/TypeInference.java | 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(parr... | 1,035 | 1,063 |
Closure-32 | private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
WhitespaceOption option) {
if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
token == JsDocToken.EOF) {
return new ExtractionInfo("", token);
}
stream.update();
int start... | private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
WhitespaceOption option) {
if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
token == JsDocToken.EOF) {
return new ExtractionInfo("", token);
}
stream.update();
int start... | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | Preserve doesn't preserve whitespace at start of line | What steps will reproduce the problem?
Code such as:
/**
* @preserve
This
was
ASCII
Art
*/
What is the expected output? What do you see instead?
The words line up on the left:
/*
This
was
ASCII
Art
*/
What version of the product are you using? On what operating system?
Live web veris... | 1,329 | 1,429 |
D4J-Repair is a curated subset of Defects4J, containing 371 single-function Java bugs from real-world projects. Each example includes a buggy implementation, its corresponding fixed version, and unit tests for verification.
Each row contains:
task_id: Unique identifier for the task (in format: project_name-bug_id)buggy_code: The buggy implementationfixed_code: The correct implementationfile_path: Original file path in the Defects4J repositoryissue_title: Title of the bugissue_description: Description of the bugstart_line: Start line of the buggy functionend_line: End line of the buggy functionThis dataset is derived from Defects4J, a collection of reproducible bugs from real-world Java projects. We carefully selected and processed single-function bugs to create this benchmark.
@article{morepair,
author = {Yang, Boyang and Tian, Haoye and Ren, Jiadong and Zhang, Hongyu and Klein, Jacques and Bissyande, Tegawende and Le Goues, Claire and Jin, Shunfu},
title = {MORepair: Teaching LLMs to Repair Code via Multi-Objective Fine-Tuning},
year = {2025},
publisher = {Association for Computing Machinery},
issn = {1049-331X},
url = {https://doi.org/10.1145/3735129},
doi = {10.1145/3735129},
journal = {ACM Trans. Softw. Eng. Methodol.},
}