Datasets:

Modalities:
Tabular
Text
Formats:
json
Size:
< 1K
ArXiv:
Libraries:
Datasets
pandas
License:
Dataset Viewer
Auto-converted to Parquet
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; } int seriesCount = dataset.getRowCount(); if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) { for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } else { for (int i = seriesCount - 1; i >= 0; i--) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } 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; } int seriesCount = dataset.getRowCount(); if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) { for (int i = 0; i < seriesCount; i++) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } else { for (int i = seriesCount - 1; i >= 0; i--) { if (isSeriesVisibleInLegend(i)) { LegendItem item = getLegendItem(index, i); if (item != null) { result.add(item); } } } } 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; } int index = this.plot.getIndexOf(this); CategoryDataset dataset = this.plot.getDataset(index); if (dataset != null) { return result; } int seriesCount = dataset.getRowCount(); ... } The warning is in the last code line where seriesCount is assigned. The variable dataset is guaranteed to be null in this location, I suppose that the check before that should actually read "if (dataset == null)", not "if (dataset != null)". This is trunk as of 2010-02-08.
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); PathIterator iterator2 = p1.getPathIterator(null); double[] d1 = new double[6]; double[] d2 = new double[6]; boolean done = iterator1.isDone() && iterator2.isDone(); while (!done) { if (iterator1.isDone() != iterator2.isDone()) { return false; } int seg1 = iterator1.currentSegment(d1); int seg2 = iterator2.currentSegment(d2); if (seg1 != seg2) { return false; } if (!Arrays.equals(d1, d2)) { return false; } iterator1.next(); iterator2.next(); done = iterator1.isDone() && iterator2.isDone(); } return true; }
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); PathIterator iterator2 = p2.getPathIterator(null); double[] d1 = new double[6]; double[] d2 = new double[6]; boolean done = iterator1.isDone() && iterator2.isDone(); while (!done) { if (iterator1.isDone() != iterator2.isDone()) { return false; } int seg1 = iterator1.currentSegment(d1); int seg2 = iterator2.currentSegment(d2); if (seg1 != seg2) { return false; } if (!Arrays.equals(d1, d2)) { return false; } iterator1.next(); iterator2.next(); done = iterator1.isDone() && iterator2.isDone(); } return true; }
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 seriesTitle = new TextTitle("Series Title", new Font("SansSerif", Font.BOLD, 12)); seriesTitle.setPosition(RectangleEdge.BOTTOM); this.pieChart.setTitle(seriesTitle); this.aggregatedItemsKey = "Other"; this.aggregatedItemsPaint = Color.lightGray; this.sectionPaints = new HashMap(); }
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 seriesTitle = new TextTitle("Series Title", new Font("SansSerif", Font.BOLD, 12)); seriesTitle.setPosition(RectangleEdge.BOTTOM); this.pieChart.setTitle(seriesTitle); this.aggregatedItemsKey = "Other"; this.aggregatedItemsPaint = Color.lightGray; this.sectionPaints = new HashMap(); }
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) super.clone(); copy.data = new java.util.ArrayList(); if (this.data.size() > 0) { for (int index = start; index <= end; index++) { TimeSeriesDataItem item = (TimeSeriesDataItem) this.data.get(index); TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone(); try { copy.add(clone); } catch (SeriesException e) { e.printStackTrace(); } } } return copy; }
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) super.clone(); copy.minY = Double.NaN; copy.maxY = Double.NaN; copy.data = new java.util.ArrayList(); if (this.data.size() > 0) { for (int index = start; index <= end; index++) { TimeSeriesDataItem item = (TimeSeriesDataItem) this.data.get(index); TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone(); try { copy.add(clone); } catch (SeriesException e) { e.printStackTrace(); } } } return copy; }
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 = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis( new Integer(domainIndex))); if (domainIndex == 0) { // grab the plot's annotations Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // or is it a range axis? int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis( new Integer(rangeIndex))); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // iterate through the datasets that map to the axis and get the union // of the ranges. Iterator iterator = mappedDatasets.iterator(); while (iterator.hasNext()) { XYDataset d = (XYDataset) iterator.next(); if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } Collection c = r.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; }
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 = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis( new Integer(domainIndex))); if (domainIndex == 0) { // grab the plot's annotations Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // or is it a range axis? int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis( new Integer(rangeIndex))); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // iterate through the datasets that map to the axis and get the union // of the ranges. Iterator iterator = mappedDatasets.iterator(); while (iterator.hasNext()) { XYDataset d = (XYDataset) iterator.next(); if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } if (r != null) { Collection c = r.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; }
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) that.get(i))) { return false; } } return true; }
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() .getStart().getTime(); if (start < minStart) { this.minStartIndex = index; } } else { this.minStartIndex = index; } if (this.maxStartIndex >= 0) { long maxStart = getDataItem(this.maxStartIndex).getPeriod() .getStart().getTime(); if (start > maxStart) { this.maxStartIndex = index; } } else { this.maxStartIndex = index; } if (this.minMiddleIndex >= 0) { long s = getDataItem(this.minMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd() .getTime(); long minMiddle = s + (e - s) / 2; if (middle < minMiddle) { this.minMiddleIndex = index; } } else { this.minMiddleIndex = index; } if (this.maxMiddleIndex >= 0) { long s = getDataItem(this.minMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd() .getTime(); long maxMiddle = s + (e - s) / 2; if (middle > maxMiddle) { this.maxMiddleIndex = index; } } else { this.maxMiddleIndex = index; } if (this.minEndIndex >= 0) { long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd() .getTime(); if (end < minEnd) { this.minEndIndex = index; } } else { this.minEndIndex = index; } if (this.maxEndIndex >= 0) { long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd() .getTime(); if (end > maxEnd) { this.maxEndIndex = index; } } else { this.maxEndIndex = index; } }
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() .getStart().getTime(); if (start < minStart) { this.minStartIndex = index; } } else { this.minStartIndex = index; } if (this.maxStartIndex >= 0) { long maxStart = getDataItem(this.maxStartIndex).getPeriod() .getStart().getTime(); if (start > maxStart) { this.maxStartIndex = index; } } else { this.maxStartIndex = index; } if (this.minMiddleIndex >= 0) { long s = getDataItem(this.minMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd() .getTime(); long minMiddle = s + (e - s) / 2; if (middle < minMiddle) { this.minMiddleIndex = index; } } else { this.minMiddleIndex = index; } if (this.maxMiddleIndex >= 0) { long s = getDataItem(this.maxMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.maxMiddleIndex).getPeriod().getEnd() .getTime(); long maxMiddle = s + (e - s) / 2; if (middle > maxMiddle) { this.maxMiddleIndex = index; } } else { this.maxMiddleIndex = index; } if (this.minEndIndex >= 0) { long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd() .getTime(); if (end < minEnd) { this.minEndIndex = index; } } else { this.minEndIndex = index; } if (this.maxEndIndex >= 0) { long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd() .getTime(); if (end > maxEnd) { this.maxEndIndex = index; } } else { this.maxEndIndex = index; } }
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."); } if (start.compareTo(end) > 0) { throw new IllegalArgumentException( "Requires start on or before end."); } boolean emptyRange = false; int startIndex = getIndex(start); if (startIndex < 0) { startIndex = -(startIndex + 1); if (startIndex == this.data.size()) { emptyRange = true; // start is after last data item } } int endIndex = getIndex(end); if (endIndex < 0) { // end period is not in original series endIndex = -(endIndex + 1); // this is first item AFTER end period endIndex = endIndex - 1; // so this is last item BEFORE end } if (endIndex < 0) { emptyRange = true; } if (emptyRange) { TimeSeries copy = (TimeSeries) super.clone(); copy.data = new java.util.ArrayList(); return copy; } else { return createCopy(startIndex, endIndex); } }
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."); } if (start.compareTo(end) > 0) { throw new IllegalArgumentException( "Requires start on or before end."); } boolean emptyRange = false; int startIndex = getIndex(start); if (startIndex < 0) { startIndex = -(startIndex + 1); if (startIndex == this.data.size()) { emptyRange = true; // start is after last data item } } int endIndex = getIndex(end); if (endIndex < 0) { // end period is not in original series endIndex = -(endIndex + 1); // this is first item AFTER end period endIndex = endIndex - 1; // so this is last item BEFORE end } if ((endIndex < 0) || (endIndex < startIndex)) { emptyRange = true; } if (emptyRange) { TimeSeries copy = (TimeSeries) super.clone(); copy.data = new java.util.ArrayList(); return copy; } else { return createCopy(startIndex, endIndex); } }
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 foo { static public void main(String args[]) { TimeSeries foo = new TimeSeries("foo",Day.class); foo.add(new Day(19,4,2005),1); foo.add(new Day(25,5,2005),1); foo.add(new Day(28,5,2005),1); foo.add(new Day(30,5,2005),1); foo.add(new Day(1,6,2005),1); foo.add(new Day(3,6,2005),1); foo.add(new Day(19,8,2005),1); foo.add(new Day(31,1,2006),1); try \{ TimeSeries bar = foo.createCopy\(new Day\(1,12,2005\),new Day\(18,1,2006\)\); \} catch \(CloneNotSupportedException e\) \{ e.printStackTrace\(\); } }
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.commons.cli.ParseException; public class Example { public static void main(String[] args) throws ParseException { brokenExample(); workingExample(); } // throws exception as expected private static void workingExample() throws ParseException { String[] args = {}; Options opts = new Options(); opts.addOption(OptionBuilder.isRequired().create('v')); GnuParser parser = new GnuParser(); CommandLine secondCL = parser.parse(opts, args); System.out.println("Done workingExample"); } // fails to throw exception on second invocation of parse private static void brokenExample() throws ParseException { String[] firstArgs = { "-v" }; String[] secondArgs = {}; Options opts = new Options(); opts.addOption(OptionBuilder.isRequired().create('v')); GnuParser parser = new GnuParser(); CommandLine firstCL = parser.parse(opts, firstArgs); CommandLine secondCL = parser.parse(opts, secondArgs); System.out.println("Done brokenExample"); } } {code} This is a result of the Options object returning the reference to its own list and the parsers modifying that list. The first call is removing the required options as they are found and subsequent calls get back an empty list.
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 the list with the default values if ((valueList == null) || valueList.isEmpty()) { valueList = (List) this.defaultValues.get(option); } // if there are more default values as specified, add them to // the list. // copy the list first return valueList == null ? Collections.EMPTY_LIST : valueList; }
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.get(option); } // augment the list with the default values if (defaultValues != null && !defaultValues.isEmpty()) { if (valueList == null || valueList.isEmpty()) { valueList = defaultValues; } else { // if there are more default values as specified, add them to // the list. if (defaultValues.size() > valueList.size()) { // copy the list first valueList = new ArrayList(valueList); for (int i=valueList.size(); i<defaultValues.size(); i++) { valueList.add(defaultValues.get(i)); } } } } return valueList == null ? Collections.EMPTY_LIST : valueList; }
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 be 1 and 2. This works as expected. 2. for 0 args passed in the values should be 100 and 1000, picking up both of the defaults. This works as expected 3. for 1 arg passed in the values should be 1 and 1000, so the second argument picks up the second default value. The valuse become just 1, which is not as expected.. Currently, in the second case will only return 1 and ignore the defaults. public void testSingleOptionSingleArgument() throws Exception { String defaulValue1 = "100"; String defaultValue2 = "1000"; final DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); final ArgumentBuilder abuilder = new ArgumentBuilder(); final GroupBuilder gbuilder = new GroupBuilder(); DefaultOption bOption = obuilder.withShortName("b") .withLongName("b") .withArgument(abuilder.withName("b") .withMinimum(0) .withMaximum(2) .withDefault(defaulValue1) .withDefault(defaultValue2) .create()) .create(); Group options = gbuilder .withName("options") .withOption(bOption) .create(); Parser parser = new Parser(); parser.setHelpTrigger("--help"); parser.setGroup(options); String enteredValue1 = "1"; String[] args = new String[] {"-b", enteredValue1} ; CommandLine cl = parser.parse(args); CommandLine cmd = cl; assertNotNull(cmd); List b = cmd.getValues("-b"); assertEquals("[" + enteredValue1 + "]", b + ""); }
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 (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { process(token.substring(i)); } else { tokens.add(token); break; } } }
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 (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { process(token.substring(i)); break; } else { tokens.add(token); break; } } }
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) { tokens.add("-" + ch); currentOption = options.getOption(ch); if (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { process(token.substring(i)); } else { tokens.add("-" + ch); } } }
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) { tokens.add("-" + ch); currentOption = options.getOption(ch); if (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { process(token.substring(i)); } else { tokens.add(token); break; } } }
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 Options options = buildCommandLineOptions(); CommandLineParser parser = new PosixParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.out.println("Invalid parameters. " + e.getMessage() + NEW_LINE); System.exit(EXIT_CODE_ERROR); } This has been tested against the nightly build dated 20050503.
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()) { // get the next command line token String token = (String) iter.next(); // handle long option --foo or --foo=bar if (token.startsWith("--")) { if (token.indexOf('=') != -1) { tokens.add(token.substring(0, token.indexOf('='))); tokens.add(token.substring(token.indexOf('=') + 1, token.length())); } else { tokens.add(token); } } // single hyphen else if ("-".equals(token)) { tokens.add(token); } else if (token.startsWith("-")) { if (token.length() == 2) { processOptionToken(token, stopAtNonOption); } else if (options.hasOption(token)) { tokens.add(token); } // requires bursting else { burstToken(token, stopAtNonOption); } } else if (stopAtNonOption) { process(token); } else { tokens.add(token); } gobble(iter); } return (String[]) tokens.toArray(new String[tokens.size()]); }
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()) { // get the next command line token String token = (String) iter.next(); // handle long option --foo or --foo=bar if (token.startsWith("--")) { int pos = token.indexOf('='); String opt = pos == -1 ? token : token.substring(0, pos); // --foo if (!options.hasOption(opt) && stopAtNonOption) { process(token); } else { tokens.add(opt); if (pos != -1) { tokens.add(token.substring(pos + 1)); } } } // single hyphen else if ("-".equals(token)) { tokens.add(token); } else if (token.startsWith("-")) { if (token.length() == 2) { processOptionToken(token, stopAtNonOption); } else if (options.hasOption(token)) { tokens.add(token); } // requires bursting else { burstToken(token, stopAtNonOption); } } else if (stopAtNonOption) { process(token); } else { tokens.add(token); } gobble(iter); } return (String[]) tokens.toArray(new String[tokens.size()]); }
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: --zop -abfoo is interpreted as: --zop -a -b foo but the last token should remain unchanged.
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))).append(defaultNewLine); // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { int lastPos = pos; text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } else if (pos == lastPos) { throw new RuntimeException("Text too long for line - throwing exception to avoid infinite loop [CLI-162]: " + text); } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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))).append(defaultNewLine); // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { sb.append(text); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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(); formatter.setWidth(20); formatter.printHelp("app", options); // hang & crash An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError.
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))).append(defaultNewLine); if (nextLineTabStop >= width) { // stops infinite loop happening throw new IllegalStateException("Total width is less than the width of the argument and indent " + "- no room for the description"); } // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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))).append(defaultNewLine); if (nextLineTabStop >= width) { // stops infinite loop happening nextLineTabStop = width - 1; } // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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(); formatter.setWidth(20); formatter.printHelp("app", options); // hang & crash An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError.
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))).append(defaultNewLine); if (nextLineTabStop >= width) { // stops infinite loop happening nextLineTabStop = width - 1; } // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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))).append(defaultNewLine); if (nextLineTabStop >= width) { // stops infinite loop happening nextLineTabStop = 1; } // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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(); formatter.setWidth(20); formatter.printHelp("app", options); // hang & crash An helpful exception indicating the insufficient width would be more appropriate than an OutOfMemoryError.
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); option.setArgs(numberOfArgs); option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); // reset the OptionBuilder properties OptionBuilder.reset(); // return the Option instance return option; }
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.setOptionalArg(optionalArg); option.setArgs(numberOfArgs); option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); } finally { // reset the OptionBuilder properties OptionBuilder.reset(); } // return the Option instance return option; }
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 // selected member variable if (selected == null || selected.equals(option.getOpt())) { selected = option.getOpt(); } else { throw new AlreadySelectedException(this, option); } }
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 // selected member variable if (selected == null || selected.equals(option.getKey())) { selected = option.getKey(); } else { throw new AlreadySelectedException(this, option); } }
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 = getOptions().getOption(option); // get the value from the properties instance String value = properties.getProperty(option); if (opt.hasArg()) { if (opt.getValues() == null || opt.getValues().length == 0) { try { opt.addValueForProcessing(value); } catch (RuntimeException exp) { // if we cannot add the value don't worry about it } } } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) { // if the value is not yes, true or 1 then don't add the // option to the CommandLine break; } cmd.addOption(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 = getOptions().getOption(option); // get the value from the properties instance String value = properties.getProperty(option); if (opt.hasArg()) { if (opt.getValues() == null || opt.getValues().length == 0) { try { opt.addValueForProcessing(value); } catch (RuntimeException exp) { // if we cannot add the value don't worry about it } } } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) { // if the value is not yes, true or 1 then don't add the // option to the CommandLine continue; } cmd.addOption(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 stopped and the remaining options are never handled. This is caused by the break statement in Parser.processProperties(Properties), a continue statement should have been used instead. The related test in ValueTest is also wrong, there are two assertions that need to be changed: Options opts = new Options(); opts.addOption("a", false, "toggle -a"); opts.addOption("c", "c", false, "toggle -c"); opts.addOption(OptionBuilder.hasOptionalArg().create('e')); properties = new Properties(); properties.setProperty( "a", "false" ); properties.setProperty( "c", "no" ); properties.setProperty( "e", "0" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive the value "0" and the second one: properties = new Properties(); properties.setProperty( "a", "just a string" ); properties.setProperty( "e", "" ); cmd = parser.parse(opts, null, properties); assertTrue( !cmd.hasOption("a") ); assertTrue( !cmd.hasOption("c") ); assertTrue( !cmd.hasOption("e") ); // Wrong, this option accepts an argument and should receive an empty string as value
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 is a "test'. The argument 'balloo' should indeed keep its trailing double quote. It is what the shell gives it, so don't try to do something clever to it. The offending code was committed here: http://svn.apache.org/viewvc?view=rev&revision=129874 and has been there for more than 6 years . Why was this committed in the first place? The fix is trivial, just get rid of Util.stripLeadingAndTrailingQuotes(), and consequently avoid calling it from Parser.processArgs().
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.valueOf(str); } } } catch (NumberFormatException nfe) { System.err.println(nfe.getMessage()); } return null; }
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 results of the catch > block > (OK) > A command line with just "-target" prints out the results of the catch > block (OK) > A command line with just "-t foobar.com" prints out "processing selected > target: foobar.com" (OK) > A command line with just "-target foobar.com" prints out "processing > selected target: arget" (ERROR?) > > ====================================================================== > == > ======================= > private static final String OPTION_TARGET = "t"; > private static final String OPTION_TARGET_LONG = "target"; > // ... > Option generateTarget = new Option(OPTION_TARGET, > OPTION_TARGET_LONG, > true, > "Generate files for the specified > target machine"); > // ... > try { > parsedLine = parser.parse(cmdLineOpts, args); > } catch (ParseException pe) { > System.out.println("Invalid command: " + pe.getMessage() + > "\n"); > HelpFormatter hf = new HelpFormatter(); > hf.printHelp(USAGE, cmdLineOpts); > System.exit(-1); > } > > if (parsedLine.hasOption(OPTION_TARGET)) { > System.out.println("processing selected target: " + > parsedLine.getOptionValue(OPTION_TARGET)); > } It is a bug but it is due to well defined behaviour (so that makes me feel a little better about myself ;). To support *special* (well I call them special anyway) like -Dsystem.property=value we need to be able to examine the first character of an option. If the first character is itself defined as an Option then the remainder of the token is used as the value, e.g. 'D' is the token, it is an option so 'system.property=value' is the argument value for that option. This is the behaviour that we are seeing for your example. 't' is the token, it is an options so 'arget' is the argument value. I suppose a solution to this could be to have a way to specify properties for parsers. In this case 'posix.special.option == true' for turning on *special* options. I'll have a look into this and let you know. Just to keep track of this and to get you used to how we operate, can you log a bug in bugzilla for this. Thanks, -John K
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 pos + 1; } else if (startPos + width >= text.length()) { return -1; } // look for the last whitespace character before startPos+width pos = startPos + width; char c; while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { --pos; } // if we found it - just return if (pos > startPos) { return pos; } // if we didn't find one, simply chop at startPos+width pos = startPos + width; while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { ++pos; } return pos == text.length() ? -1 : pos; }
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 pos + 1; } else if (startPos + width >= text.length()) { return -1; } // look for the last whitespace character before startPos+width pos = startPos + width; char c; while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { --pos; } // if we found it - just return if (pos > startPos) { return pos; } // if we didn't find one, simply chop at startPos+width pos = startPos + width; return pos == text.length() ? -1 : pos; }
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/org/apache/commons/cli/HelpFormatter.java?revision=779646&view=markup
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 the following output: line1 line2 Note that there are no whitespaces before "line2". Replacing them with "\t" doesn't solve the problem either.
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)) { matchingOpts.add(longOpt); } } return matchingOpts; }
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 (String longOpt : longOpts.keySet()) { if (longOpt.startsWith(opt)) { matchingOpts.add(longOpt); } } return matchingOpts; }
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 it cannot decide whether import is import or importToOpen. In 1.2 this is not an issue. The root lies in the new DefaultParser which does a startsWith check internally.
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) : token.substring(1, pos); return options.hasShortOption(optName); }
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() throws Exception { parser = new DefaultParser(); Option TYPE1 = Option.builder("t1").hasArg().numberOfArgs(1).optionalArg(true).argName("t1_path").build(); Option OPTION_A = Option.builder("a").hasArg(false).build(); Option OPTION_B = Option.builder("b").hasArg(false).build(); Option LAST = Option.builder("last").hasArg(false).build(); options = new Options().addOption(TYPE1).addOption(OPTION_A).addOption(OPTION_B).addOption(LAST); } {code} Add add a test for the concatenated options following an option with optional argument case: {code:java} @Test public void shouldParseConcatenatedShortOptions() throws Exception { String[] concatenatedShortOptions = new String[] { "-t1", "-ab" }; final CommandLine commandLine = parser.parse(options, concatenatedShortOptions); assertTrue(commandLine.hasOption("t1")); assertEquals(null, commandLine.getOptionValue("t1")); assertTrue(commandLine.hasOption("a")); assertTrue(commandLine.hasOption("b")); assertFalse(commandLine.hasOption("last")); } {code} One possible fix is to check that at least the first character of the option is a short option if all the other cases fail in {{isShortOption(...)}} like so: {code:java} 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) : token.substring(1, pos); if (options.hasShortOption(optName)) { return true; } return optName.length() > 0 && options.hasShortOption(String.valueOf(optName.charAt(0))); } {code}
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) : token.substring(1, pos); return options.hasShortOption(optName); // check for several concatenated short options }
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) : token.substring(1, pos); if (options.hasShortOption(optName)) { return true; } // check for several concatenated short options return optName.length() > 0 && options.hasShortOption(String.valueOf(optName.charAt(0))); }
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.builder("t1").hasArg().numberOfArgs(1).optionalArg(true).argName("t1_path").build(); Option TYPE2 = Option.builder("t2").hasArg().numberOfArgs(1).optionalArg(true).argName("t2_path").build(); Option LAST = Option.builder("last").hasArg(false).build(); Commands then look like "open -t1 path/to/my/db" or "open -t1 -last" If I use the now deprecated GnuParser, both commands work as expected. However, if I use the new DefaultParser, for the 2nd example, it thinks "-last" is the argument for -t1 rather than an option in its own right. I added the numberOfArgs(1) after reading a post on StackOverflow, but it made no difference in the behavior. Only switching back to the GnuParser seemed to work.
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); } else if (PatternOptionBuilder.NUMBER_VALUE == clazz) { return createNumber(str); } else if (PatternOptionBuilder.DATE_VALUE == clazz) { return createDate(str); } else if (PatternOptionBuilder.CLASS_VALUE == clazz) { return createClass(str); } else if (PatternOptionBuilder.FILE_VALUE == clazz) { return createFile(str); } else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) { return createFile(str); } else if (PatternOptionBuilder.FILES_VALUE == clazz) { return createFiles(str); } else if (PatternOptionBuilder.URL_VALUE == clazz) { return createURL(str); } else { return null; } }
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); } else if (PatternOptionBuilder.NUMBER_VALUE == clazz) { return createNumber(str); } else if (PatternOptionBuilder.DATE_VALUE == clazz) { return createDate(str); } else if (PatternOptionBuilder.CLASS_VALUE == clazz) { return createClass(str); } else if (PatternOptionBuilder.FILE_VALUE == clazz) { return createFile(str); } else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) { return openFile(str); } else if (PatternOptionBuilder.FILES_VALUE == clazz) { return createFiles(str); } else if (PatternOptionBuilder.URL_VALUE == clazz) { return createURL(str); } else { return null; } }
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, args); FileInputStream file = (FileInputStream) cline.getParsedOptionValue("f"); // it returns "File" object, without check File exist. I attach a solution for it: https://github.com/schaumb/commons-cli/commit/abfcc8211f529ab75f3b3edd4a827e484109eb0b
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 required options while (iter.hasNext()) { buff.append(iter.next()); } throw new MissingOptionException(buff.toString()); } }
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"); buff.append(requiredOptions.size() == 1 ? "" : "s"); buff.append(": "); // loop through the required options while (iter.hasNext()) { buff.append(iter.next()); } throw new MissingOptionException(buff.toString()); } }
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 results of the catch > block > (OK) > A command line with just "-target" prints out the results of the catch > block (OK) > A command line with just "-t foobar.com" prints out "processing selected > target: foobar.com" (OK) > A command line with just "-target foobar.com" prints out "processing > selected target: arget" (ERROR?) > > ====================================================================== > == > ======================= > private static final String OPTION_TARGET = "t"; > private static final String OPTION_TARGET_LONG = "target"; > // ... > Option generateTarget = new Option(OPTION_TARGET, > OPTION_TARGET_LONG, > true, > "Generate files for the specified > target machine"); > // ... > try { > parsedLine = parser.parse(cmdLineOpts, args); > } catch (ParseException pe) { > System.out.println("Invalid command: " + pe.getMessage() + > "\n"); > HelpFormatter hf = new HelpFormatter(); > hf.printHelp(USAGE, cmdLineOpts); > System.exit(-1); > } > > if (parsedLine.hasOption(OPTION_TARGET)) { > System.out.println("processing selected target: " + > parsedLine.getOptionValue(OPTION_TARGET)); > } It is a bug but it is due to well defined behaviour (so that makes me feel a little better about myself . To support special (well I call them special anyway) like -Dsystem.property=value we need to be able to examine the first character of an option. If the first character is itself defined as an Option then the remainder of the token is used as the value, e.g. 'D' is the token, it is an option so 'system.property=value' is the argument value for that option. This is the behaviour that we are seeing for your example. 't' is the token, it is an options so 'arget' is the argument value. I suppose a solution to this could be to have a way to specify properties for parsers. In this case 'posix.special.option == true' for turning on special options. I'll have a look into this and let you know. Just to keep track of this and to get you used to how we operate, can you log a bug in bugzilla for this. Thanks, -John K
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 (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; } }
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); } }
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 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.
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))).append(defaultNewLine); // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, nextLineTabStop); if (pos == -1) { sb.append(text); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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))).append(defaultNewLine); // all following lines must be padded with nextLineTabStop space // characters final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
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 help formatter to print it. The first line will be the correct length. The 2nd, 3rd, etc lines will all be too long. I don't have a patch (sorry) - but here is a corrected version of the method. I fixed it in two places - both were using "width + startPos" when they should have been using width. protected int findWrapPos(String text, int width, int startPos) { int pos = -1; // 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 pos+1; } else if ((width) >= text.length()) { return -1; } // look for the last whitespace character before startPos+width pos = width; char c; while ((pos >= startPos) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { --pos; } // if we found it - just return if (pos > startPos) { return pos; } // must look for the first whitespace chearacter after startPos // + width pos = startPos + width; while ((pos <= text.length()) && ((c = text.charAt(pos)) != ' ') && (c != '\n') && (c != '\r')) { ++pos; } return (pos == text.length()) ? (-1) : pos; }
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 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()); } }
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)); } }
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 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
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 create a new option for this, we assume that if the user // is removing globals, then it's OK to remove unused function args. // // See http://code.google.com/p/closure-compiler/issues/detail?id=253 Node function = fnScope.getRootNode(); Preconditions.checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { // The parameters object literal setters can not be removed. return; } Node argList = getFunctionArgList(function); boolean modifyCallers = modifyCallSites && callSiteOptimizer.canModifyCallers(function); if (!modifyCallers) { // Strip unreferenced args off the end of the function declaration. Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Var var = fnScope.getVar(lastArg.getString()); if (!referenced.contains(var)) { argList.removeChild(lastArg); compiler.reportCodeChange(); } else { break; } } } else { callSiteOptimizer.optimize(fnScope, referenced); } }
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 create a new option for this, we assume that if the user // is removing globals, then it's OK to remove unused function args. // // See http://code.google.com/p/closure-compiler/issues/detail?id=253 if (!removeGlobals) { return; } Node function = fnScope.getRootNode(); Preconditions.checkState(function.isFunction()); if (NodeUtil.isGetOrSetKey(function.getParent())) { // The parameters object literal setters can not be removed. return; } Node argList = getFunctionArgList(function); boolean modifyCallers = modifyCallSites && callSiteOptimizer.canModifyCallers(function); if (!modifyCallers) { // Strip unreferenced args off the end of the function declaration. Node lastArg; while ((lastArg = argList.getLastChild()) != null) { Var var = fnScope.getVar(lastArg.getString()); if (!referenced.contains(var)) { argList.removeChild(lastArg); compiler.reportCodeChange(); } else { break; } } } else { callSiteOptimizer.optimize(fnScope, referenced); } }
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 (foo.length); function foo (bar, baz) { return bar; } alert (foo.length); -------------------------------------- What is the expected output? function foo(a,b){return a}alert(foo.length); -------------------------------------- What do you see instead? function foo(a){return a}alert(foo.length); -------------------------------------- What version of the product are you using? On what operating system? I'm using the product from the web page http://closure-compiler.appspot.com/home I'm using Firefox 3.6.10 on Ubuntu 10.0.4 Please provide any additional information below. The function's length property is essential to many techniques, such as currying functions.
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 : 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.
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.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; }
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; }
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/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.
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); } removeDuplicateDeclarations(root); new PropogateConstantAnnotations(compiler, assertOnChange) .process(externs, root); }
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); }
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) { 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); } }
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); } }
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.extraAnnotationName); CompilationLevel level = flags.compilationLevel; level.setOptionsForCompilationLevel(options); if (flags.debug) { level.setDebugOptionsForCompilationLevel(options); } if (flags.useTypesForOptimization) { level.setTypeBasedOptimizationOptions(options); } if (flags.generateExports) { options.setGenerateExports(flags.generateExports); } WarningLevel wLevel = flags.warningLevel; wLevel.setOptionsForWarningLevel(options); for (FormattingOption formattingOption : flags.formatting) { formattingOption.applyToOptions(options); } options.closurePass = flags.processClosurePrimitives; options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level && flags.processJqueryPrimitives; options.angularPass = flags.angularPass; if (!flags.translationsFile.isEmpty()) { try { options.messageBundle = new XtbMessageBundle( new FileInputStream(flags.translationsFile), flags.translationsProject); } catch (IOException e) { throw new RuntimeException("Reading XTB file", e); } } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) { // In SIMPLE or WHITESPACE mode, if the user hasn't specified a // translations file, they might reasonably try to write their own // implementation of goog.getMsg that makes the substitution at // run-time. // // In ADVANCED mode, goog.getMsg is going to be renamed anyway, // so we might as well inline it. But shut off the i18n warnings, // because the user didn't really ask for i18n. options.messageBundle = new EmptyMessageBundle(); } return options; }
protected CompilerOptions createOptions() { CompilerOptions options = new CompilerOptions(); if (flags.processJqueryPrimitives) { options.setCodingConvention(new JqueryCodingConvention()); } else { options.setCodingConvention(new ClosureCodingConvention()); } options.setExtraAnnotationNames(flags.extraAnnotationName); CompilationLevel level = flags.compilationLevel; level.setOptionsForCompilationLevel(options); if (flags.debug) { level.setDebugOptionsForCompilationLevel(options); } if (flags.useTypesForOptimization) { level.setTypeBasedOptimizationOptions(options); } if (flags.generateExports) { options.setGenerateExports(flags.generateExports); } WarningLevel wLevel = flags.warningLevel; wLevel.setOptionsForWarningLevel(options); for (FormattingOption formattingOption : flags.formatting) { formattingOption.applyToOptions(options); } options.closurePass = flags.processClosurePrimitives; options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level && flags.processJqueryPrimitives; options.angularPass = flags.angularPass; if (!flags.translationsFile.isEmpty()) { try { options.messageBundle = new XtbMessageBundle( new FileInputStream(flags.translationsFile), flags.translationsProject); } catch (IOException e) { throw new RuntimeException("Reading XTB file", e); } } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) { // In SIMPLE or WHITESPACE mode, if the user hasn't specified a // translations file, they might reasonably try to write their own // implementation of goog.getMsg that makes the substitution at // run-time. // // In ADVANCED mode, goog.getMsg is going to be renamed anyway, // so we might as well inline it. But shut off the i18n warnings, // because the user didn't really ask for i18n. options.messageBundle = new EmptyMessageBundle(); options.setWarningLevel(JsMessageVisitor.MSG_CONVENTIONS, CheckLevel.OFF); } return options; }
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, MSG2_foo, etc.
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 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.
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.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); }
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); }
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 = 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!
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 - 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.
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 = 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; }
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; }
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); 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.
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.isExplicitlyProvided()) { unrecognizedRequires.add( new UnrecognizedRequire(n, ns, t.getSourceName())); } else { JSModule providedModule = provided.explicitModule; // This must be non-null, because there was an explicit provide. Preconditions.checkNotNull(providedModule); JSModule module = t.getModule(); if (moduleGraph != null && module != providedModule && !moduleGraph.dependsOn(module, providedModule)) { compiler.report( t.makeError(n, XMODULE_REQUIRE_ERROR, ns, providedModule.getName(), module.getName())); } } maybeAddToSymbolTable(left); maybeAddStringNodeToSymbolTable(arg); // Requires should be removed before further processing. // Some clients run closure pass multiple times, first with // the checks for broken requires turned off. In these cases, we // allow broken requires to be preserved by the first run to // let them be caught in the subsequent run. if (provided != null) { parent.detachFromParent(); compiler.reportCodeChange(); } } }
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.isExplicitlyProvided()) { unrecognizedRequires.add( new UnrecognizedRequire(n, ns, t.getSourceName())); } else { JSModule providedModule = provided.explicitModule; // This must be non-null, because there was an explicit provide. Preconditions.checkNotNull(providedModule); JSModule module = t.getModule(); if (moduleGraph != null && module != providedModule && !moduleGraph.dependsOn(module, providedModule)) { compiler.report( t.makeError(n, XMODULE_REQUIRE_ERROR, ns, providedModule.getName(), module.getName())); } } maybeAddToSymbolTable(left); maybeAddStringNodeToSymbolTable(arg); // Requires should be removed before further processing. // Some clients run closure pass multiple times, first with // the checks for broken requires turned off. In these cases, we // allow broken requires to be preserved by the first run to // let them be caught in the subsequent run. if (provided != null || requiresLevel.isOn()) { parent.detachFromParent(); compiler.reportCodeChange(); } } }
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 require calls must be left for further using/checking of the code! The related comment in the code confirms this. Nevertheless, the second condition (requiresLevel.isOn() -> see source code) is invalid and always causes removing of the requires when we want to check these requires. In any case, the method should not use the requiresLevel to decide if we need removing. The requiresLevel should be used to check if we need error reporting. The Solution Remove the condition. Please see the attached patch.
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()) { ObjectType objectType = getJSType(n.getFirstChild()).dereference(); if (objectType != null) { String propName = n.getLastChild().getString(); if (objectType.getConstructor() != null && objectType.getConstructor().isInterface()) { objectType = FunctionType.getTopDefiningInterface( objectType, propName); } else { // classes while (objectType != null && !objectType.hasOwnProperty(propName)) { objectType = objectType.getImplicitPrototype(); } } // Don't show complex function names or anonymous types. // Instead, try to get a human-readable type name. if (objectType != null && (objectType.getConstructor() != null || objectType.isFunctionPrototypeType())) { return objectType.toString() + "." + propName; } } } JSType type = getJSType(n); if (dereference) { ObjectType dereferenced = type.dereference(); if (dereferenced != null) { type = dereferenced; } } if (type.isFunctionPrototypeType() || (type.toObjectType() != null && type.toObjectType().getConstructor() != null)) { return type.toString(); } String qualifiedName = n.getQualifiedName(); if (qualifiedName != null) { return qualifiedName; } else if (type.isFunctionType()) { // Don't show complex function names. return "function"; } else { return type.toString(); } }
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() || (type.toObjectType() != null && type.toObjectType().getConstructor() != null)) { return type.toString(); } // 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()) { ObjectType objectType = getJSType(n.getFirstChild()).dereference(); if (objectType != null) { String propName = n.getLastChild().getString(); if (objectType.getConstructor() != null && objectType.getConstructor().isInterface()) { objectType = FunctionType.getTopDefiningInterface( objectType, propName); } else { // classes while (objectType != null && !objectType.hasOwnProperty(propName)) { objectType = objectType.getImplicitPrototype(); } } // Don't show complex function names or anonymous types. // Instead, try to get a human-readable type name. if (objectType != null && (objectType.getConstructor() != null || objectType.isFunctionPrototypeType())) { return objectType.toString() + "." + propName; } } } String qualifiedName = n.getQualifiedName(); if (qualifiedName != null) { return qualifiedName; } else if (type.isFunctionType()) { // Don't show complex function names. return "function"; } else { return type.toString(); } }
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, 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(), "")); } } } }
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(), "")); } } } }
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.bar; foo.foobar = new foobar; console.log(foo.foobar['bar1']);
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; 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)
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; } else if (block.isLoop) { return false; } } return true; }
boolean isAssignedOnceInLifetime() { Reference ref = getOneAndOnlyAssignment(); if (ref == null) { return false; } // Make sure this assignment is not in a loop. for (BasicBlock block = ref.getBasicBlock(); block != null; block = block.getParent()) { if (block.isFunction) { if (ref.getSymbol().getScope() != ref.scope) { return false; } break; } else if (block.isLoop) { return false; } } return true; }
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 called'; } } doStuff(); ...gets optimized to: var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b(); Notice how _uid gets optimized away and (uid!==_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from _uid. As an aside, replacing the declaration with "var _uid = +uid;" fixes it, as does adding an extra "uid = _uid" after "var _uid = uid".
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 License */ ^ 0 error(s), 1 warning(s) alert("foo"); If I take the suggestion and change the opening of the comment to '/**', everything is great. However, if I change it to '/*!', the warning goes away, but it doesn't preserve the comment either. I expect it to print the above warning, or preserve the comment. That it does neither when starting with "/*!" (and every other character I tried) is confusing. What version of the product are you using? On what operating system? Tested with my compilation of the "v20130603" tag: Closure Compiler (http://code.google.com/closure/compiler) Version: v20130603 Built on: 2013/07/07 15:04 And with the provided binary: Closure Compiler (http://code.google.com/closure/compiler) Version: v20130411-90-g4e19b4e Built on: 2013/06/03 12:07 I'm on Parabola GNU/Linux-libre with Java: java version "1.7.0_40" OpenJDK Runtime Environment (IcedTea 2.4.0) (ArchLinux build 7.u40_2.4.0-1-i686) OpenJDK Server VM (build 24.0-b40, mixed mode) Please provide any additional information below.
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)) { return false; } return true; }
private boolean isSafeReplacement(Node node, Node replacement) { // No checks are needed for simple names. if (node.isName()) { return true; } Preconditions.checkArgument(node.isGetProp()); while (node.isGetProp()) { node = node.getFirstChild(); } if (node.isName() && isNameAssignedTo(node.getString(), replacement)) { return false; } return true; }
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 compiler.jar --js test.js" 2. Compile the content of the attached file on http://closure-compiler.appspot.com/home 3. Compare the output, note how the following part is converted in the two cases: "var foreignObject = gfx.parentNode.parentNode; var parentContainer = foreignObject.parentNode.parentNode;" What is the expected output? What do you see instead? The Web UI converts the lines into: if(b){if(a=b.parentNode.parentNode,b=a.parentNode.parentNode,null!==b) The command line converts it into: var b=a=a.parentNode.parentNode; The Web UI results in correct code, the other results in code that tries to do "c.appendChild(b)" with c = b (c=a=a.parentNode.parentNode) What version of the product are you using? On what operating system? compiler.jar: v20130411-90-g4e19b4e Mac OSX 10.8.3 Java: java 1.6.0_45 Please provide any additional information below. We are also using the compiler form within our java code, with the same result. Web UI was called with: // ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS // @output_file_name default.js // ==/ClosureCompiler==
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); } // Keep track of the context in which eval is called. It is important // to distinguish between "(0, eval)()" and "eval()". if (first.isName() && "eval".equals(first.getString())) { first.putBooleanProp(Node.DIRECT_EVAL, true); } }
private void annotateCalls(Node n) { Preconditions.checkState(n.isCall()); // Keep track of of the "this" context of a call. A call without an // explicit "this" is a free call. Node first = n.getFirstChild(); // ignore cast nodes. while (first.isCast()) { first = first.getFirstChild(); } if (!NodeUtil.isGet(first)) { n.putBooleanProp(Node.FREE_CALL, true); } // Keep track of the context in which eval is called. It is important // to distinguish between "(0, eval)()" and "eval()". if (first.isName() && "eval".equals(first.getString())) { first.putBooleanProp(Node.DIRECT_EVAL, true); } }
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)("$version")); 2. Compare with this code: console.log( /** @type {!string} */ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable']( '$version' )) ) produces: 'use strict';console.log((new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")); Notice the (0,...) wrapping around the GetVariable function in the first example. This causes the call to fail in every browser (this code is IE-only but it's just for a minimal example). The second version produces a warning that the type of GetVariable could not be determined (I enabled type warnings), and it wouldn't be possible to define these in an externs file without making a horrible mess. This applies to all cases where functions are cast, but only causes problems (other than bloat) with plugins like this. It seems to serve no purpose whatsoever, so I assume it is a bug. Running on a mac, not sure what version but it reports Built on: 2013/02/12 17:00, so will have been downloaded about that time.
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.getFirstChild(); while(c != null) { traverse(c); Node next = c.getNext(); c = next; } visit(node); visits++; Preconditions.checkState(visits < 10000, "too many interations"); } while (shouldRetraverse(node)); exitNode(node); }
private void traverse(Node node) { // The goal here is to avoid retraversing // the entire AST to catch newly created opportunities. // So we track whether a "unit of code" has changed, // and revisit immediately. if (!shouldVisit(node)) { return; } int visits = 0; do { Node c = node.getFirstChild(); while(c != null) { Node next = c.getNext(); traverse(c); c = next; } visit(node); visits++; Preconditions.checkState(visits < 10000, "too many interations"); } while (shouldRetraverse(node)); exitNode(node); }
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: function () { return false; } } } What is the expected output? What do you see instead? We expect that true/false will be replaced for !0/!1, but it doesn't happend. function some_function() { var a, b; any_expression && (b = external_ref, a = function () { return b() }); return { method1: function () { a && a(); return true }, method2: function () { return false } } }; What version of the product are you using? On what operating system? This is output for latest official build. I also got the same output for 20120430, 20120305. But 20111117 is OK. Please provide any additional information below. Here is just one of example. I found too many non-replaced true/false in compiler output. Replacement non-replaced true/false to !1/!0 in conpiler output saves 1-2 kb for 850 kb js file.
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 as a variable. if (name.type == Name.Type.GET || name.type == Name.Type.SET) { continue; } if (name.globalSets == 1 && name.localSets == 0 && name.aliasingGets > 0) { // {@code name} meets condition (b). Find all of its local aliases // and try to inline them. List<Ref> refs = Lists.newArrayList(name.getRefs()); for (Ref ref : refs) { if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) { // {@code name} meets condition (c). Try to inline it. if (inlineAliasIfPossible(ref, namespace)) { name.removeRef(ref); } } } } // Check if {@code name} has any aliases left after the // local-alias-inlining above. if ((name.type == Name.Type.OBJECTLIT || name.type == Name.Type.FUNCTION) && name.aliasingGets == 0 && name.props != null) { // All of {@code name}'s children meet condition (a), so they can be // added to the worklist. workList.addAll(name.props); } } }
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 as a variable. if (name.type == Name.Type.GET || name.type == Name.Type.SET) { continue; } if (!name.inExterns && name.globalSets == 1 && name.localSets == 0 && name.aliasingGets > 0) { // {@code name} meets condition (b). Find all of its local aliases // and try to inline them. List<Ref> refs = Lists.newArrayList(name.getRefs()); for (Ref ref : refs) { if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) { // {@code name} meets condition (c). Try to inline it. if (inlineAliasIfPossible(ref, namespace)) { name.removeRef(ref); } } } } // Check if {@code name} has any aliases left after the // local-alias-inlining above. if ((name.type == Name.Type.OBJECTLIT || name.type == Name.Type.FUNCTION) && name.aliasingGets == 0 && name.props != null) { // All of {@code name}'s children meet condition (a), so they can be // added to the worklist. workList.addAll(name.props); } } }
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 function () { setTimeout(function() { alert(arguments); }, 0); } } arguments should not be collapsed.
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 true; }
public static boolean isJSIdentifier(String s) { int length = s.length(); if (length == 0 || Character.isIdentifierIgnorable(s.charAt(0)) || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < length; i++) { if (Character.isIdentifierIgnorable(s.charAt(i)) || !Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; }
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 input. However, the compiler converts the string \u0004 to the respective unicode character, and the output is: var test={ab:"c"}; // unicode character between a and b can not be displayed here What version of the product are you using? On what operating system? newest current snapshot on multiple os (OSX/linux) Please provide any additional information below.
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 or DO. return (n.getType() == Token.FUNCTION || n.getType() == Token.DO); }
private boolean isOneExactlyFunctionOrDo(Node n) { if (n.getType() == Token.LABEL) { Node labeledStatement = n.getLastChild(); if (labeledStatement.getType() != Token.BLOCK) { return isOneExactlyFunctionOrDo(labeledStatement); } else { // For labels with block children, we need to ensure that a // labeled FUNCTION or DO isn't generated when extraneous BLOCKs // are skipped. if (getNonEmptyChildCount(n, 2) == 1) { return isOneExactlyFunctionOrDo(getFirstNonEmptyChild(n)); } else { // Either a empty statement or an block with more than one child, // way it isn't a FUNCTION or DO. return false; } } } else { return (n.getType() == Token.FUNCTION || n.getType() == Token.DO); } }
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 the expected output? What do you see instead? The generated code produced is : var a=0;do b:do{a++;break b}while(0);while(0);console.log(a); Which works on all browsers except IE (Looks like IE doesn't like the missing brackets just after the first do instruction). What version of the product are you using? On what operating system? I am using the version of Jun 16 (latest) on ubuntu 10 Please provide any additional information below. Strangely, this bug doesn't happen when I use PRETTY_PRINT formatting option.
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); case FALSE: case UNKNOWN: return new TypePair(this, that); } // switch case is exhaustive throw new IllegalStateException(); }
public TypePair getTypesUnderInequality(JSType that) { // unions types if (that instanceof UnionType) { TypePair p = that.getTypesUnderInequality(this); return new TypePair(p.typeB, p.typeA); } // other types switch (this.testForEquality(that)) { case TRUE: JSType noType = getNativeType(JSTypeNative.NO_TYPE); return new TypePair(noType, noType); case FALSE: case UNKNOWN: return new TypePair(this, that); } // switch case is exhaustive throw new IllegalStateException(); }
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 output? What do you see instead? JSC_DETERMINISTIC_TEST: condition always evaluates to false left : undefined right: undefined at line 6 character 6 if (x != undefined) { g(x); } ^ JSC_TYPE_MISMATCH: actual parameter 1 of g does not match formal parameter found : undefined required: string at line 6 character 24 if (x != undefined) { g(x); } ^ the second warning is bogus.
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 non-side-effect free // function. if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) { return true; } if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) { return true; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) { return true; } } return false; }
public boolean apply(Node n) { // When the node is null it means, we reached the implicit return // where the function returns (possibly without an return statement) if (n == null) { return false; } // TODO(user): We only care about calls to functions that // passes one of the dependent variable to a non-side-effect free // function. if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) { return true; } if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) { return true; } if (n.isDelProp()) { return true; } for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) { return true; } } return false; }
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' ) ); // 'value' console.log( 'key' in customData ); // false // Compiled version: var customData={key:"value"};function testRemoveKey(b){var a=customData,c=a&&a[b];a&&delete a[b];return a&&b in a?c:null}console.log(testRemoveKey("key"));console.log("key"in customData); // null // false "b in a" is executed after "delete a[b]" what obviously doesn't make sense in this case. Reproducible on: http://closure-compiler.appspot.com/home and in "Version: 20120430 (revision 1918) Built on: 2012/04/30 18:02"
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.getType() == Token.NAME) { return; } defineDeclaredFunction(n, parent); break; case Token.CATCH: defineCatch(n, parent); break; case Token.VAR: defineVar(n, parent); break; } }
@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} 3. Now compile the code with ns.a defined within an anonymous function, like so: var ns = {}; (function() { /** @param {string=} b */ ns.a = function(b) {} })(); function d() { ns.a(); ns.a(123); } 4. Observe that a warning is emitted for calling ns.a with 0 parameters, and not for the type error, as though the @param declaration were ignored. What version of the product are you using? On what operating system? r15 Please provide any additional information below. This sort of module pattern is common enough that it strikes me as worth supporting. One last note to make matters stranger: if the calling code isn't itself within a function, no warnings are emitted at all: var ns = {}; (function() { /** @param {string=} b */ ns.a = function(b) {} })(); ns.a(); ns.a(123);
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.getString()); } } for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { findCalledFunctions(c, changed); } }
private void findCalledFunctions( Node node, Set<String> changed) { Preconditions.checkArgument(changed != null); // For each referenced function, add a new reference if (node.getType() == Token.NAME) { if (isCandidateUsage(node)) { changed.add(node.getString()); } } for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { findCalledFunctions(c, changed); } }
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 the function declaration but NOT changing the call to the function on line 76.
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 complex expressions to index into // arrays, or strings to index into array methods. return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node elem = left.getFirstChild(); for (int i = 0; elem != null && i < intIndex; i++) { elem = elem.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.getType() == Token.EMPTY) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } // Replace the entire GETELEM with the value n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
private Node tryFoldArrayAccess(Node n, Node left, Node right) { Node parent = n.getParent(); // If GETPROP/GETELEM is used as assignment target the array literal is // acting as a temporary we can't fold it here: // "[][0] += 1" if (isAssignmentTarget(n)) { return n; } if (right.getType() != Token.NUMBER) { // Sometimes people like to use complex expressions to index into // arrays, or strings to index into array methods. return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node elem = left.getFirstChild(); for (int i = 0; elem != null && i < intIndex; i++) { elem = elem.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.getType() == Token.EMPTY) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } // Replace the entire GETELEM with the value n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
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','19','16','21','18','16','20','17','17','21','17']; The error: JSC_INDEX_OUT_OF_BOUNDS_ERROR: Array index out of bounds: NUMBER 11.0 2 [sourcename: Input_0] : number at line 2 character 4 What version of the product are you using? On what operating system? The online version on 201.07.27
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({}); // // We want to modify the object literal to match the constraint, by // taking any each property on the record and trying to match // properties on this object. if (constraint.isRecordType()) { matchRecordTypeConstraint(constraint.toObjectType()); } }
public void matchConstraint(JSType constraint) { // We only want to match constraints on anonymous types. if (hasReferenceName()) { return; } // Handle the case where the constraint object is a record type. // // param constraint {{prop: (number|undefined)}} // function f(constraint) {} // f({}); // // We want to modify the object literal to match the constraint, by // taking any each property on the record and trying to match // properties on this object. if (constraint.isRecordType()) { matchRecordTypeConstraint(constraint.toObjectType()); } else if (constraint.isUnionType()) { for (JSType alt : constraint.toMaybeUnionType().getAlternates()) { if (alt.isRecordType()) { matchRecordTypeConstraint(alt.toObjectType()); } } } }
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); } else { window.console.log(record.prop); } } func({prop: 'a'}); func2({prop: 'a'}); errors with: ERROR - actual parameter 1 of func2 does not match formal parameter found : {prop: string} required: (string|{prop: string, prop2: (string|undefined)}) func2({prop: 'a'}); the type of the record input to func and func2 are identical but the parameters to func2 allow some other type.
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; } boolean inferred = true; if (info != null) { inferred = !(info.hasType() || info.hasEnumParameterType() || (isConstantSymbol(info, n) && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred && rhsValue != null && rhsValue.isFunction()) { if (info != null) { return false; } else if (!scope.isDeclared(qName, false) && n.isUnscopedQualifiedName()) { // Check if this is in a conditional block. // Functions assigned in conditional blocks are inferred. for (Node current = n.getParent(); !(current.isScript() || current.isFunction()); current = current.getParent()) { if (NodeUtil.isControlStructure(current)) { return true; } } // Check if this is assigned in an inner scope. // Functions assigned in inner scopes are inferred. AstFunctionContents contents = getFunctionAnalysisResults(scope.getRootNode()); if (contents == null || !contents.getEscapedQualifiedNames().contains(qName)) { return false; } } } return inferred; }
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 = qName.substring(0, qName.lastIndexOf(".prototype")); Var slot = scope.getSlot(className); JSType classType = slot == null ? null : slot.getType(); if (classType != null && (classType.isConstructor() || classType.isInterface())) { return false; } } boolean inferred = true; if (info != null) { inferred = !(info.hasType() || info.hasEnumParameterType() || (isConstantSymbol(info, n) && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred && rhsValue != null && rhsValue.isFunction()) { if (info != null) { return false; } else if (!scope.isDeclared(qName, false) && n.isUnscopedQualifiedName()) { // Check if this is in a conditional block. // Functions assigned in conditional blocks are inferred. for (Node current = n.getParent(); !(current.isScript() || current.isFunction()); current = current.getParent()) { if (NodeUtil.isControlStructure(current)) { return true; } } // Check if this is assigned in an inner scope. // Functions assigned in inner scopes are inferred. AstFunctionContents contents = getFunctionAnalysisResults(scope.getRootNode()); if (contents == null || !contents.getEscapedQualifiedNames().contains(qName)) { return false; } } } return inferred; }
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: WARNING - assignment to property prototype of Object found : function (): undefined required: string a.prototype = function(){}; ^
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 optimizations // // We can't do this in the general case, because String(a) has // slightly different semantics than '' + (a). See // http://code.google.com/p/closure-compiler/issues/detail?id=759 Node value = callTarget.getNext(); if (value != null) { Node addition = IR.add( IR.string("").srcref(callTarget), value.detachFromParent()); n.getParent().replaceChild(n, addition); reportCodeChange(); return addition; } } return n; }
private Node tryFoldSimpleFunctionCall(Node n) { Preconditions.checkState(n.isCall()); Node callTarget = n.getFirstChild(); if (callTarget != null && callTarget.isName() && callTarget.getString().equals("String")) { // Fold String(a) to '' + (a) on immutable literals, // which allows further optimizations // // We can't do this in the general case, because String(a) has // slightly different semantics than '' + (a). See // http://code.google.com/p/closure-compiler/issues/detail?id=759 Node value = callTarget.getNext(); if (value != null && value.getNext() == null && NodeUtil.isImmutableValue(value)) { Node addition = IR.add( IR.string("").srcref(callTarget), value.detachFromParent()); n.getParent().replaceChild(n, addition); reportCodeChange(); return addition; } } return n; }
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://closure-compiler.appspot.com/ as well). Please provide any additional information below. The compiler optimizes String(x) calls by replacing them with x + ''. This is correct in most cases, but incorrect in corner cases like the one mentioned above.
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()) { // Sometimes people like to use complex expressions to index into // arrays, or strings to index into array methods. return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node current = left.getFirstChild(); Node elem = null; for (int i = 0; current != null && i < intIndex; i++) { elem = current; current = current.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.isEmpty()) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } // Replace the entire GETELEM with the value n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
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()) { // Sometimes people like to use complex expressions to index into // arrays, or strings to index into array methods. return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node current = left.getFirstChild(); Node elem = null; for (int i = 0; current != null; i++) { if (i != intIndex) { if (mayHaveSideEffects(current)) { return n; } } else { elem = current; } current = current.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.isEmpty()) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } // Replace the entire GETELEM with the value n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
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 transform it into: console.log((console.log("hello"), "world!")); Instead, the program is transformed into: console.log("world!"); What version of the product are you using? On what operating system? Revision 2022. Ubuntu 12.04. Please provide any additional information below. tryFoldArrayAccess in com.google.javascript.jscomp.PeepholeFoldConstants should check whether every array element that is not going to be preserved has no side effects.
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.getString(); Var aliasVar = scope.getVar(name); aliases.put(name, aliasVar); String qualifiedName = aliasVar.getInitialValue().getQualifiedName(); transformation.addAlias(name, qualifiedName); // Bleeding functions already get a BAD_PARAMETERS error, so just // do nothing. // Parameters of the scope function also get a BAD_PARAMETERS // error. } else { // TODO(robbyw): Support using locals for private variables. report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString()); } } } }
private void findAliases(NodeTraversal t) { Scope scope = t.getScope(); for (Var v : scope.getVarIterable()) { Node n = v.getNode(); int type = n.getType(); Node parent = n.getParent(); if (parent.isVar() && n.hasChildren() && n.getFirstChild().isQualifiedName()) { String name = n.getString(); Var aliasVar = scope.getVar(name); aliases.put(name, aliasVar); String qualifiedName = aliasVar.getInitialValue().getQualifiedName(); transformation.addAlias(name, qualifiedName); } else if (v.isBleedingFunction()) { // Bleeding functions already get a BAD_PARAMETERS error, so just // do nothing. } else if (parent.getType() == Token.LP) { // Parameters of the scope function also get a BAD_PARAMETERS // error. } else { // TODO(robbyw): Support using locals for private variables. report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString()); } } }
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(); if (constructorType.isUnknownType()) { type = getNativeType(UNKNOWN_TYPE); } else { FunctionType ct = constructorType.toMaybeFunctionType(); if (ct == null && constructorType instanceof FunctionType) { // If constructorType is a NoObjectType, then toMaybeFunctionType will // return null. But NoObjectType implements the FunctionType // interface, precisely because it can validly construct objects. ct = (FunctionType) constructorType; } if (ct != null && ct.isConstructor()) { type = ct.getInstanceType(); } } } n.setJSType(type); for (Node arg = constructor.getNext(); arg != null; arg = arg.getNext()) { scope = traverse(arg, scope); } return scope; }
private FlowScope traverseNew(Node n, FlowScope scope) { scope = traverseChildren(n, scope); Node constructor = n.getFirstChild(); JSType constructorType = constructor.getJSType(); JSType type = null; if (constructorType != null) { constructorType = constructorType.restrictByNotNullOrUndefined(); if (constructorType.isUnknownType()) { type = getNativeType(UNKNOWN_TYPE); } else { FunctionType ct = constructorType.toMaybeFunctionType(); if (ct == null && constructorType instanceof FunctionType) { // If constructorType is a NoObjectType, then toMaybeFunctionType will // return null. But NoObjectType implements the FunctionType // interface, precisely because it can validly construct objects. ct = (FunctionType) constructorType; } if (ct != null && ct.isConstructor()) { type = ct.getInstanceType(); backwardsInferenceFromCallSite(n, ct); } } } n.setJSType(type); return scope; }
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(parry) { if (parry.prop2 && parry.prop2 < 5) alert('alright!'); alert(parry.prop1); } callz({prop1: 'hi'}); However, the following does not: /** * @param {{prop1: string, prop2: (number|undefined)}} parry * @constructor */ function callz(parry) { if (parry.prop2 && parry.prop2 < 5) alert('alright!'); alert(parry.prop1); } new callz({prop1: 'hi'}); /Users/dolapo/Desktop/reverse.js:10: ERROR - actual parameter 1 of callz does not match formal parameter found : {prop1: string} required: {prop1: string, prop2: (number|undefined)} new callz({prop1: 'hi'}); Thanks!
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 startLineno = stream.getLineno(); int startCharno = stream.getCharno() + 1; // Read the content from the first line. String line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = line.trim(); } StringBuilder builder = new StringBuilder(); builder.append(line); state = State.SEARCHING_ANNOTATION; token = next(); boolean ignoreStar = false; // Track the start of the line to count whitespace that // the tokenizer skipped. Because this case is rare, it's easier // to do this here than in the tokenizer. do { switch (token) { case STAR: if (ignoreStar) { // Mark the position after the star as the new start of the line. } else { // The star is part of the comment. if (builder.length() > 0) { builder.append(' '); } builder.append('*'); } token = next(); continue; case EOL: if (option != WhitespaceOption.SINGLE_LINE) { builder.append("\n"); } ignoreStar = true; token = next(); continue; default: ignoreStar = false; state = State.SEARCHING_ANNOTATION; // All tokens must be separated by a space. if (token == JsDocToken.EOC || token == JsDocToken.EOF || // When we're capturing a license block, annotations // in the block are ok. (token == JsDocToken.ANNOTATION && option != WhitespaceOption.PRESERVE)) { String multilineText = builder.toString(); if (option != WhitespaceOption.PRESERVE) { multilineText = multilineText.trim(); } int endLineno = stream.getLineno(); int endCharno = stream.getCharno(); if (multilineText.length() > 0) { jsdocBuilder.markText(multilineText, startLineno, startCharno, endLineno, endCharno); } return new ExtractionInfo(multilineText, token); } if (builder.length() > 0) { builder.append(' '); } builder.append(toString(token)); line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = trimEnd(line); } builder.append(line); token = next(); } } while (true); }
private ExtractionInfo extractMultilineTextualBlock(JsDocToken token, WhitespaceOption option) { if (token == JsDocToken.EOC || token == JsDocToken.EOL || token == JsDocToken.EOF) { return new ExtractionInfo("", token); } stream.update(); int startLineno = stream.getLineno(); int startCharno = stream.getCharno() + 1; // Read the content from the first line. String line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = line.trim(); } StringBuilder builder = new StringBuilder(); builder.append(line); state = State.SEARCHING_ANNOTATION; token = next(); boolean ignoreStar = false; // Track the start of the line to count whitespace that // the tokenizer skipped. Because this case is rare, it's easier // to do this here than in the tokenizer. int lineStartChar = -1; do { switch (token) { case STAR: if (ignoreStar) { // Mark the position after the star as the new start of the line. lineStartChar = stream.getCharno() + 1; } else { // The star is part of the comment. if (builder.length() > 0) { builder.append(' '); } builder.append('*'); } token = next(); continue; case EOL: if (option != WhitespaceOption.SINGLE_LINE) { builder.append("\n"); } ignoreStar = true; lineStartChar = 0; token = next(); continue; default: ignoreStar = false; state = State.SEARCHING_ANNOTATION; boolean isEOC = token == JsDocToken.EOC; if (!isEOC) { if (lineStartChar != -1 && option == WhitespaceOption.PRESERVE) { int numSpaces = stream.getCharno() - lineStartChar; for (int i = 0; i < numSpaces; i++) { builder.append(' '); } lineStartChar = -1; } else if (builder.length() > 0) { // All tokens must be separated by a space. builder.append(' '); } } if (token == JsDocToken.EOC || token == JsDocToken.EOF || // When we're capturing a license block, annotations // in the block are ok. (token == JsDocToken.ANNOTATION && option != WhitespaceOption.PRESERVE)) { String multilineText = builder.toString(); if (option != WhitespaceOption.PRESERVE) { multilineText = multilineText.trim(); } int endLineno = stream.getLineno(); int endCharno = stream.getCharno(); if (multilineText.length() > 0) { jsdocBuilder.markText(multilineText, startLineno, startCharno, endLineno, endCharno); } return new ExtractionInfo(multilineText, token); } builder.append(toString(token)); line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = trimEnd(line); } builder.append(line); token = next(); } } while (true); }
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 verison. Please provide any additional information below.
1,329
1,429
End of preview. Expand in Data Studio

Dataset Summary

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.

Supported Tasks

  • Program Repair: Fixing bugs in Java functions
  • Code Generation: Generating correct implementations from buggy code

Dataset Structure

Each row contains:

  • task_id: Unique identifier for the task (in format: project_name-bug_id)
  • buggy_code: The buggy implementation
  • fixed_code: The correct implementation
  • file_path: Original file path in the Defects4J repository
  • issue_title: Title of the bug
  • issue_description: Description of the bug
  • start_line: Start line of the buggy function
  • end_line: End line of the buggy function

Source Data

This 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.

Citation

@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.},
}
Downloads last month
71

Collection including barty/D4J-Repair