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
Closure-33
public void matchConstraint(ObjectType constraintObj) { // We only want to match contraints on anonymous types. // Handle the case where the constraint object is a record type. // // param constraintObj {{prop: (number|undefined)}} // function f(constraintObj) {} // 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 (constraintObj.isRecordType()) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!hasProperty(prop)) { typeToInfer = getNativeType(JSTypeNative.VOID_TYPE) .getLeastSupertype(propType); } defineInferredProperty(prop, typeToInfer, null); } } } }
public void matchConstraint(ObjectType constraintObj) { // We only want to match contraints on anonymous types. if (hasReferenceName()) { return; } // Handle the case where the constraint object is a record type. // // param constraintObj {{prop: (number|undefined)}} // function f(constraintObj) {} // 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 (constraintObj.isRecordType()) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!hasProperty(prop)) { typeToInfer = getNativeType(JSTypeNative.VOID_TYPE) .getLeastSupertype(propType); } defineInferredProperty(prop, typeToInfer, null); } } } }
src/com/google/javascript/rhino/jstype/PrototypeObjectType.java
weird object literal invalid property error on unrelated object prototype
Apologies in advance for the convoluted repro case and the vague summary. Compile the following code (attached as repro.js) with: java -jar build/compiler.jar --compilation_level=ADVANCED_OPTIMIZATIONS --jscomp_error=accessControls --jscomp_error=checkTypes --jscomp_error=checkVars --js repro.js * /** * @param {{text: string}} opt_data * @return {string} */ function temp1(opt_data) { return opt_data.text; } /** * @param {{activity: (boolean|number|string|null|Object)}} opt_data * @return {string} */ function temp2(opt_data) { /** @notypecheck */ function __inner() { return temp1(opt_data.activity); } return __inner(); } /** * @param {{n: number, text: string, b: boolean}} opt_data * @return {string} */ function temp3(opt_data) { return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.'; } function callee() { var output = temp3({ n: 0, text: 'a string', b: true }) alert(output); } callee(); yields: repro.js:30: ERROR - actual parameter 1 of temp3 does not match formal parameter found : {b: boolean, n: number, text: (string|undefined)} required: {b: boolean, n: number, text: string} var output = temp3({ It seems like temp3 is actually being called with the right type {b: boolean, n: number, text: string} though it seems to think that text is a (string|undefined) This seems to happen because of the seemingly unrelated code in functions temp1 and temp2. If I change the name of the text property (as in repro3.js) it works. Additionally, if I fix the type of the activity property in the record type of temp2 it works (as in repro2.js) This comes up in our codebase in some situations where we don't have type info for all the objects being passed into a function. It's always a tricky one to find because it reports an error at a location that looks correct. * it also fails with SIMPLE_OPTIMIZATIONS
555
580
Closure-35
private void inferPropertyTypesToMatchConstraint( JSType type, JSType constraint) { if (type == null || constraint == null) { return; } ObjectType constraintObj = ObjectType.cast(constraint.restrictByNotNullOrUndefined()); if (constraintObj != null && constraintObj.isRecordType()) { ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined()); if (objType != null) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!objType.isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!objType.hasProperty(prop)) { typeToInfer = getNativeType(VOID_TYPE).getLeastSupertype(propType); } objType.defineInferredProperty(prop, typeToInfer, null); } } } } }
private void inferPropertyTypesToMatchConstraint( JSType type, JSType constraint) { if (type == null || constraint == null) { return; } ObjectType constraintObj = ObjectType.cast(constraint.restrictByNotNullOrUndefined()); if (constraintObj != null) { type.matchConstraint(constraintObj); } }
src/com/google/javascript/jscomp/TypeInference.java
assignment to object in conditional causes type error on function w/ record type return type
slightly dodgy code :) /** @returns {{prop1: (Object|undefined), prop2: (string|undefined), prop3: (string|undefined)}} */ function func(a, b) { var results; if (a) { results = {}; results.prop1 = {a: 3}; } if (b) { results = results || {}; results.prop2 = 'prop2'; } else { results = results || {}; results.prop3 = 'prop3'; } return results; } results in this error: JSC_TYPE_MISMATCH: inconsistent return type found : ({prop1: {a: number}}|{}) required: {prop1: (Object|null|undefined), prop2: (string|undefined), prop3: (string|undefined)} at line 18 character 7 return results; defining results on the first line on the function causes it the world. the still dodgy, but slightly less so, use of this is if the function return type were that record type|undefined and not all branches were guaranteed to be executed.
1,113
1,137
Closure-36
private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } // If the value is read more than once, skip it. // VAR declarations and EXPR_RESULT don't need the value, but other // ASSIGN expressions parents do. if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } // Be very conservative and do no cross control structures or // scope boundaries if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } // Do not inline into a call node. This would change // the context in which it was being called. For example, // var a = b.c; // a(); // should not be inlined, because it calls a in the context of b // rather than the context of the window. // var a = b.c; // f(a) // is ok. Node value = initialization.getAssignedValue(); Preconditions.checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); // Bug 2388531: Don't inline subclass definitions into class defining // calls as this confused class removing logic. SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } // issue 668: Don't inline singleton getter methods // calls as this confused class removing logic. } } return canMoveAggressively(value) || canMoveModerately(initialization, reference); }
private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } // If the value is read more than once, skip it. // VAR declarations and EXPR_RESULT don't need the value, but other // ASSIGN expressions parents do. if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } // Be very conservative and do no cross control structures or // scope boundaries if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } // Do not inline into a call node. This would change // the context in which it was being called. For example, // var a = b.c; // a(); // should not be inlined, because it calls a in the context of b // rather than the context of the window. // var a = b.c; // f(a) // is ok. Node value = initialization.getAssignedValue(); Preconditions.checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); // Bug 2388531: Don't inline subclass definitions into class defining // calls as this confused class removing logic. SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } // issue 668: Don't inline singleton getter methods // calls as this confused class removing logic. if (convention.getSingletonGetterClassName(callNode) != null) { return false; } } } return canMoveAggressively(value) || canMoveModerately(initialization, reference); }
src/com/google/javascript/jscomp/InlineVariables.java
goog.addSingletonGetter prevents unused class removal
What steps will reproduce the problem? // ==ClosureCompiler== // @compilation_level ADVANCED_OPTIMIZATIONS // @output_file_name default.js // @use_closure_library true // @formatting pretty_print,print_input_delimiter // @warning_level VERBOSE // @debug true // ==/ClosureCompiler== goog.provide('foo'); var foo = function() { this.values = []; }; goog.addSingletonGetter(foo); foo.prototype.add = function(value) {this.values.push(value)}; What is the expected output? What do you see instead? Expect: The code is completely removed. Instead: (function($ctor$$) { $ctor$$.$getInstance$ = function $$ctor$$$$getInstance$$() { return $ctor$$.$instance_$ || ($ctor$$.$instance_$ = new $ctor$$) } })(function() { }); What version of the product are you using? On what operating system? http://closure-compiler.appspot.com on Feb 28, 2012 Please provide any additional information below.
519
580
Closure-38
void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); boolean negativeZero = isNegativeZero(x); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x && !negativeZero) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); boolean negativeZero = isNegativeZero(x); if ((x < 0 || negativeZero) && prev == '-') { add(" "); } if ((long) x == x && !negativeZero) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
src/com/google/javascript/jscomp/CodeConsumer.java
Identifier minus a negative number needs a space between the "-"s
What steps will reproduce the problem? 1. Compile the attached file with java -jar build/compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js bulletfail.js --js_output_file cc.js 2. Try to run the file in a JS engine, for example node cc.js What is the expected output? What do you see instead? The file does not parse properly, because it contains g--0.0 This is subtraction of a negative number, but it looks like JS engines interpret it as decrementing g, and then fail to parse the 0.0. (g- -0.0, with a space, would parse ok.) What version of the product are you using? On what operating system? Trunk closure compiler on Ubuntu Please provide any additional information below.
240
267
Closure-39
String toStringHelper(boolean forAnnotations) { if (hasReferenceName()) { return getReferenceName(); } else if (prettyPrint) { // Don't pretty print recursively. prettyPrint = false; // Use a tree set so that the properties are sorted. Set<String> propertyNames = Sets.newTreeSet(); for (ObjectType current = this; current != null && !current.isNativeObjectType() && propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES; current = current.getImplicitPrototype()) { propertyNames.addAll(current.getOwnPropertyNames()); } StringBuilder sb = new StringBuilder(); sb.append("{"); int i = 0; for (String property : propertyNames) { if (i > 0) { sb.append(", "); } sb.append(property); sb.append(": "); sb.append(getPropertyType(property).toString()); ++i; if (i == MAX_PRETTY_PRINTED_PROPERTIES) { sb.append(", ..."); break; } } sb.append("}"); prettyPrint = true; return sb.toString(); } else { return "{...}"; } }
String toStringHelper(boolean forAnnotations) { if (hasReferenceName()) { return getReferenceName(); } else if (prettyPrint) { // Don't pretty print recursively. prettyPrint = false; // Use a tree set so that the properties are sorted. Set<String> propertyNames = Sets.newTreeSet(); for (ObjectType current = this; current != null && !current.isNativeObjectType() && propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES; current = current.getImplicitPrototype()) { propertyNames.addAll(current.getOwnPropertyNames()); } StringBuilder sb = new StringBuilder(); sb.append("{"); int i = 0; for (String property : propertyNames) { if (i > 0) { sb.append(", "); } sb.append(property); sb.append(": "); sb.append(getPropertyType(property).toStringHelper(forAnnotations)); ++i; if (!forAnnotations && i == MAX_PRETTY_PRINTED_PROPERTIES) { sb.append(", ..."); break; } } sb.append("}"); prettyPrint = true; return sb.toString(); } else { return forAnnotations ? "?" : "{...}"; } }
src/com/google/javascript/rhino/jstype/PrototypeObjectType.java
externExport with @typedef can generate invalid externs
What steps will reproduce the problem? 1. Create a file that has a @typedef and code referencing the type def above and below the typedef declaration. 2. Run the closure compiler and grab the externExport string stored on the last result for review. 3. I have attached both source and output files displaying the issue. What is the expected output? What do you see instead? The code above the @typedef references the aliased name of the @typedef as expected however the code below the @typedef tries embedding the body of the @typedef and ends up truncating it if the length is too long with a "...". This throws bad type errors when compiling against this extern. What is odd is this only seems to be the case when the parameter with the type is optional. When neither are optional it embeds the types, which is not a big deal, except when types are long; they get truncated and throw errors. What version of the product are you using? On what operating system? plovr built from revision 3103:d6db24beeb7f Revision numbers for embedded Closure Tools: Closure Library: 1374 Closure Compiler: 1559 Closure Templates: 23 Please provide any additional information below.
353
396
Closure-4
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) { // TODO(user): Investigate whether it is really necessary to keep two // different mechanisms for resolving named types, and if so, which order // makes more sense. Now, resolution via registry is first in order to // avoid triggering the warnings built into the resolution via properties. boolean resolved = resolveViaRegistry(t, enclosing); if (detectImplicitPrototypeCycle()) { handleTypeCycle(t); } if (resolved) { super.resolveInternal(t, enclosing); finishPropertyContinuations(); return registry.isLastGeneration() ? getReferencedType() : this; } resolveViaProperties(t, enclosing); if (detectImplicitPrototypeCycle()) { handleTypeCycle(t); } super.resolveInternal(t, enclosing); if (isResolved()) { finishPropertyContinuations(); } return registry.isLastGeneration() ? getReferencedType() : this; }
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) { // TODO(user): Investigate whether it is really necessary to keep two // different mechanisms for resolving named types, and if so, which order // makes more sense. Now, resolution via registry is first in order to // avoid triggering the warnings built into the resolution via properties. boolean resolved = resolveViaRegistry(t, enclosing); if (detectInheritanceCycle()) { handleTypeCycle(t); } if (resolved) { super.resolveInternal(t, enclosing); finishPropertyContinuations(); return registry.isLastGeneration() ? getReferencedType() : this; } resolveViaProperties(t, enclosing); if (detectInheritanceCycle()) { handleTypeCycle(t); } super.resolveInternal(t, enclosing); if (isResolved()) { finishPropertyContinuations(); } return registry.isLastGeneration() ? getReferencedType() : this; }
src/com/google/javascript/rhino/jstype/NamedType.java
Converting from an interface type to a constructor which @implements itself causes stack overflow.
// Options: --externs externs/es3.js --property_renaming OFF --variable_renaming OFF --jscomp_warning=checkTypes --js=t.js // File: t.js /** * @interface */ var OtherType = function() {} /** * @implements {MyType} * @constructor */ var MyType = function() {} /** * @type {MyType} */ var x = /** @type {!OtherType} */ (new Object()); Get Infinite recursion in: PrototypeObjectType.isSubtype @ 350 Options: - prevent cycles in the inheritance/implements graph - detect cycles after they are created and exit compilation before any subsequent passes run - detect and remove cycles after they are created but before any subsequent passes run - make every subsequent pass robust against cycles in that graph
184
212
Closure-40
public void visit(NodeTraversal t, Node n, Node parent) { // Record global variable and function declarations if (t.inGlobalScope()) { if (NodeUtil.isVarDeclaration(n)) { NameInformation ns = createNameInformation(t, n, parent); Preconditions.checkNotNull(ns); recordSet(ns.name, n); } else if (NodeUtil.isFunctionDeclaration(n)) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { JsName nameInfo = getName(nameNode.getString(), true); recordSet(nameInfo.name, nameNode); } } else if (NodeUtil.isObjectLitKey(n, parent)) { NameInformation ns = createNameInformation(t, n, parent); if (ns != null) { recordSet(ns.name, n); } } } // Record assignments and call sites if (n.isAssign()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { if (ns.isPrototype) { recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n); } else { recordSet(ns.name, nameNode); } } } else if (n.isCall()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null && ns.onlyAffectsClassDef) { JsName name = getName(ns.name, false); if (name != null) { refNodes.add(new ClassDefiningFunctionNode( name, n, parent, parent.getParent())); } } } }
public void visit(NodeTraversal t, Node n, Node parent) { // Record global variable and function declarations if (t.inGlobalScope()) { if (NodeUtil.isVarDeclaration(n)) { NameInformation ns = createNameInformation(t, n, parent); Preconditions.checkNotNull(ns); recordSet(ns.name, n); } else if (NodeUtil.isFunctionDeclaration(n)) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { JsName nameInfo = getName(nameNode.getString(), true); recordSet(nameInfo.name, nameNode); } } else if (NodeUtil.isObjectLitKey(n, parent)) { NameInformation ns = createNameInformation(t, n, parent); if (ns != null) { recordSet(ns.name, n); } } } // Record assignments and call sites if (n.isAssign()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { if (ns.isPrototype) { recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n); } else { recordSet(ns.name, nameNode); } } } else if (n.isCall()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null && ns.onlyAffectsClassDef) { JsName name = getName(ns.name, true); refNodes.add(new ClassDefiningFunctionNode( name, n, parent, parent.getParent())); } } }
src/com/google/javascript/jscomp/NameAnalyzer.java
smartNameRemoval causing compiler crash
What steps will reproduce the problem? Compiler the following code in advanced mode: {{{ var goog = {}; goog.inherits = function(x, y) {}; var ns = {}; /** @constructor */ ns.PageSelectionModel = function(){}; /** @constructor */ ns.PageSelectionModel.FooEvent = function() {}; /** @constructor */ ns.PageSelectionModel.SelectEvent = function() {}; goog.inherits(ns.PageSelectionModel.ChangeEvent, ns.PageSelectionModel.FooEvent); }}} What is the expected output? What do you see instead? The compiler will crash. The last var check throws an illegal state exception because it knows something is wrong. The crash is caused by smartNameRemoval. It has special logic for counting references in class-defining function calls (like goog.inherits), and it isn't properly creating a reference to PageSelectionModel.
596
642
Closure-42
Node processForInLoop(ForInLoop loopNode) { // Return the bare minimum to put the AST in a valid state. return newNode( Token.FOR, transform(loopNode.getIterator()), transform(loopNode.getIteratedObject()), transformBlock(loopNode.getBody())); }
Node processForInLoop(ForInLoop loopNode) { if (loopNode.isForEach()) { errorReporter.error( "unsupported language extension: for each", sourceName, loopNode.getLineno(), "", 0); // Return the bare minimum to put the AST in a valid state. return newNode(Token.EXPR_RESULT, Node.newNumber(0)); } return newNode( Token.FOR, transform(loopNode.getIterator()), transform(loopNode.getIteratedObject()), transformBlock(loopNode.getBody())); }
src/com/google/javascript/jscomp/parsing/IRFactory.java
Simple "Whitespace only" compression removing "each" keyword from "for each (var x in arr)" loop
What steps will reproduce the problem? See below code snippet before after compression ---Before--- contactcenter.screenpop.updatePopStatus = function(stamp, status) { for each ( var curTiming in this.timeLog.timings ) { if ( curTiming.callId == stamp ) { curTiming.flag = status; break; } } }; ---After--- contactcenter.screenpop.updatePopStatus=function(stamp,status){for(var curTiming in this.timeLog.timings)if(curTiming.callId==stamp){curTiming.flag=status;break}}; What is the expected output? What do you see instead? ---each keyword should be preserved What version of the product are you using? On what operating system? Please provide any additional information below. for each (** in **) ---> returns object value for (** in **) --> returns index
567
575
Closure-44
void add(String newcode) { maybeEndStatement(); if (newcode.length() == 0) { return; } char c = newcode.charAt(0); if ((isWordChar(c) || c == '\\') && isWordChar(getLastChar())) { // need space to separate. This is not pretty printing. // For example: "return foo;" append(" "); // Do not allow a forward slash to appear after a DIV. // For example, // REGEXP DIV REGEXP // is valid and should print like // / // / / } append(newcode); }
void add(String newcode) { maybeEndStatement(); if (newcode.length() == 0) { return; } char c = newcode.charAt(0); if ((isWordChar(c) || c == '\\') && isWordChar(getLastChar())) { // need space to separate. This is not pretty printing. // For example: "return foo;" append(" "); } else if (c == '/' && getLastChar() == '/') { // Do not allow a forward slash to appear after a DIV. // For example, // REGEXP DIV REGEXP // is valid and should print like // / // / / append(" "); } append(newcode); }
src/com/google/javascript/jscomp/CodeConsumer.java
alert(/ / / / /)
alert(/ / / / /); output: alert(/ /// /); should be: alert(/ // / /);
181
202
Closure-51
void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x && !isNegativeZero(x)) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
src/com/google/javascript/jscomp/CodeConsumer.java
-0.0 becomes 0 even in whitespace mode
Affects dart: http://code.google.com/p/dart/issues/detail?id=146
233
260
Closure-53
private void replaceAssignmentExpression(Var v, Reference ref, Map<String, String> varmap) { // Compute all of the assignments necessary List<Node> nodes = Lists.newArrayList(); Node val = ref.getAssignedValue(); blacklistVarReferencesInTree(val, v.scope); Preconditions.checkState(val.getType() == Token.OBJECTLIT); Set<String> all = Sets.newLinkedHashSet(varmap.keySet()); for (Node key = val.getFirstChild(); key != null; key = key.getNext()) { String var = key.getString(); Node value = key.removeFirstChild(); // TODO(user): Copy type information. nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), value)); all.remove(var); } // TODO(user): Better source information. for (String var : all) { nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), NodeUtil.newUndefinedNode(null))); } Node replacement; // All assignments evaluate to true, so make sure that the // expr statement evaluates to true in case it matters. nodes.add(new Node(Token.TRUE)); // Join these using COMMA. A COMMA node must have 2 children, so we // create a tree. In the tree the first child be the COMMA to match // the parser, otherwise tree equality tests fail. nodes = Lists.reverse(nodes); replacement = new Node(Token.COMMA); Node cur = replacement; int i; for (i = 0; i < nodes.size() - 2; i++) { cur.addChildToFront(nodes.get(i)); Node t = new Node(Token.COMMA); cur.addChildToFront(t); cur = t; } cur.addChildToFront(nodes.get(i)); cur.addChildToFront(nodes.get(i + 1)); Node replace = ref.getParent(); replacement.copyInformationFromForTree(replace); if (replace.getType() == Token.VAR) { replace.getParent().replaceChild( replace, NodeUtil.newExpr(replacement)); } else { replace.getParent().replaceChild(replace, replacement); } }
private void replaceAssignmentExpression(Var v, Reference ref, Map<String, String> varmap) { // Compute all of the assignments necessary List<Node> nodes = Lists.newArrayList(); Node val = ref.getAssignedValue(); blacklistVarReferencesInTree(val, v.scope); Preconditions.checkState(val.getType() == Token.OBJECTLIT); Set<String> all = Sets.newLinkedHashSet(varmap.keySet()); for (Node key = val.getFirstChild(); key != null; key = key.getNext()) { String var = key.getString(); Node value = key.removeFirstChild(); // TODO(user): Copy type information. nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), value)); all.remove(var); } // TODO(user): Better source information. for (String var : all) { nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), NodeUtil.newUndefinedNode(null))); } Node replacement; if (nodes.isEmpty()) { replacement = new Node(Token.TRUE); } else { // All assignments evaluate to true, so make sure that the // expr statement evaluates to true in case it matters. nodes.add(new Node(Token.TRUE)); // Join these using COMMA. A COMMA node must have 2 children, so we // create a tree. In the tree the first child be the COMMA to match // the parser, otherwise tree equality tests fail. nodes = Lists.reverse(nodes); replacement = new Node(Token.COMMA); Node cur = replacement; int i; for (i = 0; i < nodes.size() - 2; i++) { cur.addChildToFront(nodes.get(i)); Node t = new Node(Token.COMMA); cur.addChildToFront(t); cur = t; } cur.addChildToFront(nodes.get(i)); cur.addChildToFront(nodes.get(i + 1)); } Node replace = ref.getParent(); replacement.copyInformationFromForTree(replace); if (replace.getType() == Token.VAR) { replace.getParent().replaceChild( replace, NodeUtil.newExpr(replacement)); } else { replace.getParent().replaceChild(replace, replacement); } }
src/com/google/javascript/jscomp/InlineObjectLiterals.java
compiler-20110811 crashes with index(1) must be less than size(1)
What steps will reproduce the problem? Run compiler on https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js You can copy this into the Appspot closure compiler to see the error: // ==ClosureCompiler== // @output_file_name default.js // @compilation_level SIMPLE_OPTIMIZATIONS // @code_url https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js // ==/ClosureCompiler== I've attached a dump of the error from appspot. (This is the popular SoundManager library for HTML5 audio) What is the expected output? What do you see instead? Got crash... What version of the product are you using? On what operating system? Latest (compiler-20110811). We were previously using the June build, and had no problems Please provide any additional information below.
303
360
Closure-57
private static String extractClassNameIfGoog(Node node, Node parent, String functionName){ String className = null; if (NodeUtil.isExprCall(parent)) { Node callee = node.getFirstChild(); if (callee != null && callee.getType() == Token.GETPROP) { String qualifiedName = callee.getQualifiedName(); if (functionName.equals(qualifiedName)) { Node target = callee.getNext(); if (target != null) { className = target.getString(); } } } } return className; }
private static String extractClassNameIfGoog(Node node, Node parent, String functionName){ String className = null; if (NodeUtil.isExprCall(parent)) { Node callee = node.getFirstChild(); if (callee != null && callee.getType() == Token.GETPROP) { String qualifiedName = callee.getQualifiedName(); if (functionName.equals(qualifiedName)) { Node target = callee.getNext(); if (target != null && target.getType() == Token.STRING) { className = target.getString(); } } } } return className; }
src/com/google/javascript/jscomp/ClosureCodingConvention.java
compiler crashes when goog.provide used with non string
What steps will reproduce the problem? 1. insert goog.provide(some.function); 2. compile. 3. What is the expected output? What do you see instead? This should give an error diagnostic. What it gives is: java.lang.RuntimeException: java.lang.RuntimeException: INTERNAL COMPILER ERROR. Please email js-compiler@google.com with this stack trace. GETPROP 17 [originalname: Spike] [source_file: file.js] is not a string node Node(CALL): file.js:17:12 goog.provide(mine.Spike); ... [stack traces...] I think this is the current build as of the day of this report.
188
204
Closure-58
private void computeGenKill(Node n, BitSet gen, BitSet kill, boolean conditional) { switch (n.getType()) { case Token.SCRIPT: case Token.BLOCK: case Token.FUNCTION: return; case Token.WHILE: case Token.DO: case Token.IF: computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); return; case Token.FOR: if (!NodeUtil.isForIn(n)) { computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); } else { // for(x in y) {...} Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); if (NodeUtil.isVar(lhs)) { // for(var x in y) {...} lhs = lhs.getLastChild(); } addToSetIfLocal(lhs, kill); addToSetIfLocal(lhs, gen); computeGenKill(rhs, gen, kill, conditional); } return; case Token.VAR: for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.hasChildren()) { computeGenKill(c.getFirstChild(), gen, kill, conditional); if (!conditional) { addToSetIfLocal(c, kill); } } } return; case Token.AND: case Token.OR: computeGenKill(n.getFirstChild(), gen, kill, conditional); // May short circuit. computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.HOOK: computeGenKill(n.getFirstChild(), gen, kill, conditional); // Assume both sides are conditional. computeGenKill(n.getFirstChild().getNext(), gen, kill, true); computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.NAME: if (isArgumentsName(n)) { markAllParametersEscaped(); } else { addToSetIfLocal(n, gen); } return; default: if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) { Node lhs = n.getFirstChild(); if (!conditional) { addToSetIfLocal(lhs, kill); } if (!NodeUtil.isAssign(n)) { // assignments such as a += 1 reads a. addToSetIfLocal(lhs, gen); } computeGenKill(lhs.getNext(), gen, kill, conditional); } else { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { computeGenKill(c, gen, kill, conditional); } } return; } }
private void computeGenKill(Node n, BitSet gen, BitSet kill, boolean conditional) { switch (n.getType()) { case Token.SCRIPT: case Token.BLOCK: case Token.FUNCTION: return; case Token.WHILE: case Token.DO: case Token.IF: computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); return; case Token.FOR: if (!NodeUtil.isForIn(n)) { computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); } else { // for(x in y) {...} Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); if (NodeUtil.isVar(lhs)) { // for(var x in y) {...} lhs = lhs.getLastChild(); } if (NodeUtil.isName(lhs)) { addToSetIfLocal(lhs, kill); addToSetIfLocal(lhs, gen); } else { computeGenKill(lhs, gen, kill, conditional); } computeGenKill(rhs, gen, kill, conditional); } return; case Token.VAR: for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.hasChildren()) { computeGenKill(c.getFirstChild(), gen, kill, conditional); if (!conditional) { addToSetIfLocal(c, kill); } } } return; case Token.AND: case Token.OR: computeGenKill(n.getFirstChild(), gen, kill, conditional); // May short circuit. computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.HOOK: computeGenKill(n.getFirstChild(), gen, kill, conditional); // Assume both sides are conditional. computeGenKill(n.getFirstChild().getNext(), gen, kill, true); computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.NAME: if (isArgumentsName(n)) { markAllParametersEscaped(); } else { addToSetIfLocal(n, gen); } return; default: if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) { Node lhs = n.getFirstChild(); if (!conditional) { addToSetIfLocal(lhs, kill); } if (!NodeUtil.isAssign(n)) { // assignments such as a += 1 reads a. addToSetIfLocal(lhs, gen); } computeGenKill(lhs.getNext(), gen, kill, conditional); } else { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { computeGenKill(c, gen, kill, conditional); } } return; } }
src/com/google/javascript/jscomp/LiveVariablesAnalysis.java
Online CC bug: report java error.
What steps will reproduce the problem? 1. open http://closure-compiler.appspot.com/ 2. input js code: function keys(obj) { var a = [], i = 0; for (a[i++] in obj) ; return a; } 3. press [compile] button. What is the expected output? What do you see instead? Except OK. See java error. What version of the product are you using? On what operating system? Online CC version.
178
263
Closure-61
static boolean functionCallHasSideEffects( Node callNode, @Nullable AbstractCompiler compiler) { if (callNode.getType() != Token.CALL) { throw new IllegalStateException( "Expected CALL node, got " + Token.name(callNode.getType())); } if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); // Built-in functions with no side effects. if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) { return false; } } else if (nameNode.getType() == Token.GETPROP) { if (callNode.hasOneChild() && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains( nameNode.getLastChild().getString())) { return false; } if (callNode.isOnlyModifiesThisCall() && evaluatesToLocalValue(nameNode.getFirstChild())) { return false; } // Functions in the "Math" namespace have no side effects. if (compiler != null && !compiler.hasRegExpGlobalReferences()) { if (nameNode.getFirstChild().getType() == Token.REGEXP && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) { return false; } else if (nameNode.getFirstChild().getType() == Token.STRING && STRING_REGEXP_METHODS.contains( nameNode.getLastChild().getString())) { Node param = nameNode.getNext(); if (param != null && (param.getType() == Token.STRING || param.getType() == Token.REGEXP)) return false; } } } return true; }
static boolean functionCallHasSideEffects( Node callNode, @Nullable AbstractCompiler compiler) { if (callNode.getType() != Token.CALL) { throw new IllegalStateException( "Expected CALL node, got " + Token.name(callNode.getType())); } if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); // Built-in functions with no side effects. if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) { return false; } } else if (nameNode.getType() == Token.GETPROP) { if (callNode.hasOneChild() && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains( nameNode.getLastChild().getString())) { return false; } if (callNode.isOnlyModifiesThisCall() && evaluatesToLocalValue(nameNode.getFirstChild())) { return false; } // Functions in the "Math" namespace have no side effects. if (nameNode.getFirstChild().getType() == Token.NAME) { String namespaceName = nameNode.getFirstChild().getString(); if (namespaceName.equals("Math")) { return false; } } if (compiler != null && !compiler.hasRegExpGlobalReferences()) { if (nameNode.getFirstChild().getType() == Token.REGEXP && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) { return false; } else if (nameNode.getFirstChild().getType() == Token.STRING && STRING_REGEXP_METHODS.contains( nameNode.getLastChild().getString())) { Node param = nameNode.getNext(); if (param != null && (param.getType() == Token.STRING || param.getType() == Token.REGEXP)) return false; } } } return true; }
src/com/google/javascript/jscomp/NodeUtil.java
Closure removes needed code.
What steps will reproduce the problem? 1. Try the following code, in Simple mode Math.blah = function(test) { test.a = 5; }; var test = new Object(); Math.blah(test); 2. The output is Math.blah=function(a){a.a=5};var test={}; What is the expected output? What do you see instead? Note that Math.blah(test) was removed. It should not be. It issues a warning: JSC_USELESS_CODE: Suspicious code. This code lacks side-effects. Is there a bug? at line 4 character 9 What version of the product are you using? On what operating system? Tested on Google hosted Closure service. Please provide any additional information below. Closure seems to be protective about Math in particular, and doesn't like people messing around with her? So, when I try the following code:- var n = {}; n.blah = function(test) { test.a = 5; }; var test = new Object(); n.blah(test); It works. When I replace n by Math, then again, Closure kicks out blah. I need that poor fellow. Please talk some sense into it.
926
976
Closure-62
private String format(JSError error, boolean warning) { // extract source excerpt SourceExcerptProvider source = getSource(); String sourceExcerpt = source == null ? null : excerpt.get( source, error.sourceName, error.lineNumber, excerptFormatter); // formatting the message StringBuilder b = new StringBuilder(); if (error.sourceName != null) { b.append(error.sourceName); if (error.lineNumber > 0) { b.append(':'); b.append(error.lineNumber); } b.append(": "); } b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR)); b.append(" - "); b.append(error.description); b.append('\n'); if (sourceExcerpt != null) { b.append(sourceExcerpt); b.append('\n'); int charno = error.getCharno(); // padding equal to the excerpt and arrow at the end // charno == sourceExpert.length() means something is missing // at the end of the line if (excerpt.equals(LINE) && 0 <= charno && charno < sourceExcerpt.length()) { for (int i = 0; i < charno; i++) { char c = sourceExcerpt.charAt(i); if (Character.isWhitespace(c)) { b.append(c); } else { b.append(' '); } } b.append("^\n"); } } return b.toString(); }
private String format(JSError error, boolean warning) { // extract source excerpt SourceExcerptProvider source = getSource(); String sourceExcerpt = source == null ? null : excerpt.get( source, error.sourceName, error.lineNumber, excerptFormatter); // formatting the message StringBuilder b = new StringBuilder(); if (error.sourceName != null) { b.append(error.sourceName); if (error.lineNumber > 0) { b.append(':'); b.append(error.lineNumber); } b.append(": "); } b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR)); b.append(" - "); b.append(error.description); b.append('\n'); if (sourceExcerpt != null) { b.append(sourceExcerpt); b.append('\n'); int charno = error.getCharno(); // padding equal to the excerpt and arrow at the end // charno == sourceExpert.length() means something is missing // at the end of the line if (excerpt.equals(LINE) && 0 <= charno && charno <= sourceExcerpt.length()) { for (int i = 0; i < charno; i++) { char c = sourceExcerpt.charAt(i); if (Character.isWhitespace(c)) { b.append(c); } else { b.append(' '); } } b.append("^\n"); } } return b.toString(); }
src/com/google/javascript/jscomp/LightweightMessageFormatter.java
Column-indicating caret is sometimes not in error output
For some reason, the caret doesn't always show up in the output when there are errors. When test.js looks like this: >alert(1; , the output is this: >java -jar compiler.jar --js test.js test.js:1: ERROR - Parse error. missing ) after argument list 1 error(s), 0 warning(s) However, when test.js looks like this (notice the line break after the semicolon): >alert(1; > , the output is this: >java -jar compiler.jar --js test.js test.js:1: ERROR - Parse error. missing ) after argument list alert(1; ^ 1 error(s), 0 warning(s) That's the simplest reproduction of the problem that I could come up with, but I just encountered the problem in a file with ~100 LOC in it. This is the first time I believe I've run into the problem, but when it happens, my error parser fails and it becomes a pain to track down the raw output to find the actual problem. Tested against r1171, committed 6/10 08:06. The problem is present going back to at least r1000, so this isn't a new issue.
66
111
Closure-67
private boolean isPrototypePropertyAssign(Node assign) { Node n = assign.getFirstChild(); if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign) && n.getType() == Token.GETPROP ) { // We want to exclude the assignment itself from the usage list boolean isChainedProperty = n.getFirstChild().getType() == Token.GETPROP; if (isChainedProperty) { Node child = n.getFirstChild().getFirstChild().getNext(); if (child.getType() == Token.STRING && child.getString().equals("prototype")) { return true; } } } return false; }
private boolean isPrototypePropertyAssign(Node assign) { Node n = assign.getFirstChild(); if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign) && n.getType() == Token.GETPROP && assign.getParent().getType() == Token.EXPR_RESULT) { // We want to exclude the assignment itself from the usage list boolean isChainedProperty = n.getFirstChild().getType() == Token.GETPROP; if (isChainedProperty) { Node child = n.getFirstChild().getFirstChild().getNext(); if (child.getType() == Token.STRING && child.getString().equals("prototype")) { return true; } } } return false; }
src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java
Advanced compilations renames a function and then deletes it, leaving a reference to a renamed but non-existent function
If we provide the below code to advanced: function A() { this._x = 1; } A.prototype['func1'] = // done to save public reference to func1 A.prototype.func1 = function() { this._x = 2; this.func2(); } A.prototype.func2 = function() { this._x = 3; this.func3(); } window['A'] = A; We get the output: function a() { this.a = 1 } a.prototype.func1 = a.prototype.b = function() { this.a = 2; this.c() // Problem! }; window.A = a; So the compiler emits no errors, and renames 'func2' to 'c' but ends up throwing away the definition of that function! The problem arises when I use: A.prototype['func1'] = // done to save public reference to func1 A.prototype.func1 = function() { ... } The ['func1'] line is apparently enough to save the reference correctly, but also has the side effect of causing the function innards to do the wrong thing. I can of course instead write it as: A.prototype['func1'] = A.prototype.func1; A.prototype.func1 = function() { this._x = 2; this.func2(); } In which case Advanced will compile correctly and the results will also be valid. function a() { this.a = 1 } a.prototype.func1 = a.prototype.b; a.prototype.b = function() { this.a = 2; this.a = 3 // func2, correctly minified }; window.A = a; For now I can just use the expected way of declaring that func1 export, but since the compiler returns with no errors or warnings and creates a function with no definition, it seems worth reporting.
314
334
Closure-69
private void visitCall(NodeTraversal t, Node n) { Node child = n.getFirstChild(); JSType childType = getJSType(child).restrictByNotNullOrUndefined(); if (!childType.canBeCalled()) { report(t, n, NOT_CALLABLE, childType.toString()); ensureTyped(t, n); return; } // A couple of types can be called as if they were functions. // If it is a function type, then validate parameters. if (childType instanceof FunctionType) { FunctionType functionType = (FunctionType) childType; boolean isExtern = false; JSDocInfo functionJSDocInfo = functionType.getJSDocInfo(); if(functionJSDocInfo != null) { String sourceName = functionJSDocInfo.getSourceName(); CompilerInput functionSource = compiler.getInput(sourceName); isExtern = functionSource.isExtern(); } // Non-native constructors should not be called directly // unless they specify a return type and are defined // in an extern. if (functionType.isConstructor() && !functionType.isNativeObjectType() && (functionType.getReturnType().isUnknownType() || functionType.getReturnType().isVoidType() || !isExtern)) { report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString()); } // Functions with explcit 'this' types must be called in a GETPROP // or GETELEM. visitParameterList(t, n, functionType); ensureTyped(t, n, functionType.getReturnType()); } else { ensureTyped(t, n); } // TODO: Add something to check for calls of RegExp objects, which is not // supported by IE. Either say something about the return type or warn // about the non-portability of the call or both. }
private void visitCall(NodeTraversal t, Node n) { Node child = n.getFirstChild(); JSType childType = getJSType(child).restrictByNotNullOrUndefined(); if (!childType.canBeCalled()) { report(t, n, NOT_CALLABLE, childType.toString()); ensureTyped(t, n); return; } // A couple of types can be called as if they were functions. // If it is a function type, then validate parameters. if (childType instanceof FunctionType) { FunctionType functionType = (FunctionType) childType; boolean isExtern = false; JSDocInfo functionJSDocInfo = functionType.getJSDocInfo(); if(functionJSDocInfo != null) { String sourceName = functionJSDocInfo.getSourceName(); CompilerInput functionSource = compiler.getInput(sourceName); isExtern = functionSource.isExtern(); } // Non-native constructors should not be called directly // unless they specify a return type and are defined // in an extern. if (functionType.isConstructor() && !functionType.isNativeObjectType() && (functionType.getReturnType().isUnknownType() || functionType.getReturnType().isVoidType() || !isExtern)) { report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString()); } // Functions with explcit 'this' types must be called in a GETPROP // or GETELEM. if (functionType.isOrdinaryFunction() && !functionType.getTypeOfThis().isUnknownType() && !functionType.getTypeOfThis().isNativeObjectType() && !(child.getType() == Token.GETELEM || child.getType() == Token.GETPROP)) { report(t, n, EXPECTED_THIS_TYPE, functionType.toString()); } visitParameterList(t, n, functionType); ensureTyped(t, n, functionType.getReturnType()); } else { ensureTyped(t, n); } // TODO: Add something to check for calls of RegExp objects, which is not // supported by IE. Either say something about the return type or warn // about the non-portability of the call or both. }
src/com/google/javascript/jscomp/TypeCheck.java
Compiler should warn/error when instance methods are operated on
What steps will reproduce the problem? 1. Compile and run the following code: goog.require('goog.graphics.Path'); function demo() { var path = new goog.graphics.Path(); var points = [[1,1], [2,2]]; for (var i = 0; i < points.length; i++) { (i == 0 ? path.moveTo : path.lineTo)(points[i][0], points[i][1]); } } goog.exportSymbol('demo', demo); What is the expected output? What do you see instead? I expect it to either work or produce a warning. In this case, the latter since there's an error in the javascript - when calling path.moveTo(x, y), "this" is set correctly to the path element in the moveTo function. But when the function is operated on, as in (i == 0 ? path.moveTo : path.lineTo)(x, y), it's no longer an instance method invocation, so "this" reverts to the window object. In this case, an error results because moveTo references a field in Path that is now "undefined". Better would be to issue a warning/error that an instance method is being converted to a normal function (perhaps only if it references this). What version of the product are you using? On what operating system? Unknown (it's built into my build tools) - I presume this issue is present in all builds. Running on ubuntu. Please provide any additional information below.
1,544
1,590
Closure-7
public JSType caseObjectType(ObjectType type) { if (value.equals("function")) { JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE); return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null; // Objects are restricted to "Function", subtypes are left // Only filter out subtypes of "function" } return matchesExpectation("object") ? type : null; }
public JSType caseObjectType(ObjectType type) { if (value.equals("function")) { JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE); if (resultEqualsValue) { // Objects are restricted to "Function", subtypes are left return ctorType.getGreatestSubtype(type); } else { // Only filter out subtypes of "function" return type.isSubtype(ctorType) ? null : type; } } return matchesExpectation("object") ? type : null; }
src/com/google/javascript/jscomp/type/ChainableReverseAbstractInterpreter.java
Bad type inference with goog.isFunction and friends
experimental/johnlenz/typeerror/test.js:16: WARNING - Property length never defined on Number var i = object.length; This is the reduced test case: /** * @param {*} object Any object. * @return {boolean} */ test.isMatched = function(object) { if (goog.isDef(object)) { if (goog.isFunction(object)) { // return object(); } else if (goog.isBoolean(object)) { // return object; } else if (goog.isString(object)) { // return test.isDef(object); } else if (goog.isArray(object)) { var i = object.length; } } return false; };
610
618
Closure-70
private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), true); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } } // end declareArguments
private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), false); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } } // end declareArguments
src/com/google/javascript/jscomp/TypedScopeCreator.java
unexpected typed coverage of less than 100%
What steps will reproduce the problem? 1. Create JavaScript file: /*global window*/ /*jslint sub: true*/ /** * @constructor * @param {!Element} element */ function Example(element) { /** * @param {!string} ns * @param {!string} name * @return {undefined} */ this.appendElement = function appendElement(ns, name) { var e = element.ownerDocument.createElementNS(ns, name); element.appendChild(e); }; } window["Example"] = Example; 2. compile it: java -jar compiler.jar --jscomp_error checkTypes --summary_detail_level 3 --js v.js --js_output_file compiled.js 3. observe the outcome: 0 error(s), 0 warning(s), 73.7% typed What is the expected output? What do you see instead? This was expected: 0 error(s), 0 warning(s), 100% typed What version of the product are you using? On what operating system? Closure Compiler Version: 964, Built on: 2011/04/05 14:31 on GNU/Linux. Please provide any additional information below.
1,734
1,753
Closure-81
Node processFunctionNode(FunctionNode functionNode) { Name name = functionNode.getFunctionName(); Boolean isUnnamedFunction = false; if (name == null) { name = new Name(); name.setIdentifier(""); isUnnamedFunction = true; } Node node = newNode(Token.FUNCTION); Node newName = transform(name); if (isUnnamedFunction) { // Old Rhino tagged the empty name node with the line number of the // declaration. newName.setLineno(functionNode.getLineno()); // TODO(bowdidge) Mark line number of paren correctly. // Same problem as below - the left paren might not be on the // same line as the function keyword. int lpColumn = functionNode.getAbsolutePosition() + functionNode.getLp(); newName.setCharno(position2charno(lpColumn)); } node.addChildToBack(newName); Node lp = newNode(Token.LP); // The left paren's complicated because it's not represented by an // AstNode, so there's nothing that has the actual line number that it // appeared on. We know the paren has to appear on the same line as the // function name (or else a semicolon will be inserted.) If there's no // function name, assume the paren was on the same line as the function. // TODO(bowdidge): Mark line number of paren correctly. Name fnName = functionNode.getFunctionName(); if (fnName != null) { lp.setLineno(fnName.getLineno()); } else { lp.setLineno(functionNode.getLineno()); } int lparenCharno = functionNode.getLp() + functionNode.getAbsolutePosition(); lp.setCharno(position2charno(lparenCharno)); for (AstNode param : functionNode.getParams()) { lp.addChildToBack(transform(param)); } node.addChildToBack(lp); Node bodyNode = transform(functionNode.getBody()); parseDirectives(bodyNode); node.addChildToBack(bodyNode); return node; }
Node processFunctionNode(FunctionNode functionNode) { Name name = functionNode.getFunctionName(); Boolean isUnnamedFunction = false; if (name == null) { int functionType = functionNode.getFunctionType(); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { errorReporter.error( "unnamed function statement", sourceName, functionNode.getLineno(), "", 0); } name = new Name(); name.setIdentifier(""); isUnnamedFunction = true; } Node node = newNode(Token.FUNCTION); Node newName = transform(name); if (isUnnamedFunction) { // Old Rhino tagged the empty name node with the line number of the // declaration. newName.setLineno(functionNode.getLineno()); // TODO(bowdidge) Mark line number of paren correctly. // Same problem as below - the left paren might not be on the // same line as the function keyword. int lpColumn = functionNode.getAbsolutePosition() + functionNode.getLp(); newName.setCharno(position2charno(lpColumn)); } node.addChildToBack(newName); Node lp = newNode(Token.LP); // The left paren's complicated because it's not represented by an // AstNode, so there's nothing that has the actual line number that it // appeared on. We know the paren has to appear on the same line as the // function name (or else a semicolon will be inserted.) If there's no // function name, assume the paren was on the same line as the function. // TODO(bowdidge): Mark line number of paren correctly. Name fnName = functionNode.getFunctionName(); if (fnName != null) { lp.setLineno(fnName.getLineno()); } else { lp.setLineno(functionNode.getLineno()); } int lparenCharno = functionNode.getLp() + functionNode.getAbsolutePosition(); lp.setCharno(position2charno(lparenCharno)); for (AstNode param : functionNode.getParams()) { lp.addChildToBack(transform(param)); } node.addChildToBack(lp); Node bodyNode = transform(functionNode.getBody()); parseDirectives(bodyNode); node.addChildToBack(bodyNode); return node; }
src/com/google/javascript/jscomp/parsing/IRFactory.java
An unnamed function statement statements should generate a parse error
An unnamed function statement statements should generate a parse error, but it does not, for example: function () {}; Note: Unnamed function expression are legal: (function(){});
513
562
Closure-82
public final boolean isEmptyType() { return isNoType() || isNoObjectType() || isNoResolvedType(); }
public final boolean isEmptyType() { return isNoType() || isNoObjectType() || isNoResolvedType() || (registry.getNativeFunctionType( JSTypeNative.LEAST_FUNCTION_TYPE) == this); }
src/com/google/javascript/rhino/jstype/JSType.java
.indexOf fails to produce missing property warning
The following code compiled with VERBOSE warnings or with the missingProperties check enabled fails to produce a warning or error: var s = new String("hello"); alert(s.toLowerCase.indexOf("l")); However, other string functions do properly produce the warning: var s = new String("hello"); alert(s.toLowerCase.substr(0, 1));
162
164
Closure-83
public int parseArguments(Parameters params) throws CmdLineException { String param = params.getParameter(0); if (param == null) { setter.addValue(true); return 0; } else { String lowerParam = param.toLowerCase(); if (TRUES.contains(lowerParam)) { setter.addValue(true); } else if (FALSES.contains(lowerParam)) { setter.addValue(false); } else { setter.addValue(true); return 0; } return 1; } }
public int parseArguments(Parameters params) throws CmdLineException { String param = null; try { param = params.getParameter(0); } catch (CmdLineException e) {} if (param == null) { setter.addValue(true); return 0; } else { String lowerParam = param.toLowerCase(); if (TRUES.contains(lowerParam)) { setter.addValue(true); } else if (FALSES.contains(lowerParam)) { setter.addValue(false); } else { setter.addValue(true); return 0; } return 1; } }
src/com/google/javascript/jscomp/CommandLineRunner.java
Cannot see version with --version
What steps will reproduce the problem? 1. Download sources of latest (r698) command-line version of closure compiler. 2. Build (with ant from command line). 3. Run compiler (java -jar compiler.jar --version). What is the expected output? Closure Compiler (http://code.google.com/closure/compiler) Version: 698 Built on: 2011/01/17 12:16 What do you see instead? Опция "--version" требует операнд (Option "--version" requires operand) and full list of options with description. What version of the product are you using? On what operating system? Latest source of command-line compiler from SVN (r698). OS Linux Mint 7, Sun Java 1.6.0_22. Please provide any additional information below. When running compiler with java -jar compiler.jar --version ? it shows error message, then version info, then full list of options.
333
351
Closure-86
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) { switch (value.getType()) { case Token.ASSIGN: // A result that is aliased by a non-local name, is the effectively the // same as returning a non-local name, but this doesn't matter if the // value is immutable. return NodeUtil.isImmutableValue(value.getLastChild()) || (locals.apply(value) && evaluatesToLocalValue(value.getLastChild(), locals)); case Token.COMMA: return evaluatesToLocalValue(value.getLastChild(), locals); case Token.AND: case Token.OR: return evaluatesToLocalValue(value.getFirstChild(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.HOOK: return evaluatesToLocalValue(value.getFirstChild().getNext(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.INC: case Token.DEC: if (value.getBooleanProp(Node.INCRDECR_PROP)) { return evaluatesToLocalValue(value.getFirstChild(), locals); } else { return true; } case Token.THIS: return locals.apply(value); case Token.NAME: return isImmutableValue(value) || locals.apply(value); case Token.GETELEM: case Token.GETPROP: // There is no information about the locality of object properties. return locals.apply(value); case Token.CALL: return callHasLocalResult(value) || isToStringMethodCall(value) || locals.apply(value); case Token.NEW: // TODO(nicksantos): This needs to be changed so that it // returns true iff we're sure the value was never aliased from inside // the constructor (similar to callHasLocalResult) return true; case Token.FUNCTION: case Token.REGEXP: case Token.ARRAYLIT: case Token.OBJECTLIT: // Literals objects with non-literal children are allowed. return true; case Token.IN: // TODO(johnlenz): should IN operator be included in #isSimpleOperator? return true; default: // Other op force a local value: // x = '' + g (x is now an local string) // x -= g (x is now an local number) if (isAssignmentOp(value) || isSimpleOperator(value) || isImmutableValue(value)) { return true; } throw new IllegalStateException( "Unexpected expression node" + value + "\n parent:" + value.getParent()); } }
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) { switch (value.getType()) { case Token.ASSIGN: // A result that is aliased by a non-local name, is the effectively the // same as returning a non-local name, but this doesn't matter if the // value is immutable. return NodeUtil.isImmutableValue(value.getLastChild()) || (locals.apply(value) && evaluatesToLocalValue(value.getLastChild(), locals)); case Token.COMMA: return evaluatesToLocalValue(value.getLastChild(), locals); case Token.AND: case Token.OR: return evaluatesToLocalValue(value.getFirstChild(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.HOOK: return evaluatesToLocalValue(value.getFirstChild().getNext(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.INC: case Token.DEC: if (value.getBooleanProp(Node.INCRDECR_PROP)) { return evaluatesToLocalValue(value.getFirstChild(), locals); } else { return true; } case Token.THIS: return locals.apply(value); case Token.NAME: return isImmutableValue(value) || locals.apply(value); case Token.GETELEM: case Token.GETPROP: // There is no information about the locality of object properties. return locals.apply(value); case Token.CALL: return callHasLocalResult(value) || isToStringMethodCall(value) || locals.apply(value); case Token.NEW: // TODO(nicksantos): This needs to be changed so that it // returns true iff we're sure the value was never aliased from inside // the constructor (similar to callHasLocalResult) return false; case Token.FUNCTION: case Token.REGEXP: case Token.ARRAYLIT: case Token.OBJECTLIT: // Literals objects with non-literal children are allowed. return true; case Token.IN: // TODO(johnlenz): should IN operator be included in #isSimpleOperator? return true; default: // Other op force a local value: // x = '' + g (x is now an local string) // x -= g (x is now an local number) if (isAssignmentOp(value) || isSimpleOperator(value) || isImmutableValue(value)) { return true; } throw new IllegalStateException( "Unexpected expression node" + value + "\n parent:" + value.getParent()); } }
src/com/google/javascript/jscomp/NodeUtil.java
side-effects analysis incorrectly removing function calls with side effects
Sample Code: --- /** @constructor */ function Foo() { var self = this; window.setTimeout(function() { window.location = self.location; }, 0); } Foo.prototype.setLocation = function(loc) { this.location = loc; }; (new Foo()).setLocation('http://www.google.com/'); --- The setLocation call will get removed in advanced mode.
2,424
2,489
Closure-87
private boolean isFoldableExpressBlock(Node n) { if (n.getType() == Token.BLOCK) { if (n.hasOneChild()) { Node maybeExpr = n.getFirstChild(); // IE has a bug where event handlers behave differently when // their return value is used vs. when their return value is in // an EXPR_RESULT. It's pretty freaking weird. See: // http://code.google.com/p/closure-compiler/issues/detail?id=291 // We try to detect this case, and not fold EXPR_RESULTs // into other expressions. // We only have to worry about methods with an implicit 'this' // param, or this doesn't happen. return NodeUtil.isExpressionNode(maybeExpr); } } return false; }
private boolean isFoldableExpressBlock(Node n) { if (n.getType() == Token.BLOCK) { if (n.hasOneChild()) { Node maybeExpr = n.getFirstChild(); if (maybeExpr.getType() == Token.EXPR_RESULT) { // IE has a bug where event handlers behave differently when // their return value is used vs. when their return value is in // an EXPR_RESULT. It's pretty freaking weird. See: // http://code.google.com/p/closure-compiler/issues/detail?id=291 // We try to detect this case, and not fold EXPR_RESULTs // into other expressions. if (maybeExpr.getFirstChild().getType() == Token.CALL) { Node calledFn = maybeExpr.getFirstChild().getFirstChild(); // We only have to worry about methods with an implicit 'this' // param, or this doesn't happen. if (calledFn.getType() == Token.GETELEM) { return false; } else if (calledFn.getType() == Token.GETPROP && calledFn.getLastChild().getString().startsWith("on")) { return false; } } return true; } return false; } } return false; }
src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
IE8 error: Object doesn't support this action
What steps will reproduce the problem? 1. Use script with fragment like if (e.onchange) { e.onchange({ _extendedByPrototype: Prototype.emptyFunction, target: e }); } 2. Compile with Compiler (command-line, latest version) 3. Use in IE8 What is the expected output? Script: if(b.onchange){b.onchange({_extendedByPrototype:Prototype.emptyFunction,target :b})} What do you see instead? Script: b.onchange&&b.onchange({_extendedByPrototype:Prototype.emptyFunction,target :b}) IE8: Error message "Object doesn't support this action" What version of the product are you using? On what operating system? Version: 20100917 (revision 440) Built on: 2010/09/17 17:55
519
538
Closure-88
private VariableLiveness isVariableReadBeforeKill( Node n, String variable) { if (NodeUtil.isName(n) && variable.equals(n.getString())) { if (NodeUtil.isLhs(n, n.getParent())) { // The expression to which the assignment is made is evaluated before // the RHS is evaluated (normal left to right evaluation) but the KILL // occurs after the RHS is evaluated. return VariableLiveness.KILL; } else { return VariableLiveness.READ; } } // Expressions are evaluated left-right, depth first. for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION VariableLiveness state = isVariableReadBeforeKill(child, variable); if (state != VariableLiveness.MAYBE_LIVE) { return state; } } } return VariableLiveness.MAYBE_LIVE; }
private VariableLiveness isVariableReadBeforeKill( Node n, String variable) { if (NodeUtil.isName(n) && variable.equals(n.getString())) { if (NodeUtil.isLhs(n, n.getParent())) { Preconditions.checkState(n.getParent().getType() == Token.ASSIGN); // The expression to which the assignment is made is evaluated before // the RHS is evaluated (normal left to right evaluation) but the KILL // occurs after the RHS is evaluated. Node rhs = n.getNext(); VariableLiveness state = isVariableReadBeforeKill(rhs, variable); if (state == VariableLiveness.READ) { return state; } return VariableLiveness.KILL; } else { return VariableLiveness.READ; } } // Expressions are evaluated left-right, depth first. for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION VariableLiveness state = isVariableReadBeforeKill(child, variable); if (state != VariableLiveness.MAYBE_LIVE) { return state; } } } return VariableLiveness.MAYBE_LIVE; }
src/com/google/javascript/jscomp/DeadAssignmentsElimination.java
Incorrect assignment removal from expression in simple mode.
function closureCompilerTest(someNode) { var nodeId; return ((nodeId=someNode.id) && (nodeId=parseInt(nodeId.substr(1))) && nodeId>0); } COMPILES TO: function closureCompilerTest(b){var a;return b.id&&(a=parseInt(a.substr(1)))&&a>0}; "nodeId=someNode.id" is replaced with simply "b.id" which is incorrect as the value of "nodeId" is used.
323
347
Closure-91
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } // Don't traverse functions unless they would normally // be able to have a @this annotation associated with them. e.g., // var a = function() { }; // or // function a() {} // or // a.x = function() {}; // or // var a = {x: function() {}}; int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN || // object literal keys pType == Token.STRING || pType == Token.NUMBER)) { return false; } // Don't traverse functions that are getting lent to a prototype. } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { // Always traverse the left side of the assignment. To handle // nested assignments properly (e.g., (a = this).property = c;), // assignLhsChild should not be overridden. if (assignLhsChild == null) { assignLhsChild = lhs; } } else { // Only traverse the right side if it's not an assignment to a prototype // property or subproperty. if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; }
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } // Don't traverse functions unless they would normally // be able to have a @this annotation associated with them. e.g., // var a = function() { }; // or // function a() {} // or // a.x = function() {}; // or // var a = {x: function() {}}; int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN || // object literal keys pType == Token.STRING || pType == Token.NUMBER)) { return false; } // Don't traverse functions that are getting lent to a prototype. Node gramps = parent.getParent(); if (NodeUtil.isObjectLitKey(parent, gramps)) { JSDocInfo maybeLends = gramps.getJSDocInfo(); if (maybeLends != null && maybeLends.getLendsName() != null && maybeLends.getLendsName().endsWith(".prototype")) { return false; } } } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { // Always traverse the left side of the assignment. To handle // nested assignments properly (e.g., (a = this).property = c;), // assignLhsChild should not be overridden. if (assignLhsChild == null) { assignLhsChild = lhs; } } else { // Only traverse the right side if it's not an assignment to a prototype // property or subproperty. if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; }
src/com/google/javascript/jscomp/CheckGlobalThis.java
support @lends annotation
Some javascript toolkits (dojo, base, etc.) have a special way of declaring (what java calls) classes, for example in dojo: dojo.declare("MyClass", [superClass1, superClass2], { foo: function(){ ... } bar: function(){ ... } }); JSDoc (or at least JSDoc toolkit) supports this via annotations: /** * @name MyClass * @class * @extends superClass1 * @extends superClass2 */ dojo.declare("MyClass", [superClass1, superClass2], /** @lends MyClass.prototype */ { foo: function(){ ... } bar: function(){ ... } }); The @lends keyword in particular is useful since it tells JSDoc that foo and bar are part of MyClass's prototype. But closure compiler isn't picking up on that, thus I get a bunch of errors about "dangerous use of this" inside of foo() and bar(). So, can @lends support be added to the closure compiler? The workaround is to use @this on every method, but not sure if that is sufficient to make advanced mode compilation work correctly.
82
146