id
stringlengths
5
19
content
stringlengths
94
57.5k
max_stars_repo_path
stringlengths
36
95
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
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
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
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
Chart-13
protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { double[] w = new double[5]; double[] h = new double[5]; w[0] = constraint.getWidth(); if (this.topBlock != null) { RectangleConstraint c1 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight()), LengthConstraintType.RANGE); Size2D size = this.topBlock.arrange(g2, c1); h[0] = size.height; } w[1] = w[0]; if (this.bottomBlock != null) { RectangleConstraint c2 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight() - h[0]), LengthConstraintType.RANGE); Size2D size = this.bottomBlock.arrange(g2, c2); h[1] = size.height; } h[2] = constraint.getHeight() - h[1] - h[0]; if (this.leftBlock != null) { RectangleConstraint c3 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth()), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.leftBlock.arrange(g2, c3); w[2] = size.width; } h[3] = h[2]; if (this.rightBlock != null) { RectangleConstraint c4 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth() - w[2]), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.rightBlock.arrange(g2, c4); w[3] = size.width; } h[4] = h[2]; w[4] = constraint.getWidth() - w[3] - w[2]; RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]); if (this.centerBlock != null) { this.centerBlock.arrange(g2, c5); } if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0], h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2], w[1], h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], h[2])); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0], w[3], h[3])); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4], h[4])); } return new Size2D(constraint.getWidth(), constraint.getHeight()); } protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { double[] w = new double[5]; double[] h = new double[5]; w[0] = constraint.getWidth(); if (this.topBlock != null) { RectangleConstraint c1 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight()), LengthConstraintType.RANGE); Size2D size = this.topBlock.arrange(g2, c1); h[0] = size.height; } w[1] = w[0]; if (this.bottomBlock != null) { RectangleConstraint c2 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight() - h[0]), LengthConstraintType.RANGE); Size2D size = this.bottomBlock.arrange(g2, c2); h[1] = size.height; } h[2] = constraint.getHeight() - h[1] - h[0]; if (this.leftBlock != null) { RectangleConstraint c3 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth()), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.leftBlock.arrange(g2, c3); w[2] = size.width; } h[3] = h[2]; if (this.rightBlock != null) { RectangleConstraint c4 = new RectangleConstraint(0.0, new Range(0.0, Math.max(constraint.getWidth() - w[2], 0.0)), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.rightBlock.arrange(g2, c4); w[3] = size.width; } h[4] = h[2]; w[4] = constraint.getWidth() - w[3] - w[2]; RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]); if (this.centerBlock != null) { this.centerBlock.arrange(g2, c5); } if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0], h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2], w[1], h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], h[2])); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0], w[3], h[3])); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4], h[4])); } return new Size2D(constraint.getWidth(), constraint.getHeight()); }
source/org/jfree/chart/block/BorderArrangement.java
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
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
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
Chart-26
protected AxisState drawLabel(String label, Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { // it is unlikely that 'state' will be null, but check anyway... if (state == null) { throw new IllegalArgumentException("Null 'state' argument."); } if ((label == null) || (label.equals(""))) { return state; } Font font = getLabelFont(); RectangleInsets insets = getLabelInsets(); g2.setFont(font); g2.setPaint(getLabelPaint()); FontMetrics fm = g2.getFontMetrics(); Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm); Shape hotspot = null; if (edge == RectangleEdge.TOP) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() - insets.getBottom() - h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorUp(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.BOTTOM) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() + insets.getTop() + h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorDown(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.LEFT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() - insets.getRight() - w / 2.0); float labely = (float) dataArea.getCenterY(); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorLeft(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } else if (edge == RectangleEdge.RIGHT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() + Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() + insets.getLeft() + w / 2.0); float labely = (float) (dataArea.getY() + dataArea.getHeight() / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorRight(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } if (plotState != null && hotspot != null) { ChartRenderingInfo owner = plotState.getOwner(); EntityCollection entities = owner.getEntityCollection(); if (entities != null) { entities.add(new AxisLabelEntity(this, hotspot, this.labelToolTip, this.labelURL)); } } return state; } protected AxisState drawLabel(String label, Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { // it is unlikely that 'state' will be null, but check anyway... if (state == null) { throw new IllegalArgumentException("Null 'state' argument."); } if ((label == null) || (label.equals(""))) { return state; } Font font = getLabelFont(); RectangleInsets insets = getLabelInsets(); g2.setFont(font); g2.setPaint(getLabelPaint()); FontMetrics fm = g2.getFontMetrics(); Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm); Shape hotspot = null; if (edge == RectangleEdge.TOP) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() - insets.getBottom() - h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorUp(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.BOTTOM) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() + insets.getTop() + h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorDown(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.LEFT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() - insets.getRight() - w / 2.0); float labely = (float) dataArea.getCenterY(); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorLeft(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } else if (edge == RectangleEdge.RIGHT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() + Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() + insets.getLeft() + w / 2.0); float labely = (float) (dataArea.getY() + dataArea.getHeight() / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorRight(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } if (plotState != null && hotspot != null) { ChartRenderingInfo owner = plotState.getOwner(); if (owner != null) { EntityCollection entities = owner.getEntityCollection(); if (entities != null) { entities.add(new AxisLabelEntity(this, hotspot, this.labelToolTip, this.labelURL)); } } } return state; }
source/org/jfree/chart/axis/Axis.java
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
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
Chart-5
public XYDataItem addOrUpdate(Number x, Number y) { if (x == null) { throw new IllegalArgumentException("Null 'x' argument."); } // if we get to here, we know that duplicate X values are not permitted XYDataItem overwritten = null; int index = indexOf(x); if (index >= 0 && !this.allowDuplicateXValues) { XYDataItem existing = (XYDataItem) this.data.get(index); try { overwritten = (XYDataItem) existing.clone(); } catch (CloneNotSupportedException e) { throw new SeriesException("Couldn't clone XYDataItem!"); } existing.setY(y); } else { // if the series is sorted, the negative index is a result from // Collections.binarySearch() and tells us where to insert the // new item...otherwise it will be just -1 and we should just // append the value to the list... if (this.autoSort) { this.data.add(-index - 1, new XYDataItem(x, y)); } else { this.data.add(new XYDataItem(x, y)); } // check if this addition will exceed the maximum item count... if (getItemCount() > this.maximumItemCount) { this.data.remove(0); } } fireSeriesChanged(); return overwritten; } public XYDataItem addOrUpdate(Number x, Number y) { if (x == null) { throw new IllegalArgumentException("Null 'x' argument."); } if (this.allowDuplicateXValues) { add(x, y); return null; } // if we get to here, we know that duplicate X values are not permitted XYDataItem overwritten = null; int index = indexOf(x); if (index >= 0) { XYDataItem existing = (XYDataItem) this.data.get(index); try { overwritten = (XYDataItem) existing.clone(); } catch (CloneNotSupportedException e) { throw new SeriesException("Couldn't clone XYDataItem!"); } existing.setY(y); } else { // if the series is sorted, the negative index is a result from // Collections.binarySearch() and tells us where to insert the // new item...otherwise it will be just -1 and we should just // append the value to the list... if (this.autoSort) { this.data.add(-index - 1, new XYDataItem(x, y)); } else { this.data.add(new XYDataItem(x, y)); } // check if this addition will exceed the maximum item count... if (getItemCount() > this.maximumItemCount) { this.data.remove(0); } } fireSeriesChanged(); return overwritten; }
source/org/jfree/data/xy/XYSeries.java
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
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
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
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
Cli-11
private static void appendOption(final StringBuffer buff, final Option option, final boolean required) { if (!required) { buff.append("["); } if (option.getOpt() != null) { buff.append("-").append(option.getOpt()); } else { buff.append("--").append(option.getLongOpt()); } // if the Option has a value if (option.hasArg() && (option.getArgName() != null)) { buff.append(" <").append(option.getArgName()).append(">"); } // if the Option is not a required option if (!required) { buff.append("]"); } } private static void appendOption(final StringBuffer buff, final Option option, final boolean required) { if (!required) { buff.append("["); } if (option.getOpt() != null) { buff.append("-").append(option.getOpt()); } else { buff.append("--").append(option.getLongOpt()); } // if the Option has a value if (option.hasArg() && option.hasArgName()) { buff.append(" <").append(option.getArgName()).append(">"); } // if the Option is not a required option if (!required) { buff.append("]"); } }
src/java/org/apache/commons/cli/HelpFormatter.java
Cli-12
protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); boolean eatTheRest = false; for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if ("--".equals(arg)) { eatTheRest = true; tokens.add("--"); } else if ("-".equals(arg)) { tokens.add("-"); } else if (arg.startsWith("-")) { String opt = Util.stripLeadingHyphens(arg); if (options.hasOption(opt)) { tokens.add(arg); } else { if (options.hasOption(arg.substring(0, 2))) { // the format is --foo=value or -foo=value // the format is a special properties option (-Dproperty=value) tokens.add(arg.substring(0, 2)); // -D tokens.add(arg.substring(2)); // property=value } else { eatTheRest = stopAtNonOption; tokens.add(arg); } } } else { tokens.add(arg); } if (eatTheRest) { for (i++; i < arguments.length; i++) { tokens.add(arguments[i]); } } } return (String[]) tokens.toArray(new String[tokens.size()]); } protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); boolean eatTheRest = false; for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if ("--".equals(arg)) { eatTheRest = true; tokens.add("--"); } else if ("-".equals(arg)) { tokens.add("-"); } else if (arg.startsWith("-")) { String opt = Util.stripLeadingHyphens(arg); if (options.hasOption(opt)) { tokens.add(arg); } else { if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) { // the format is --foo=value or -foo=value tokens.add(arg.substring(0, arg.indexOf('='))); // --foo tokens.add(arg.substring(arg.indexOf('=') + 1)); // value } else if (options.hasOption(arg.substring(0, 2))) { // the format is a special properties option (-Dproperty=value) tokens.add(arg.substring(0, 2)); // -D tokens.add(arg.substring(2)); // property=value } else { eatTheRest = stopAtNonOption; tokens.add(arg); } } } else { tokens.add(arg); } if (eatTheRest) { for (i++; i < arguments.length; i++) { tokens.add(arguments[i]); } } } return (String[]) tokens.toArray(new String[tokens.size()]); }
src/java/org/apache/commons/cli/GnuParser.java
Cli-14
public void validate(final WriteableCommandLine commandLine) throws OptionException { // number of options found int present = 0; // reference to first unexpected option Option unexpected = null; for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); // needs validation? boolean validate = option.isRequired() || option instanceof Group; if (validate) { option.validate(commandLine); } // if the child option is present then validate it if (commandLine.hasOption(option)) { if (++present > maximum) { unexpected = option; break; } option.validate(commandLine); } } // too many options if (unexpected != null) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, unexpected.getPreferredName()); } // too few option if (present < minimum) { throw new OptionException(this, ResourceConstants.MISSING_OPTION); } // validate each anonymous argument for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.validate(commandLine); } } public void validate(final WriteableCommandLine commandLine) throws OptionException { // number of options found int present = 0; // reference to first unexpected option Option unexpected = null; for (final Iterator i = options.iterator(); i.hasNext();) { final Option option = (Option) i.next(); // needs validation? boolean validate = option.isRequired() || option instanceof Group; // if the child option is present then validate it if (commandLine.hasOption(option)) { if (++present > maximum) { unexpected = option; break; } validate = true; } if (validate) { option.validate(commandLine); } } // too many options if (unexpected != null) { throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN, unexpected.getPreferredName()); } // too few option if (present < minimum) { throw new OptionException(this, ResourceConstants.MISSING_OPTION); } // validate each anonymous argument for (final Iterator i = anonymous.iterator(); i.hasNext();) { final Option option = (Option) i.next(); option.validate(commandLine); } }
src/java/org/apache/commons/cli2/option/GroupImpl.java
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Closure-105
void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right, Node parent) { if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) { return; } Node arrayNode = left.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return; } String joinString = NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = new StringBuilder(); int foldedSize = 0; Node elem = arrayNode.getFirstChild(); // Merges adjacent String nodes. while (elem != null) { if (NodeUtil.isImmutableValue(elem)) { if (sb.length() > 0) { sb.append(joinString); } sb.append(NodeUtil.getStringValue(elem)); } else { if (sb.length() > 0) { // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); sb = new StringBuilder(); } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } elem = elem.getNext(); } if (sb.length() > 0) { // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); } // one for each comma. foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); parent.replaceChild(n, emptyStringNode); break; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { // If the Node is not a string literal, ensure that // it is coerced to a string. Node replacement = new Node(Token.ADD, Node.newString(""), foldedStringNode); foldedStringNode = replacement; } parent.replaceChild(n, foldedStringNode); break; default: // No folding could actually be performed. if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += InlineCostEstimator.getCost(right); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } break; } t.getCompiler().reportCodeChange(); } void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right, Node parent) { if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) { return; } Node arrayNode = left.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return; } String joinString = NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = null; int foldedSize = 0; Node elem = arrayNode.getFirstChild(); // Merges adjacent String nodes. while (elem != null) { if (NodeUtil.isImmutableValue(elem)) { if (sb == null) { sb = new StringBuilder(); } else { sb.append(joinString); } sb.append(NodeUtil.getStringValue(elem)); } else { if (sb != null) { // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); sb = null; } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } elem = elem.getNext(); } if (sb != null) { // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); } // one for each comma. foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); parent.replaceChild(n, emptyStringNode); break; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { // If the Node is not a string literal, ensure that // it is coerced to a string. Node replacement = new Node(Token.ADD, Node.newString(""), foldedStringNode); foldedStringNode = replacement; } parent.replaceChild(n, foldedStringNode); break; default: // No folding could actually be performed. if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += InlineCostEstimator.getCost(right); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } break; } t.getCompiler().reportCodeChange(); }
src/com/google/javascript/jscomp/FoldConstants.java
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
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
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
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
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
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
Closure-114
private void recordAssignment(NodeTraversal t, Node n, Node recordNode) { Node nameNode = n.getFirstChild(); Node parent = n.getParent(); NameInformation ns = createNameInformation(t, nameNode); if (ns != null) { if (parent.isFor() && !NodeUtil.isForIn(parent)) { // Patch for assignments that appear in the init, // condition or iteration part of a FOR loop. Without // this change, all 3 of those parts try to claim the for // loop as their dependency scope. The last assignment in // those three fields wins, which can result in incorrect // reference edges between referenced and assigned variables. // // TODO(user) revisit the dependency scope calculation // logic. if (parent.getFirstChild().getNext() != n) { recordDepScope(recordNode, ns); } else { recordDepScope(nameNode, ns); } } else { // The rhs of the assignment is the caller, so it's used by the // context. Don't associate it w/ the lhs. // FYI: this fixes only the specific case where the assignment is the // caller expression, but it could be nested deeper in the caller and // we would still get a bug. // See testAssignWithCall2 for an example of this. recordDepScope(recordNode, ns); } } } private void recordAssignment(NodeTraversal t, Node n, Node recordNode) { Node nameNode = n.getFirstChild(); Node parent = n.getParent(); NameInformation ns = createNameInformation(t, nameNode); if (ns != null) { if (parent.isFor() && !NodeUtil.isForIn(parent)) { // Patch for assignments that appear in the init, // condition or iteration part of a FOR loop. Without // this change, all 3 of those parts try to claim the for // loop as their dependency scope. The last assignment in // those three fields wins, which can result in incorrect // reference edges between referenced and assigned variables. // // TODO(user) revisit the dependency scope calculation // logic. if (parent.getFirstChild().getNext() != n) { recordDepScope(recordNode, ns); } else { recordDepScope(nameNode, ns); } } else if (!(parent.isCall() && parent.getFirstChild() == n)) { // The rhs of the assignment is the caller, so it's used by the // context. Don't associate it w/ the lhs. // FYI: this fixes only the specific case where the assignment is the // caller expression, but it could be nested deeper in the caller and // we would still get a bug. // See testAssignWithCall2 for an example of this. recordDepScope(recordNode, ns); } } }
src/com/google/javascript/jscomp/NameAnalyzer.java
Closure-115
private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode) { if (!isDirectCallNodeReplacementPossible(fnNode)) { return CanInlineResult.NO; } Node block = fnNode.getLastChild(); boolean hasSideEffects = false; if (block.hasChildren()) { Preconditions.checkState(block.hasOneChild()); Node stmt = block.getFirstChild(); if (stmt.isReturn()) { hasSideEffects = NodeUtil.mayHaveSideEffects(stmt.getFirstChild(), compiler); } } // CALL NODE: [ NAME, ARG1, ARG2, ... ] Node cArg = callNode.getFirstChild().getNext(); // Functions called via 'call' and 'apply' have a this-object as // the first parameter, but this is not part of the called function's // parameter list. if (!callNode.getFirstChild().isName()) { if (NodeUtil.isFunctionObjectCall(callNode)) { // TODO(johnlenz): Support replace this with a value. if (cArg == null || !cArg.isThis()) { return CanInlineResult.NO; } cArg = cArg.getNext(); } else { // ".apply" call should be filtered before this. Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode)); } } // FUNCTION NODE -> LP NODE: [ ARG1, ARG2, ... ] Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); while (cArg != null || fnParam != null) { // For each named parameter check if a mutable argument use more than one. if (fnParam != null) { if (cArg != null) { if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) { return CanInlineResult.NO; } // Check for arguments that are evaluated more than once. // Note: Unlike block inlining, there it is not possible that a // parameter reference will be in a loop. if (NodeUtil.mayEffectMutableState(cArg, compiler) && NodeUtil.getNameReferenceCount( block, fnParam.getString()) > 1) { return CanInlineResult.NO; } } // Move to the next name. fnParam = fnParam.getNext(); } // For every call argument check for side-effects, even if there // isn't a named parameter to match. if (cArg != null) { if (NodeUtil.mayHaveSideEffects(cArg, compiler)) { return CanInlineResult.NO; } cArg = cArg.getNext(); } } return CanInlineResult.YES; } private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode) { if (!isDirectCallNodeReplacementPossible(fnNode)) { return CanInlineResult.NO; } Node block = fnNode.getLastChild(); // CALL NODE: [ NAME, ARG1, ARG2, ... ] Node cArg = callNode.getFirstChild().getNext(); // Functions called via 'call' and 'apply' have a this-object as // the first parameter, but this is not part of the called function's // parameter list. if (!callNode.getFirstChild().isName()) { if (NodeUtil.isFunctionObjectCall(callNode)) { // TODO(johnlenz): Support replace this with a value. if (cArg == null || !cArg.isThis()) { return CanInlineResult.NO; } cArg = cArg.getNext(); } else { // ".apply" call should be filtered before this. Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode)); } } // FUNCTION NODE -> LP NODE: [ ARG1, ARG2, ... ] Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); while (cArg != null || fnParam != null) { // For each named parameter check if a mutable argument use more than one. if (fnParam != null) { if (cArg != null) { // Check for arguments that are evaluated more than once. // Note: Unlike block inlining, there it is not possible that a // parameter reference will be in a loop. if (NodeUtil.mayEffectMutableState(cArg, compiler) && NodeUtil.getNameReferenceCount( block, fnParam.getString()) > 1) { return CanInlineResult.NO; } } // Move to the next name. fnParam = fnParam.getNext(); } // For every call argument check for side-effects, even if there // isn't a named parameter to match. if (cArg != null) { if (NodeUtil.mayHaveSideEffects(cArg, compiler)) { return CanInlineResult.NO; } cArg = cArg.getNext(); } } return CanInlineResult.YES; }
src/com/google/javascript/jscomp/FunctionInjector.java
Closure-116
private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode) { if (!isDirectCallNodeReplacementPossible(fnNode)) { return CanInlineResult.NO; } Node block = fnNode.getLastChild(); // CALL NODE: [ NAME, ARG1, ARG2, ... ] Node cArg = callNode.getFirstChild().getNext(); // Functions called via 'call' and 'apply' have a this-object as // the first parameter, but this is not part of the called function's // parameter list. if (!callNode.getFirstChild().isName()) { if (NodeUtil.isFunctionObjectCall(callNode)) { // TODO(johnlenz): Support replace this with a value. if (cArg == null || !cArg.isThis()) { return CanInlineResult.NO; } cArg = cArg.getNext(); } else { // ".apply" call should be filtered before this. Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode)); } } // FUNCTION NODE -> LP NODE: [ ARG1, ARG2, ... ] Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); while (cArg != null || fnParam != null) { // For each named parameter check if a mutable argument use more than one. if (fnParam != null) { if (cArg != null) { // Check for arguments that are evaluated more than once. // Note: Unlike block inlining, there it is not possible that a // parameter reference will be in a loop. if (NodeUtil.mayEffectMutableState(cArg, compiler) && NodeUtil.getNameReferenceCount( block, fnParam.getString()) > 1) { return CanInlineResult.NO; } } // Move to the next name. fnParam = fnParam.getNext(); } // For every call argument check for side-effects, even if there // isn't a named parameter to match. if (cArg != null) { if (NodeUtil.mayHaveSideEffects(cArg, compiler)) { return CanInlineResult.NO; } cArg = cArg.getNext(); } } return CanInlineResult.YES; } private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode) { if (!isDirectCallNodeReplacementPossible(fnNode)) { return CanInlineResult.NO; } Node block = fnNode.getLastChild(); boolean hasSideEffects = false; // empty function case if (block.hasChildren()) { Preconditions.checkState(block.hasOneChild()); Node stmt = block.getFirstChild(); if (stmt.isReturn()) { hasSideEffects = NodeUtil.mayHaveSideEffects( stmt.getFirstChild(), compiler); } } // CALL NODE: [ NAME, ARG1, ARG2, ... ] Node cArg = callNode.getFirstChild().getNext(); // Functions called via 'call' and 'apply' have a this-object as // the first parameter, but this is not part of the called function's // parameter list. if (!callNode.getFirstChild().isName()) { if (NodeUtil.isFunctionObjectCall(callNode)) { // TODO(johnlenz): Support replace this with a value. if (cArg == null || !cArg.isThis()) { return CanInlineResult.NO; } cArg = cArg.getNext(); } else { // ".apply" call should be filtered before this. Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode)); } } // FUNCTION NODE -> LP NODE: [ ARG1, ARG2, ... ] Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); while (cArg != null || fnParam != null) { // For each named parameter check if a mutable argument use more than one. if (fnParam != null) { if (cArg != null) { if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) { return CanInlineResult.NO; } // Check for arguments that are evaluated more than once. // Note: Unlike block inlining, there it is not possible that a // parameter reference will be in a loop. if (NodeUtil.mayEffectMutableState(cArg, compiler) && NodeUtil.getNameReferenceCount( block, fnParam.getString()) > 1) { return CanInlineResult.NO; } } // Move to the next name. fnParam = fnParam.getNext(); } // For every call argument check for side-effects, even if there // isn't a named parameter to match. if (cArg != null) { if (NodeUtil.mayHaveSideEffects(cArg, compiler)) { return CanInlineResult.NO; } cArg = cArg.getNext(); } } return CanInlineResult.YES; }
src/com/google/javascript/jscomp/FunctionInjector.java
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
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
Closure-119
public void collect(JSModule module, Scope scope, Node n) { Node parent = n.getParent(); String name; boolean isSet = false; Name.Type type = Name.Type.OTHER; boolean isPropAssign = false; switch (n.getType()) { case Token.GETTER_DEF: case Token.SETTER_DEF: case Token.STRING_KEY: // This may be a key in an object literal declaration. name = null; if (parent != null && parent.isObjectLit()) { name = getNameForObjLitKey(n); } if (name == null) { return; } isSet = true; switch (n.getType()) { case Token.STRING_KEY: type = getValueType(n.getFirstChild()); break; case Token.GETTER_DEF: type = Name.Type.GET; break; case Token.SETTER_DEF: type = Name.Type.SET; break; default: throw new IllegalStateException("unexpected:" + n); } break; case Token.NAME: // This may be a variable get or set. if (parent != null) { switch (parent.getType()) { case Token.VAR: isSet = true; Node rvalue = n.getFirstChild(); type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue); break; case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); } break; case Token.GETPROP: return; case Token.FUNCTION: Node gramps = parent.getParent(); if (gramps == null || NodeUtil.isFunctionExpression(parent)) { return; } isSet = true; type = Name.Type.FUNCTION; break; case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getString(); break; case Token.GETPROP: // This may be a namespaced name get or set. if (parent != null) { switch (parent.getType()) { case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); isPropAssign = true; } break; case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; case Token.GETPROP: return; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getQualifiedName(); if (name == null) { return; } break; default: return; } // We are only interested in global names. if (!isGlobalNameReference(name, scope)) { return; } if (isSet) { if (isGlobalScope(scope)) { handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type); } else { handleSetFromLocal(module, scope, n, parent, name); } } else { handleGet(module, scope, n, parent, name); } } public void collect(JSModule module, Scope scope, Node n) { Node parent = n.getParent(); String name; boolean isSet = false; Name.Type type = Name.Type.OTHER; boolean isPropAssign = false; switch (n.getType()) { case Token.GETTER_DEF: case Token.SETTER_DEF: case Token.STRING_KEY: // This may be a key in an object literal declaration. name = null; if (parent != null && parent.isObjectLit()) { name = getNameForObjLitKey(n); } if (name == null) { return; } isSet = true; switch (n.getType()) { case Token.STRING_KEY: type = getValueType(n.getFirstChild()); break; case Token.GETTER_DEF: type = Name.Type.GET; break; case Token.SETTER_DEF: type = Name.Type.SET; break; default: throw new IllegalStateException("unexpected:" + n); } break; case Token.NAME: // This may be a variable get or set. if (parent != null) { switch (parent.getType()) { case Token.VAR: isSet = true; Node rvalue = n.getFirstChild(); type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue); break; case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); } break; case Token.GETPROP: return; case Token.FUNCTION: Node gramps = parent.getParent(); if (gramps == null || NodeUtil.isFunctionExpression(parent)) { return; } isSet = true; type = Name.Type.FUNCTION; break; case Token.CATCH: case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getString(); break; case Token.GETPROP: // This may be a namespaced name get or set. if (parent != null) { switch (parent.getType()) { case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); isPropAssign = true; } break; case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; case Token.GETPROP: return; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getQualifiedName(); if (name == null) { return; } break; default: return; } // We are only interested in global names. if (!isGlobalNameReference(name, scope)) { return; } if (isSet) { if (isGlobalScope(scope)) { handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type); } else { handleSetFromLocal(module, scope, n, parent, name); } } else { handleGet(module, scope, n, parent, name); } }
src/com/google/javascript/jscomp/GlobalNamespace.java
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
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
Closure-121
private void inlineNonConstants( Var v, ReferenceCollection referenceInfo, boolean maybeModifiedArguments) { int refCount = referenceInfo.references.size(); Reference declaration = referenceInfo.references.get(0); Reference init = referenceInfo.getInitializingReference(); int firstRefAfterInit = (declaration == init) ? 2 : 3; if (refCount > 1 && isImmutableAndWellDefinedVariable(v, referenceInfo)) { // if the variable is referenced more than once, we can only // inline it if it's immutable and never defined before referenced. Node value; if (init != null) { value = init.getAssignedValue(); } else { // Create a new node for variable that is never initialized. Node srcLocation = declaration.getNode(); value = NodeUtil.newUndefinedNode(srcLocation); } Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } else if (refCount == firstRefAfterInit) { // The variable likely only read once, try some more // complex inlining heuristics. Reference reference = referenceInfo.references.get( firstRefAfterInit - 1); if (canInline(declaration, init, reference)) { inline(v, declaration, init, reference); staleVars.add(v); } } else if (declaration != init && refCount == 2) { if (isValidDeclaration(declaration) && isValidInitialization(init)) { // The only reference is the initialization, remove the assignment and // the variable declaration. Node value = init.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } } // If this variable was not inlined normally, check if we can // inline an alias of it. (If the variable was inlined, then the // reference data is out of sync. We're better off just waiting for // the next pass.) if (!maybeModifiedArguments && !staleVars.contains(v) && referenceInfo.isWellDefined() && referenceInfo.isAssignedOnceInLifetime()) { // Inlining the variable based solely on well-defined and assigned // once is *NOT* correct. We relax the correctness requirement if // the variable is declared constant. List<Reference> refs = referenceInfo.references; for (int i = 1 /* start from a read */; i < refs.size(); i++) { Node nameNode = refs.get(i).getNode(); if (aliasCandidates.containsKey(nameNode)) { AliasCandidate candidate = aliasCandidates.get(nameNode); if (!staleVars.contains(candidate.alias) && !isVarInlineForbidden(candidate.alias)) { Reference aliasInit; aliasInit = candidate.refInfo.getInitializingReference(); Node value = aliasInit.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(candidate.alias, value, candidate.refInfo.references); staleVars.add(candidate.alias); } } } } } private void inlineNonConstants( Var v, ReferenceCollection referenceInfo, boolean maybeModifiedArguments) { int refCount = referenceInfo.references.size(); Reference declaration = referenceInfo.references.get(0); Reference init = referenceInfo.getInitializingReference(); int firstRefAfterInit = (declaration == init) ? 2 : 3; if (refCount > 1 && isImmutableAndWellDefinedVariable(v, referenceInfo)) { // if the variable is referenced more than once, we can only // inline it if it's immutable and never defined before referenced. Node value; if (init != null) { value = init.getAssignedValue(); } else { // Create a new node for variable that is never initialized. Node srcLocation = declaration.getNode(); value = NodeUtil.newUndefinedNode(srcLocation); } Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } else if (refCount == firstRefAfterInit) { // The variable likely only read once, try some more // complex inlining heuristics. Reference reference = referenceInfo.references.get( firstRefAfterInit - 1); if (canInline(declaration, init, reference)) { inline(v, declaration, init, reference); staleVars.add(v); } } else if (declaration != init && refCount == 2) { if (isValidDeclaration(declaration) && isValidInitialization(init)) { // The only reference is the initialization, remove the assignment and // the variable declaration. Node value = init.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } } // If this variable was not inlined normally, check if we can // inline an alias of it. (If the variable was inlined, then the // reference data is out of sync. We're better off just waiting for // the next pass.) if (!maybeModifiedArguments && !staleVars.contains(v) && referenceInfo.isWellDefined() && referenceInfo.isAssignedOnceInLifetime() && // Inlining the variable based solely on well-defined and assigned // once is *NOT* correct. We relax the correctness requirement if // the variable is declared constant. (isInlineableDeclaredConstant(v, referenceInfo) || referenceInfo.isOnlyAssignmentSameScopeAsDeclaration())) { List<Reference> refs = referenceInfo.references; for (int i = 1 /* start from a read */; i < refs.size(); i++) { Node nameNode = refs.get(i).getNode(); if (aliasCandidates.containsKey(nameNode)) { AliasCandidate candidate = aliasCandidates.get(nameNode); if (!staleVars.contains(candidate.alias) && !isVarInlineForbidden(candidate.alias)) { Reference aliasInit; aliasInit = candidate.refInfo.getInitializingReference(); Node value = aliasInit.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(candidate.alias, value, candidate.refInfo.references); staleVars.add(candidate.alias); } } } } }
src/com/google/javascript/jscomp/InlineVariables.java
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
Closure-123
void add(Node n, Context context) { if (!cc.continueProcessing()) { return; } int type = n.getType(); String opstr = NodeUtil.opToStr(type); int childCount = n.getChildCount(); Node first = n.getFirstChild(); Node last = n.getLastChild(); // Handle all binary operators if (opstr != null && first != last) { Preconditions.checkState( childCount == 2, "Bad binary operator \"%s\": expected 2 arguments but got %s", opstr, childCount); int p = NodeUtil.precedence(type); // For right-hand-side of operations, only pass context if it's // the IN_FOR_INIT_CLAUSE one. Context rhsContext = getContextForNoInOperator(context); // Handle associativity. // e.g. if the parse tree is a * (b * c), // we can simply generate a * b * c. if (last.getType() == type && NodeUtil.isAssociative(type)) { addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) { // Assignments are the only right-associative binary operators addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else { unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1); } return; } cc.startSourceMapping(n); switch (type) { case Token.TRY: { Preconditions.checkState(first.getNext().isBlock() && !first.getNext().hasMoreThanOneChild()); Preconditions.checkState(childCount >= 2 && childCount <= 3); add("try"); add(first, Context.PRESERVE_BLOCK); // second child contains the catch block, or nothing if there // isn't a catch block Node catchblock = first.getNext().getFirstChild(); if (catchblock != null) { add(catchblock); } if (childCount == 3) { add("finally"); add(last, Context.PRESERVE_BLOCK); } break; } case Token.CATCH: Preconditions.checkState(childCount == 2); add("catch("); add(first); add(")"); add(last, Context.PRESERVE_BLOCK); break; case Token.THROW: Preconditions.checkState(childCount == 1); add("throw"); add(first); // Must have a ';' after a throw statement, otherwise safari can't // parse this. cc.endStatement(true); break; case Token.RETURN: add("return"); if (childCount == 1) { add(first); } else { Preconditions.checkState(childCount == 0); } cc.endStatement(); break; case Token.VAR: if (first != null) { add("var "); addList(first, false, getContextForNoInOperator(context)); } break; case Token.LABEL_NAME: Preconditions.checkState(!n.getString().isEmpty()); addIdentifier(n.getString()); break; case Token.NAME: if (first == null || first.isEmpty()) { addIdentifier(n.getString()); } else { Preconditions.checkState(childCount == 1); addIdentifier(n.getString()); cc.addOp("=", true); if (first.isComma()) { addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER); } else { // Add expression, consider nearby code at lowest level of // precedence. addExpr(first, 0, getContextForNoInOperator(context)); } } break; case Token.ARRAYLIT: add("["); addArrayList(first); add("]"); break; case Token.PARAM_LIST: add("("); addList(first); add(")"); break; case Token.COMMA: Preconditions.checkState(childCount == 2); unrollBinaryOperator(n, Token.COMMA, ",", context, getContextForNoInOperator(context), 0, 0); break; case Token.NUMBER: Preconditions.checkState(childCount == 0); cc.addNumber(n.getDouble()); break; case Token.TYPEOF: case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.POS: { // All of these unary operators are right-associative Preconditions.checkState(childCount == 1); cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); break; } case Token.NEG: { Preconditions.checkState(childCount == 1); // It's important to our sanity checker that the code // we print produces the same AST as the code we parse back. // NEG is a weird case because Rhino parses "- -2" as "2". if (n.getFirstChild().isNumber()) { cc.addNumber(-n.getFirstChild().getDouble()); } else { cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); } break; } case Token.HOOK: { Preconditions.checkState(childCount == 3); int p = NodeUtil.precedence(type); Context rhsContext = Context.OTHER; addExpr(first, p + 1, context); cc.addOp("?", true); addExpr(first.getNext(), 1, rhsContext); cc.addOp(":", true); addExpr(last, 1, rhsContext); break; } case Token.REGEXP: if (!first.isString() || !last.isString()) { throw new Error("Expected children to be strings"); } String regexp = regexpEscape(first.getString(), outputCharsetEncoder); // I only use one .add because whitespace matters if (childCount == 2) { add(regexp + last.getString()); } else { Preconditions.checkState(childCount == 1); add(regexp); } break; case Token.FUNCTION: if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } Preconditions.checkState(childCount == 3); boolean funcNeedsParens = (context == Context.START_OF_EXPR); if (funcNeedsParens) { add("("); } add("function"); add(first); add(first.getNext()); add(last, Context.PRESERVE_BLOCK); cc.endFunction(context == Context.STATEMENT); if (funcNeedsParens) { add(")"); } break; case Token.GETTER_DEF: case Token.SETTER_DEF: Preconditions.checkState(n.getParent().isObjectLit()); Preconditions.checkState(childCount == 1); Preconditions.checkState(first.isFunction()); // Get methods are unnamed Preconditions.checkState(first.getFirstChild().getString().isEmpty()); if (type == Token.GETTER_DEF) { // Get methods have no parameters. Preconditions.checkState(!first.getChildAtIndex(1).hasChildren()); add("get "); } else { // Set methods have one parameter. Preconditions.checkState(first.getChildAtIndex(1).hasOneChild()); add("set "); } // The name is on the GET or SET node. String name = n.getString(); Node fn = first; Node parameters = fn.getChildAtIndex(1); Node body = fn.getLastChild(); // Add the property name. if (!n.isQuotedString() && TokenStream.isJSIdentifier(name) && // do not encode literally any non-literal characters that were // Unicode escaped. NodeUtil.isLatin(name)) { add(name); } else { // Determine if the string is a simple number. double d = getSimpleNumber(name); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addJsString(n); } } add(parameters); add(body, Context.PRESERVE_BLOCK); break; case Token.SCRIPT: case Token.BLOCK: { if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } boolean preserveBlock = context == Context.PRESERVE_BLOCK; if (preserveBlock) { cc.beginBlock(); } boolean preferLineBreaks = type == Token.SCRIPT || (type == Token.BLOCK && !preserveBlock && n.getParent() != null && n.getParent().isScript()); for (Node c = first; c != null; c = c.getNext()) { add(c, Context.STATEMENT); // VAR doesn't include ';' since it gets used in expressions if (c.isVar()) { cc.endStatement(); } if (c.isFunction()) { cc.maybeLineBreak(); } // Prefer to break lines in between top-level statements // because top-level statements are more homogeneous. if (preferLineBreaks) { cc.notePreferredLineBreak(); } } if (preserveBlock) { cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT)); } break; } case Token.FOR: if (childCount == 4) { add("for("); if (first.isVar()) { add(first, Context.IN_FOR_INIT_CLAUSE); } else { addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE); } add(";"); add(first.getNext()); add(";"); add(first.getNext().getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { Preconditions.checkState(childCount == 3); add("for("); add(first); add("in"); add(first.getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } break; case Token.DO: Preconditions.checkState(childCount == 2); add("do"); addNonEmptyStatement(first, Context.OTHER, false); add("while("); add(last); add(")"); cc.endStatement(); break; case Token.WHILE: Preconditions.checkState(childCount == 2); add("while("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.EMPTY: Preconditions.checkState(childCount == 0); break; case Token.GETPROP: { Preconditions.checkState( childCount == 2, "Bad GETPROP: expected 2 children, but got %s", childCount); Preconditions.checkState( last.isString(), "Bad GETPROP: RHS should be STRING"); boolean needsParens = (first.isNumber()); if (needsParens) { add("("); } addExpr(first, NodeUtil.precedence(type), context); if (needsParens) { add(")"); } if (this.languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(last.getString())) { // Check for ECMASCRIPT3 keywords. add("["); add(last); add("]"); } else { add("."); addIdentifier(last.getString()); } break; } case Token.GETELEM: Preconditions.checkState( childCount == 2, "Bad GETELEM: expected 2 children but got %s", childCount); addExpr(first, NodeUtil.precedence(type), context); add("["); add(first.getNext()); add("]"); break; case Token.WITH: Preconditions.checkState(childCount == 2); add("with("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.INC: case Token.DEC: { Preconditions.checkState(childCount == 1); String o = type == Token.INC ? "++" : "--"; int postProp = n.getIntProp(Node.INCRDECR_PROP); // A non-zero post-prop value indicates a post inc/dec, default of zero // is a pre-inc/dec. if (postProp != 0) { addExpr(first, NodeUtil.precedence(type), context); cc.addOp(o, false); } else { cc.addOp(o, false); add(first); } break; } case Token.CALL: // We have two special cases here: // 1) If the left hand side of the call is a direct reference to eval, // then it must have a DIRECT_EVAL annotation. If it does not, then // that means it was originally an indirect call to eval, and that // indirectness must be preserved. // 2) If the left hand side of the call is a property reference, // then the call must not a FREE_CALL annotation. If it does, then // that means it was originally an call without an explicit this and // that must be preserved. if (isIndirectEval(first) || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) { add("(0,"); addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER); add(")"); } else { addExpr(first, NodeUtil.precedence(type), context); } add("("); addList(first.getNext()); add(")"); break; case Token.IF: boolean hasElse = childCount == 3; boolean ambiguousElseClause = context == Context.BEFORE_DANGLING_ELSE && !hasElse; if (ambiguousElseClause) { cc.beginBlock(); } add("if("); add(first); add(")"); if (hasElse) { addNonEmptyStatement( first.getNext(), Context.BEFORE_DANGLING_ELSE, false); add("else"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { addNonEmptyStatement(first.getNext(), Context.OTHER, false); Preconditions.checkState(childCount == 2); } if (ambiguousElseClause) { cc.endBlock(); } break; case Token.NULL: Preconditions.checkState(childCount == 0); cc.addConstant("null"); break; case Token.THIS: Preconditions.checkState(childCount == 0); add("this"); break; case Token.FALSE: Preconditions.checkState(childCount == 0); cc.addConstant("false"); break; case Token.TRUE: Preconditions.checkState(childCount == 0); cc.addConstant("true"); break; case Token.CONTINUE: Preconditions.checkState(childCount <= 1); add("continue"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.DEBUGGER: Preconditions.checkState(childCount == 0); add("debugger"); cc.endStatement(); break; case Token.BREAK: Preconditions.checkState(childCount <= 1); add("break"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.EXPR_RESULT: Preconditions.checkState(childCount == 1); add(first, Context.START_OF_EXPR); cc.endStatement(); break; case Token.NEW: add("new "); int precedence = NodeUtil.precedence(type); // If the first child contains a CALL, then claim higher precedence // to force parentheses. Otherwise, when parsed, NEW will bind to the // first viable parentheses (don't traverse into functions). if (NodeUtil.containsType( first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) { precedence = NodeUtil.precedence(first.getType()) + 1; } addExpr(first, precedence, Context.OTHER); // '()' is optional when no arguments are present Node next = first.getNext(); if (next != null) { add("("); addList(next); add(")"); } break; case Token.STRING_KEY: Preconditions.checkState( childCount == 1, "Object lit key must have 1 child"); addJsString(n); break; case Token.STRING: Preconditions.checkState( childCount == 0, "A string may not have children"); addJsString(n); break; case Token.DELPROP: Preconditions.checkState(childCount == 1); add("delete "); add(first); break; case Token.OBJECTLIT: { boolean needsParens = (context == Context.START_OF_EXPR); if (needsParens) { add("("); } add("{"); for (Node c = first; c != null; c = c.getNext()) { if (c != first) { cc.listSeparator(); } if (c.isGetterDef() || c.isSetterDef()) { add(c); } else { Preconditions.checkState(c.isStringKey()); String key = c.getString(); // Object literal property names don't have to be quoted if they // are not JavaScript keywords if (!c.isQuotedString() && !(languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(key)) && TokenStream.isJSIdentifier(key) // do not encode literally any non-literal characters that // were Unicode escaped. && NodeUtil.isLatin(key)) { add(key); } else { // Determine if the string is a simple number. double d = getSimpleNumber(key); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addExpr(c, 1, Context.OTHER); } } add(":"); addExpr(c.getFirstChild(), 1, Context.OTHER); } } add("}"); if (needsParens) { add(")"); } break; } case Token.SWITCH: add("switch("); add(first); add(")"); cc.beginBlock(); addAllSiblings(first.getNext()); cc.endBlock(context == Context.STATEMENT); break; case Token.CASE: Preconditions.checkState(childCount == 2); add("case "); add(first); addCaseBody(last); break; case Token.DEFAULT_CASE: Preconditions.checkState(childCount == 1); add("default"); addCaseBody(first); break; case Token.LABEL: Preconditions.checkState(childCount == 2); if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(first); add(":"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), true); break; case Token.CAST: add("("); add(first); add(")"); break; default: throw new Error("Unknown type " + type + "\n" + n.toStringTree()); } cc.endSourceMapping(n); } void add(Node n, Context context) { if (!cc.continueProcessing()) { return; } int type = n.getType(); String opstr = NodeUtil.opToStr(type); int childCount = n.getChildCount(); Node first = n.getFirstChild(); Node last = n.getLastChild(); // Handle all binary operators if (opstr != null && first != last) { Preconditions.checkState( childCount == 2, "Bad binary operator \"%s\": expected 2 arguments but got %s", opstr, childCount); int p = NodeUtil.precedence(type); // For right-hand-side of operations, only pass context if it's // the IN_FOR_INIT_CLAUSE one. Context rhsContext = getContextForNoInOperator(context); // Handle associativity. // e.g. if the parse tree is a * (b * c), // we can simply generate a * b * c. if (last.getType() == type && NodeUtil.isAssociative(type)) { addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) { // Assignments are the only right-associative binary operators addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else { unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1); } return; } cc.startSourceMapping(n); switch (type) { case Token.TRY: { Preconditions.checkState(first.getNext().isBlock() && !first.getNext().hasMoreThanOneChild()); Preconditions.checkState(childCount >= 2 && childCount <= 3); add("try"); add(first, Context.PRESERVE_BLOCK); // second child contains the catch block, or nothing if there // isn't a catch block Node catchblock = first.getNext().getFirstChild(); if (catchblock != null) { add(catchblock); } if (childCount == 3) { add("finally"); add(last, Context.PRESERVE_BLOCK); } break; } case Token.CATCH: Preconditions.checkState(childCount == 2); add("catch("); add(first); add(")"); add(last, Context.PRESERVE_BLOCK); break; case Token.THROW: Preconditions.checkState(childCount == 1); add("throw"); add(first); // Must have a ';' after a throw statement, otherwise safari can't // parse this. cc.endStatement(true); break; case Token.RETURN: add("return"); if (childCount == 1) { add(first); } else { Preconditions.checkState(childCount == 0); } cc.endStatement(); break; case Token.VAR: if (first != null) { add("var "); addList(first, false, getContextForNoInOperator(context)); } break; case Token.LABEL_NAME: Preconditions.checkState(!n.getString().isEmpty()); addIdentifier(n.getString()); break; case Token.NAME: if (first == null || first.isEmpty()) { addIdentifier(n.getString()); } else { Preconditions.checkState(childCount == 1); addIdentifier(n.getString()); cc.addOp("=", true); if (first.isComma()) { addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER); } else { // Add expression, consider nearby code at lowest level of // precedence. addExpr(first, 0, getContextForNoInOperator(context)); } } break; case Token.ARRAYLIT: add("["); addArrayList(first); add("]"); break; case Token.PARAM_LIST: add("("); addList(first); add(")"); break; case Token.COMMA: Preconditions.checkState(childCount == 2); unrollBinaryOperator(n, Token.COMMA, ",", context, getContextForNoInOperator(context), 0, 0); break; case Token.NUMBER: Preconditions.checkState(childCount == 0); cc.addNumber(n.getDouble()); break; case Token.TYPEOF: case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.POS: { // All of these unary operators are right-associative Preconditions.checkState(childCount == 1); cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); break; } case Token.NEG: { Preconditions.checkState(childCount == 1); // It's important to our sanity checker that the code // we print produces the same AST as the code we parse back. // NEG is a weird case because Rhino parses "- -2" as "2". if (n.getFirstChild().isNumber()) { cc.addNumber(-n.getFirstChild().getDouble()); } else { cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); } break; } case Token.HOOK: { Preconditions.checkState(childCount == 3); int p = NodeUtil.precedence(type); Context rhsContext = getContextForNoInOperator(context); addExpr(first, p + 1, context); cc.addOp("?", true); addExpr(first.getNext(), 1, rhsContext); cc.addOp(":", true); addExpr(last, 1, rhsContext); break; } case Token.REGEXP: if (!first.isString() || !last.isString()) { throw new Error("Expected children to be strings"); } String regexp = regexpEscape(first.getString(), outputCharsetEncoder); // I only use one .add because whitespace matters if (childCount == 2) { add(regexp + last.getString()); } else { Preconditions.checkState(childCount == 1); add(regexp); } break; case Token.FUNCTION: if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } Preconditions.checkState(childCount == 3); boolean funcNeedsParens = (context == Context.START_OF_EXPR); if (funcNeedsParens) { add("("); } add("function"); add(first); add(first.getNext()); add(last, Context.PRESERVE_BLOCK); cc.endFunction(context == Context.STATEMENT); if (funcNeedsParens) { add(")"); } break; case Token.GETTER_DEF: case Token.SETTER_DEF: Preconditions.checkState(n.getParent().isObjectLit()); Preconditions.checkState(childCount == 1); Preconditions.checkState(first.isFunction()); // Get methods are unnamed Preconditions.checkState(first.getFirstChild().getString().isEmpty()); if (type == Token.GETTER_DEF) { // Get methods have no parameters. Preconditions.checkState(!first.getChildAtIndex(1).hasChildren()); add("get "); } else { // Set methods have one parameter. Preconditions.checkState(first.getChildAtIndex(1).hasOneChild()); add("set "); } // The name is on the GET or SET node. String name = n.getString(); Node fn = first; Node parameters = fn.getChildAtIndex(1); Node body = fn.getLastChild(); // Add the property name. if (!n.isQuotedString() && TokenStream.isJSIdentifier(name) && // do not encode literally any non-literal characters that were // Unicode escaped. NodeUtil.isLatin(name)) { add(name); } else { // Determine if the string is a simple number. double d = getSimpleNumber(name); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addJsString(n); } } add(parameters); add(body, Context.PRESERVE_BLOCK); break; case Token.SCRIPT: case Token.BLOCK: { if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } boolean preserveBlock = context == Context.PRESERVE_BLOCK; if (preserveBlock) { cc.beginBlock(); } boolean preferLineBreaks = type == Token.SCRIPT || (type == Token.BLOCK && !preserveBlock && n.getParent() != null && n.getParent().isScript()); for (Node c = first; c != null; c = c.getNext()) { add(c, Context.STATEMENT); // VAR doesn't include ';' since it gets used in expressions if (c.isVar()) { cc.endStatement(); } if (c.isFunction()) { cc.maybeLineBreak(); } // Prefer to break lines in between top-level statements // because top-level statements are more homogeneous. if (preferLineBreaks) { cc.notePreferredLineBreak(); } } if (preserveBlock) { cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT)); } break; } case Token.FOR: if (childCount == 4) { add("for("); if (first.isVar()) { add(first, Context.IN_FOR_INIT_CLAUSE); } else { addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE); } add(";"); add(first.getNext()); add(";"); add(first.getNext().getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { Preconditions.checkState(childCount == 3); add("for("); add(first); add("in"); add(first.getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } break; case Token.DO: Preconditions.checkState(childCount == 2); add("do"); addNonEmptyStatement(first, Context.OTHER, false); add("while("); add(last); add(")"); cc.endStatement(); break; case Token.WHILE: Preconditions.checkState(childCount == 2); add("while("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.EMPTY: Preconditions.checkState(childCount == 0); break; case Token.GETPROP: { Preconditions.checkState( childCount == 2, "Bad GETPROP: expected 2 children, but got %s", childCount); Preconditions.checkState( last.isString(), "Bad GETPROP: RHS should be STRING"); boolean needsParens = (first.isNumber()); if (needsParens) { add("("); } addExpr(first, NodeUtil.precedence(type), context); if (needsParens) { add(")"); } if (this.languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(last.getString())) { // Check for ECMASCRIPT3 keywords. add("["); add(last); add("]"); } else { add("."); addIdentifier(last.getString()); } break; } case Token.GETELEM: Preconditions.checkState( childCount == 2, "Bad GETELEM: expected 2 children but got %s", childCount); addExpr(first, NodeUtil.precedence(type), context); add("["); add(first.getNext()); add("]"); break; case Token.WITH: Preconditions.checkState(childCount == 2); add("with("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.INC: case Token.DEC: { Preconditions.checkState(childCount == 1); String o = type == Token.INC ? "++" : "--"; int postProp = n.getIntProp(Node.INCRDECR_PROP); // A non-zero post-prop value indicates a post inc/dec, default of zero // is a pre-inc/dec. if (postProp != 0) { addExpr(first, NodeUtil.precedence(type), context); cc.addOp(o, false); } else { cc.addOp(o, false); add(first); } break; } case Token.CALL: // We have two special cases here: // 1) If the left hand side of the call is a direct reference to eval, // then it must have a DIRECT_EVAL annotation. If it does not, then // that means it was originally an indirect call to eval, and that // indirectness must be preserved. // 2) If the left hand side of the call is a property reference, // then the call must not a FREE_CALL annotation. If it does, then // that means it was originally an call without an explicit this and // that must be preserved. if (isIndirectEval(first) || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) { add("(0,"); addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER); add(")"); } else { addExpr(first, NodeUtil.precedence(type), context); } add("("); addList(first.getNext()); add(")"); break; case Token.IF: boolean hasElse = childCount == 3; boolean ambiguousElseClause = context == Context.BEFORE_DANGLING_ELSE && !hasElse; if (ambiguousElseClause) { cc.beginBlock(); } add("if("); add(first); add(")"); if (hasElse) { addNonEmptyStatement( first.getNext(), Context.BEFORE_DANGLING_ELSE, false); add("else"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { addNonEmptyStatement(first.getNext(), Context.OTHER, false); Preconditions.checkState(childCount == 2); } if (ambiguousElseClause) { cc.endBlock(); } break; case Token.NULL: Preconditions.checkState(childCount == 0); cc.addConstant("null"); break; case Token.THIS: Preconditions.checkState(childCount == 0); add("this"); break; case Token.FALSE: Preconditions.checkState(childCount == 0); cc.addConstant("false"); break; case Token.TRUE: Preconditions.checkState(childCount == 0); cc.addConstant("true"); break; case Token.CONTINUE: Preconditions.checkState(childCount <= 1); add("continue"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.DEBUGGER: Preconditions.checkState(childCount == 0); add("debugger"); cc.endStatement(); break; case Token.BREAK: Preconditions.checkState(childCount <= 1); add("break"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.EXPR_RESULT: Preconditions.checkState(childCount == 1); add(first, Context.START_OF_EXPR); cc.endStatement(); break; case Token.NEW: add("new "); int precedence = NodeUtil.precedence(type); // If the first child contains a CALL, then claim higher precedence // to force parentheses. Otherwise, when parsed, NEW will bind to the // first viable parentheses (don't traverse into functions). if (NodeUtil.containsType( first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) { precedence = NodeUtil.precedence(first.getType()) + 1; } addExpr(first, precedence, Context.OTHER); // '()' is optional when no arguments are present Node next = first.getNext(); if (next != null) { add("("); addList(next); add(")"); } break; case Token.STRING_KEY: Preconditions.checkState( childCount == 1, "Object lit key must have 1 child"); addJsString(n); break; case Token.STRING: Preconditions.checkState( childCount == 0, "A string may not have children"); addJsString(n); break; case Token.DELPROP: Preconditions.checkState(childCount == 1); add("delete "); add(first); break; case Token.OBJECTLIT: { boolean needsParens = (context == Context.START_OF_EXPR); if (needsParens) { add("("); } add("{"); for (Node c = first; c != null; c = c.getNext()) { if (c != first) { cc.listSeparator(); } if (c.isGetterDef() || c.isSetterDef()) { add(c); } else { Preconditions.checkState(c.isStringKey()); String key = c.getString(); // Object literal property names don't have to be quoted if they // are not JavaScript keywords if (!c.isQuotedString() && !(languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(key)) && TokenStream.isJSIdentifier(key) // do not encode literally any non-literal characters that // were Unicode escaped. && NodeUtil.isLatin(key)) { add(key); } else { // Determine if the string is a simple number. double d = getSimpleNumber(key); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addExpr(c, 1, Context.OTHER); } } add(":"); addExpr(c.getFirstChild(), 1, Context.OTHER); } } add("}"); if (needsParens) { add(")"); } break; } case Token.SWITCH: add("switch("); add(first); add(")"); cc.beginBlock(); addAllSiblings(first.getNext()); cc.endBlock(context == Context.STATEMENT); break; case Token.CASE: Preconditions.checkState(childCount == 2); add("case "); add(first); addCaseBody(last); break; case Token.DEFAULT_CASE: Preconditions.checkState(childCount == 1); add("default"); addCaseBody(first); break; case Token.LABEL: Preconditions.checkState(childCount == 2); if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(first); add(":"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), true); break; case Token.CAST: add("("); add(first); add(")"); break; default: throw new Error("Unknown type " + type + "\n" + n.toStringTree()); } cc.endSourceMapping(n); }
src/com/google/javascript/jscomp/CodeGenerator.java
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
Closure-125
private void visitNew(NodeTraversal t, Node n) { Node constructor = n.getFirstChild(); JSType type = getJSType(constructor).restrictByNotNullOrUndefined(); if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) { FunctionType fnType = type.toMaybeFunctionType(); if (fnType != null) { visitParameterList(t, n, fnType); ensureTyped(t, n, fnType.getInstanceType()); } else { ensureTyped(t, n); } } else { report(t, n, NOT_A_CONSTRUCTOR); ensureTyped(t, n); } } private void visitNew(NodeTraversal t, Node n) { Node constructor = n.getFirstChild(); JSType type = getJSType(constructor).restrictByNotNullOrUndefined(); if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) { FunctionType fnType = type.toMaybeFunctionType(); if (fnType != null && fnType.hasInstanceType()) { visitParameterList(t, n, fnType); ensureTyped(t, n, fnType.getInstanceType()); } else { ensureTyped(t, n); } } else { report(t, n, NOT_A_CONSTRUCTOR); ensureTyped(t, n); } }
src/com/google/javascript/jscomp/TypeCheck.java
Closure-126
void tryMinimizeExits(Node n, int exitType, String labelName) { // Just an 'exit'. if (matchingExitNode(n, exitType, labelName)) { NodeUtil.removeChild(n.getParent(), n); compiler.reportCodeChange(); return; } // Just an 'if'. if (n.isIf()) { Node ifBlock = n.getFirstChild().getNext(); tryMinimizeExits(ifBlock, exitType, labelName); Node elseBlock = ifBlock.getNext(); if (elseBlock != null) { tryMinimizeExits(elseBlock, exitType, labelName); } return; } // Just a 'try/catch/finally'. if (n.isTry()) { Node tryBlock = n.getFirstChild(); tryMinimizeExits(tryBlock, exitType, labelName); Node allCatchNodes = NodeUtil.getCatchBlock(n); if (NodeUtil.hasCatchHandler(allCatchNodes)) { Preconditions.checkState(allCatchNodes.hasOneChild()); Node catchNode = allCatchNodes.getFirstChild(); Node catchCodeBlock = catchNode.getLastChild(); tryMinimizeExits(catchCodeBlock, exitType, labelName); } /* Don't try to minimize the exits of finally blocks, as this * can cause problems if it changes the completion type of the finally * block. See ECMA 262 Sections 8.9 & 12.14 */ if (NodeUtil.hasFinally(n)) { Node finallyBlock = n.getLastChild(); tryMinimizeExits(finallyBlock, exitType, labelName); } } // Just a 'label'. if (n.isLabel()) { Node labelBlock = n.getLastChild(); tryMinimizeExits(labelBlock, exitType, labelName); } // TODO(johnlenz): The last case of SWITCH statement? // The rest assumes a block with at least one child, bail on anything else. if (!n.isBlock() || n.getLastChild() == null) { return; } // Multiple if-exits can be converted in a single pass. // Convert "if (blah) break; if (blah2) break; other_stmt;" to // become "if (blah); else { if (blah2); else { other_stmt; } }" // which will get converted to "if (!blah && !blah2) { other_stmt; }". for (Node c : n.children()) { // An 'if' block to process below. if (c.isIf()) { Node ifTree = c; Node trueBlock, falseBlock; // First, the true condition block. trueBlock = ifTree.getFirstChild().getNext(); falseBlock = trueBlock.getNext(); tryMinimizeIfBlockExits(trueBlock, falseBlock, ifTree, exitType, labelName); // Now the else block. // The if blocks may have changed, get them again. trueBlock = ifTree.getFirstChild().getNext(); falseBlock = trueBlock.getNext(); if (falseBlock != null) { tryMinimizeIfBlockExits(falseBlock, trueBlock, ifTree, exitType, labelName); } } if (c == n.getLastChild()) { break; } } // Now try to minimize the exits of the last child, if it is removed // look at what has become the last child. for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) { tryMinimizeExits(c, exitType, labelName); // If the node is still the last child, we are done. if (c == n.getLastChild()) { break; } } } void tryMinimizeExits(Node n, int exitType, String labelName) { // Just an 'exit'. if (matchingExitNode(n, exitType, labelName)) { NodeUtil.removeChild(n.getParent(), n); compiler.reportCodeChange(); return; } // Just an 'if'. if (n.isIf()) { Node ifBlock = n.getFirstChild().getNext(); tryMinimizeExits(ifBlock, exitType, labelName); Node elseBlock = ifBlock.getNext(); if (elseBlock != null) { tryMinimizeExits(elseBlock, exitType, labelName); } return; } // Just a 'try/catch/finally'. if (n.isTry()) { Node tryBlock = n.getFirstChild(); tryMinimizeExits(tryBlock, exitType, labelName); Node allCatchNodes = NodeUtil.getCatchBlock(n); if (NodeUtil.hasCatchHandler(allCatchNodes)) { Preconditions.checkState(allCatchNodes.hasOneChild()); Node catchNode = allCatchNodes.getFirstChild(); Node catchCodeBlock = catchNode.getLastChild(); tryMinimizeExits(catchCodeBlock, exitType, labelName); } /* Don't try to minimize the exits of finally blocks, as this * can cause problems if it changes the completion type of the finally * block. See ECMA 262 Sections 8.9 & 12.14 */ } // Just a 'label'. if (n.isLabel()) { Node labelBlock = n.getLastChild(); tryMinimizeExits(labelBlock, exitType, labelName); } // TODO(johnlenz): The last case of SWITCH statement? // The rest assumes a block with at least one child, bail on anything else. if (!n.isBlock() || n.getLastChild() == null) { return; } // Multiple if-exits can be converted in a single pass. // Convert "if (blah) break; if (blah2) break; other_stmt;" to // become "if (blah); else { if (blah2); else { other_stmt; } }" // which will get converted to "if (!blah && !blah2) { other_stmt; }". for (Node c : n.children()) { // An 'if' block to process below. if (c.isIf()) { Node ifTree = c; Node trueBlock, falseBlock; // First, the true condition block. trueBlock = ifTree.getFirstChild().getNext(); falseBlock = trueBlock.getNext(); tryMinimizeIfBlockExits(trueBlock, falseBlock, ifTree, exitType, labelName); // Now the else block. // The if blocks may have changed, get them again. trueBlock = ifTree.getFirstChild().getNext(); falseBlock = trueBlock.getNext(); if (falseBlock != null) { tryMinimizeIfBlockExits(falseBlock, trueBlock, ifTree, exitType, labelName); } } if (c == n.getLastChild()) { break; } } // Now try to minimize the exits of the last child, if it is removed // look at what has become the last child. for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) { tryMinimizeExits(c, exitType, labelName); // If the node is still the last child, we are done. if (c == n.getLastChild()) { break; } } }
src/com/google/javascript/jscomp/MinimizeExitPoints.java
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
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
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
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
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
Closure-132
private Node tryMinimizeIf(Node n) { Node parent = n.getParent(); Node cond = n.getFirstChild(); /* If the condition is a literal, we'll let other * optimizations try to remove useless code. */ if (NodeUtil.isLiteralValue(cond, true)) { return n; } Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); if (elseBranch == null) { if (isFoldableExpressBlock(thenBranch)) { Node expr = getBlockExpression(thenBranch); if (!late && isPropertyAssignmentInExpression(expr)) { // Keep opportunities for CollapseProperties such as // a.longIdentifier || a.longIdentifier = ... -> var a = ...; // until CollapseProperties has been run. return n; } if (cond.isNot()) { // if(!x)bar(); -> x||bar(); if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), OR_PRECEDENCE)) { // It's not okay to add two sets of parentheses. return n; } Node or = IR.or( cond.removeFirstChild(), expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(or); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } // if(x)foo(); -> x&&foo(); if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), AND_PRECEDENCE)) { // One additional set of parentheses is worth the change even if // there is no immediate code size win. However, two extra pair of // {}, we would have to think twice. (unless we know for sure the // we can further optimize its parent. return n; } n.removeChild(cond); Node and = IR.and(cond, expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(and); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } else { // Try to combine two IF-ELSE if (NodeUtil.isStatementBlock(thenBranch) && thenBranch.hasOneChild()) { Node innerIf = thenBranch.getFirstChild(); if (innerIf.isIf()) { Node innerCond = innerIf.getFirstChild(); Node innerThenBranch = innerCond.getNext(); Node innerElseBranch = innerThenBranch.getNext(); if (innerElseBranch == null && !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) { n.detachChildren(); n.addChildToBack( IR.and( cond, innerCond.detachFromParent()) .srcref(cond)); n.addChildrenToBack(innerThenBranch.detachFromParent()); reportCodeChange(); // Not worth trying to fold the current IF-ELSE into && because // the inner IF-ELSE wasn't able to be folded into && anyways. return n; } } } } return n; } /* TODO(dcc) This modifies the siblings of n, which is undesirable for a * peephole optimization. This should probably get moved to another pass. */ tryRemoveRepeatedStatements(n); // if(!x)foo();else bar(); -> if(x)bar();else foo(); // An additional set of curly braces isn't worth it. if (cond.isNot() && !consumesDanglingElse(elseBranch)) { n.replaceChild(cond, cond.removeFirstChild()); n.removeChild(thenBranch); n.addChildToBack(thenBranch); reportCodeChange(); return n; } // if(x)return 1;else return 2; -> return x?1:2; if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) { Node thenExpr = getBlockReturnExpression(thenBranch); Node elseExpr = getBlockReturnExpression(elseBranch); n.removeChild(cond); thenExpr.detachFromParent(); elseExpr.detachFromParent(); // note - we ignore any cases with "return;", technically this // can be converted to "return undefined;" or some variant, but // that does not help code size. Node returnNode = IR.returnNode( IR.hook(cond, thenExpr, elseExpr) .srcref(n)); parent.replaceChild(n, returnNode); reportCodeChange(); return returnNode; } boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch); boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch); if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) { Node thenOp = getBlockExpression(thenBranch).getFirstChild(); Node elseOp = getBlockExpression(elseBranch).getFirstChild(); if (thenOp.getType() == elseOp.getType()) { // if(x)a=1;else a=2; -> a=x?1:2; if (NodeUtil.isAssignmentOp(thenOp)) { Node lhs = thenOp.getFirstChild(); if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) && // if LHS has side effects, don't proceed [since the optimization // evaluates LHS before cond] // NOTE - there are some circumstances where we can // proceed even if there are side effects... !mayEffectMutableState(lhs)) { n.removeChild(cond); Node assignName = thenOp.removeFirstChild(); Node thenExpr = thenOp.removeFirstChild(); Node elseExpr = elseOp.getLastChild(); elseOp.removeChild(elseExpr); Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n); Node assign = new Node(thenOp.getType(), assignName, hookNode) .srcref(thenOp); Node expr = NodeUtil.newExpr(assign); parent.replaceChild(n, expr); reportCodeChange(); return expr; } } } // if(x)foo();else bar(); -> x?foo():bar() n.removeChild(cond); thenOp.detachFromParent(); elseOp.detachFromParent(); Node expr = IR.exprResult( IR.hook(cond, thenOp, elseOp).srcref(n)); parent.replaceChild(n, expr); reportCodeChange(); return expr; } boolean thenBranchIsVar = isVarBlock(thenBranch); boolean elseBranchIsVar = isVarBlock(elseBranch); // if(x)var y=1;else y=2 -> var y=x?1:2 if (thenBranchIsVar && elseBranchIsExpressionBlock && getBlockExpression(elseBranch).getFirstChild().isAssign()) { Node var = getBlockVar(thenBranch); Node elseAssign = getBlockExpression(elseBranch).getFirstChild(); Node name1 = var.getFirstChild(); Node maybeName2 = elseAssign.getFirstChild(); if (name1.hasChildren() && maybeName2.isName() && name1.getString().equals(maybeName2.getString())) { Node thenExpr = name1.removeChildren(); Node elseExpr = elseAssign.getLastChild().detachFromParent(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name1.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } // if(x)y=1;else var y=2 -> var y=x?1:2 } else if (elseBranchIsVar && thenBranchIsExpressionBlock && getBlockExpression(thenBranch).getFirstChild().isAssign()) { Node var = getBlockVar(elseBranch); Node thenAssign = getBlockExpression(thenBranch).getFirstChild(); Node maybeName1 = thenAssign.getFirstChild(); Node name2 = var.getFirstChild(); if (name2.hasChildren() && maybeName1.isName() && maybeName1.getString().equals(name2.getString())) { Node thenExpr = thenAssign.getLastChild().detachFromParent(); Node elseExpr = name2.removeChildren(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name2.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } } return n; } private Node tryMinimizeIf(Node n) { Node parent = n.getParent(); Node cond = n.getFirstChild(); /* If the condition is a literal, we'll let other * optimizations try to remove useless code. */ if (NodeUtil.isLiteralValue(cond, true)) { return n; } Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); if (elseBranch == null) { if (isFoldableExpressBlock(thenBranch)) { Node expr = getBlockExpression(thenBranch); if (!late && isPropertyAssignmentInExpression(expr)) { // Keep opportunities for CollapseProperties such as // a.longIdentifier || a.longIdentifier = ... -> var a = ...; // until CollapseProperties has been run. return n; } if (cond.isNot()) { // if(!x)bar(); -> x||bar(); if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), OR_PRECEDENCE)) { // It's not okay to add two sets of parentheses. return n; } Node or = IR.or( cond.removeFirstChild(), expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(or); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } // if(x)foo(); -> x&&foo(); if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), AND_PRECEDENCE)) { // One additional set of parentheses is worth the change even if // there is no immediate code size win. However, two extra pair of // {}, we would have to think twice. (unless we know for sure the // we can further optimize its parent. return n; } n.removeChild(cond); Node and = IR.and(cond, expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(and); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } else { // Try to combine two IF-ELSE if (NodeUtil.isStatementBlock(thenBranch) && thenBranch.hasOneChild()) { Node innerIf = thenBranch.getFirstChild(); if (innerIf.isIf()) { Node innerCond = innerIf.getFirstChild(); Node innerThenBranch = innerCond.getNext(); Node innerElseBranch = innerThenBranch.getNext(); if (innerElseBranch == null && !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) { n.detachChildren(); n.addChildToBack( IR.and( cond, innerCond.detachFromParent()) .srcref(cond)); n.addChildrenToBack(innerThenBranch.detachFromParent()); reportCodeChange(); // Not worth trying to fold the current IF-ELSE into && because // the inner IF-ELSE wasn't able to be folded into && anyways. return n; } } } } return n; } /* TODO(dcc) This modifies the siblings of n, which is undesirable for a * peephole optimization. This should probably get moved to another pass. */ tryRemoveRepeatedStatements(n); // if(!x)foo();else bar(); -> if(x)bar();else foo(); // An additional set of curly braces isn't worth it. if (cond.isNot() && !consumesDanglingElse(elseBranch)) { n.replaceChild(cond, cond.removeFirstChild()); n.removeChild(thenBranch); n.addChildToBack(thenBranch); reportCodeChange(); return n; } // if(x)return 1;else return 2; -> return x?1:2; if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) { Node thenExpr = getBlockReturnExpression(thenBranch); Node elseExpr = getBlockReturnExpression(elseBranch); n.removeChild(cond); thenExpr.detachFromParent(); elseExpr.detachFromParent(); // note - we ignore any cases with "return;", technically this // can be converted to "return undefined;" or some variant, but // that does not help code size. Node returnNode = IR.returnNode( IR.hook(cond, thenExpr, elseExpr) .srcref(n)); parent.replaceChild(n, returnNode); reportCodeChange(); return returnNode; } boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch); boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch); if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) { Node thenOp = getBlockExpression(thenBranch).getFirstChild(); Node elseOp = getBlockExpression(elseBranch).getFirstChild(); if (thenOp.getType() == elseOp.getType()) { // if(x)a=1;else a=2; -> a=x?1:2; if (NodeUtil.isAssignmentOp(thenOp)) { Node lhs = thenOp.getFirstChild(); if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) && // if LHS has side effects, don't proceed [since the optimization // evaluates LHS before cond] // NOTE - there are some circumstances where we can // proceed even if there are side effects... !mayEffectMutableState(lhs) && (!mayHaveSideEffects(cond) || (thenOp.isAssign() && thenOp.getFirstChild().isName()))) { n.removeChild(cond); Node assignName = thenOp.removeFirstChild(); Node thenExpr = thenOp.removeFirstChild(); Node elseExpr = elseOp.getLastChild(); elseOp.removeChild(elseExpr); Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n); Node assign = new Node(thenOp.getType(), assignName, hookNode) .srcref(thenOp); Node expr = NodeUtil.newExpr(assign); parent.replaceChild(n, expr); reportCodeChange(); return expr; } } } // if(x)foo();else bar(); -> x?foo():bar() n.removeChild(cond); thenOp.detachFromParent(); elseOp.detachFromParent(); Node expr = IR.exprResult( IR.hook(cond, thenOp, elseOp).srcref(n)); parent.replaceChild(n, expr); reportCodeChange(); return expr; } boolean thenBranchIsVar = isVarBlock(thenBranch); boolean elseBranchIsVar = isVarBlock(elseBranch); // if(x)var y=1;else y=2 -> var y=x?1:2 if (thenBranchIsVar && elseBranchIsExpressionBlock && getBlockExpression(elseBranch).getFirstChild().isAssign()) { Node var = getBlockVar(thenBranch); Node elseAssign = getBlockExpression(elseBranch).getFirstChild(); Node name1 = var.getFirstChild(); Node maybeName2 = elseAssign.getFirstChild(); if (name1.hasChildren() && maybeName2.isName() && name1.getString().equals(maybeName2.getString())) { Node thenExpr = name1.removeChildren(); Node elseExpr = elseAssign.getLastChild().detachFromParent(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name1.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } // if(x)y=1;else var y=2 -> var y=x?1:2 } else if (elseBranchIsVar && thenBranchIsExpressionBlock && getBlockExpression(thenBranch).getFirstChild().isAssign()) { Node var = getBlockVar(elseBranch); Node thenAssign = getBlockExpression(thenBranch).getFirstChild(); Node maybeName1 = thenAssign.getFirstChild(); Node name2 = var.getFirstChild(); if (name2.hasChildren() && maybeName1.isName() && maybeName1.getString().equals(name2.getString())) { Node thenExpr = thenAssign.getLastChild().detachFromParent(); Node elseExpr = name2.removeChildren(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name2.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } } return n; }
src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
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
Closure-14
private static Node computeFollowNode( Node fromNode, Node node, ControlFlowAnalysis cfa) { /* * This is the case where: * * 1. Parent is null implies that we are transferring control to the end of * the script. * * 2. Parent is a function implies that we are transferring control back to * the caller of the function. * * 3. If the node is a return statement, we should also transfer control * back to the caller of the function. * * 4. If the node is root then we have reached the end of what we have been * asked to traverse. * * In all cases we should transfer control to a "symbolic return" node. * This will make life easier for DFAs. */ Node parent = node.getParent(); if (parent == null || parent.isFunction() || (cfa != null && node == cfa.root)) { return null; } // If we are just before a IF/WHILE/DO/FOR: switch (parent.getType()) { // The follow() of any of the path from IF would be what follows IF. case Token.IF: return computeFollowNode(fromNode, parent, cfa); case Token.CASE: case Token.DEFAULT_CASE: // After the body of a CASE, the control goes to the body of the next // case, without having to go to the case condition. if (parent.getNext() != null) { if (parent.getNext().isCase()) { return parent.getNext().getFirstChild().getNext(); } else if (parent.getNext().isDefaultCase()) { return parent.getNext().getFirstChild(); } else { Preconditions.checkState(false, "Not reachable"); } } else { return computeFollowNode(fromNode, parent, cfa); } break; case Token.FOR: if (NodeUtil.isForIn(parent)) { return parent; } else { return parent.getFirstChild().getNext().getNext(); } case Token.WHILE: case Token.DO: return parent; case Token.TRY: // If we are coming out of the TRY block... if (parent.getFirstChild() == node) { if (NodeUtil.hasFinally(parent)) { // and have FINALLY block. return computeFallThrough(parent.getLastChild()); } else { // and have no FINALLY. return computeFollowNode(fromNode, parent, cfa); } // CATCH block. } else if (NodeUtil.getCatchBlock(parent) == node){ if (NodeUtil.hasFinally(parent)) { // and have FINALLY block. return computeFallThrough(node.getNext()); } else { return computeFollowNode(fromNode, parent, cfa); } // If we are coming out of the FINALLY block... } else if (parent.getLastChild() == node){ if (cfa != null) { for (Node finallyNode : cfa.finallyMap.get(parent)) { cfa.createEdge(fromNode, Branch.UNCOND, finallyNode); } } return computeFollowNode(fromNode, parent, cfa); } } // Now that we are done with the special cases follow should be its // immediate sibling, unless its sibling is a function Node nextSibling = node.getNext(); // Skip function declarations because control doesn't get pass into it. while (nextSibling != null && nextSibling.isFunction()) { nextSibling = nextSibling.getNext(); } if (nextSibling != null) { return computeFallThrough(nextSibling); } else { // If there are no more siblings, control is transferred up the AST. return computeFollowNode(fromNode, parent, cfa); } } private static Node computeFollowNode( Node fromNode, Node node, ControlFlowAnalysis cfa) { /* * This is the case where: * * 1. Parent is null implies that we are transferring control to the end of * the script. * * 2. Parent is a function implies that we are transferring control back to * the caller of the function. * * 3. If the node is a return statement, we should also transfer control * back to the caller of the function. * * 4. If the node is root then we have reached the end of what we have been * asked to traverse. * * In all cases we should transfer control to a "symbolic return" node. * This will make life easier for DFAs. */ Node parent = node.getParent(); if (parent == null || parent.isFunction() || (cfa != null && node == cfa.root)) { return null; } // If we are just before a IF/WHILE/DO/FOR: switch (parent.getType()) { // The follow() of any of the path from IF would be what follows IF. case Token.IF: return computeFollowNode(fromNode, parent, cfa); case Token.CASE: case Token.DEFAULT_CASE: // After the body of a CASE, the control goes to the body of the next // case, without having to go to the case condition. if (parent.getNext() != null) { if (parent.getNext().isCase()) { return parent.getNext().getFirstChild().getNext(); } else if (parent.getNext().isDefaultCase()) { return parent.getNext().getFirstChild(); } else { Preconditions.checkState(false, "Not reachable"); } } else { return computeFollowNode(fromNode, parent, cfa); } break; case Token.FOR: if (NodeUtil.isForIn(parent)) { return parent; } else { return parent.getFirstChild().getNext().getNext(); } case Token.WHILE: case Token.DO: return parent; case Token.TRY: // If we are coming out of the TRY block... if (parent.getFirstChild() == node) { if (NodeUtil.hasFinally(parent)) { // and have FINALLY block. return computeFallThrough(parent.getLastChild()); } else { // and have no FINALLY. return computeFollowNode(fromNode, parent, cfa); } // CATCH block. } else if (NodeUtil.getCatchBlock(parent) == node){ if (NodeUtil.hasFinally(parent)) { // and have FINALLY block. return computeFallThrough(node.getNext()); } else { return computeFollowNode(fromNode, parent, cfa); } // If we are coming out of the FINALLY block... } else if (parent.getLastChild() == node){ if (cfa != null) { for (Node finallyNode : cfa.finallyMap.get(parent)) { cfa.createEdge(fromNode, Branch.ON_EX, finallyNode); } } return computeFollowNode(fromNode, parent, cfa); } } // Now that we are done with the special cases follow should be its // immediate sibling, unless its sibling is a function Node nextSibling = node.getNext(); // Skip function declarations because control doesn't get pass into it. while (nextSibling != null && nextSibling.isFunction()) { nextSibling = nextSibling.getNext(); } if (nextSibling != null) { return computeFallThrough(nextSibling); } else { // If there are no more siblings, control is transferred up the AST. return computeFollowNode(fromNode, parent, cfa); } }
src/com/google/javascript/jscomp/ControlFlowAnalysis.java
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
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
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
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
Closure-152
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) { setResolvedTypeInternal(this); call = (ArrowType) safeResolve(call, t, scope); prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope); // Warning about typeOfThis if it doesn't resolve to an ObjectType // is handled further upstream. // TODO(nicksantos): Handle this correctly if we have a UnionType. typeOfThis = (ObjectType) safeResolve(typeOfThis, t, scope); boolean changed = false; ImmutableList.Builder<ObjectType> resolvedInterfaces = ImmutableList.builder(); for (ObjectType iface : implementedInterfaces) { ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope); resolvedInterfaces.add(resolvedIface); changed |= (resolvedIface != iface); } if (changed) { implementedInterfaces = resolvedInterfaces.build(); } if (subTypes != null) { for (int i = 0; i < subTypes.size(); i++) { subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope)); } } return super.resolveInternal(t, scope); } JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) { setResolvedTypeInternal(this); call = (ArrowType) safeResolve(call, t, scope); prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope); // Warning about typeOfThis if it doesn't resolve to an ObjectType // is handled further upstream. // TODO(nicksantos): Handle this correctly if we have a UnionType. JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope); if (maybeTypeOfThis instanceof ObjectType) { typeOfThis = (ObjectType) maybeTypeOfThis; } boolean changed = false; ImmutableList.Builder<ObjectType> resolvedInterfaces = ImmutableList.builder(); for (ObjectType iface : implementedInterfaces) { ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope); resolvedInterfaces.add(resolvedIface); changed |= (resolvedIface != iface); } if (changed) { implementedInterfaces = resolvedInterfaces.build(); } if (subTypes != null) { for (int i = 0; i < subTypes.size(); i++) { subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope)); } } return super.resolveInternal(t, scope); }
src/com/google/javascript/rhino/jstype/FunctionType.java
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-160
public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { // If DiagnosticGroups did not override the plain checkTypes // option, and checkTypes is enabled, then turn off the // parser type warnings. options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn()) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } // Initialize the warnings guard. List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. if (!options.checkSymbols && (warningsGuard == null || !warningsGuard.disables( DiagnosticGroups.CHECK_VARIABLES))) { guards.add(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = new ComposeWarningsGuard(guards); } public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { // If DiagnosticGroups did not override the plain checkTypes // option, and checkTypes is enabled, then turn off the // parser type warnings. options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn()) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } // Initialize the warnings guard. List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards); // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. if (!options.checkSymbols && !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) { composedGuards.addGuard(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = composedGuards; }
src/com/google/javascript/jscomp/Compiler.java
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
Closure-164
public boolean isSubtype(JSType other) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); // "that" can't be a supertype, because it's missing a required argument. // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required arguement. return true; } public boolean isSubtype(JSType other) { if (!(other instanceof ArrowType)) { return false; } ArrowType that = (ArrowType) other; // This is described in Draft 2 of the ES4 spec, // Section 3.4.7: Subtyping Function Types. // this.returnType <: that.returnType (covariant) if (!this.returnType.isSubtype(that.returnType)) { return false; } // that.paramType[i] <: this.paramType[i] (contravariant) // // If this.paramType[i] is required, // then that.paramType[i] is required. // // In theory, the "required-ness" should work in the other direction as // well. In other words, if we have // // function f(number, number) {} // function g(number) {} // // Then f *should* not be a subtype of g, and g *should* not be // a subtype of f. But in practice, we do not implement it this way. // We want to support the use case where you can pass g where f is // expected, and pretend that g ignores the second argument. // That way, you can have a single "no-op" function, and you don't have // to create a new no-op function for every possible type signature. // // So, in this case, g < f, but f !< g Node thisParam = parameters.getFirstChild(); Node thatParam = that.parameters.getFirstChild(); while (thisParam != null && thatParam != null) { JSType thisParamType = thisParam.getJSType(); JSType thatParamType = thatParam.getJSType(); if (thisParamType != null) { if (thatParamType == null || !thatParamType.isSubtype(thisParamType)) { return false; } } boolean thisIsVarArgs = thisParam.isVarArgs(); boolean thatIsVarArgs = thatParam.isVarArgs(); boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg(); boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg(); // "that" can't be a supertype, because it's missing a required argument. if (!thisIsOptional && thatIsOptional) { // NOTE(nicksantos): In our type system, we use {function(...?)} and // {function(...NoType)} to to indicate that arity should not be // checked. Strictly speaking, this is not a correct formulation, // because now a sub-function can required arguments that are var_args // in the super-function. So we special-case this. boolean isTopFunction = thatIsVarArgs && (thatParamType == null || thatParamType.isUnknownType() || thatParamType.isNoType()); if (!isTopFunction) { return false; } } // don't advance if we have variable arguments if (!thisIsVarArgs) { thisParam = thisParam.getNext(); } if (!thatIsVarArgs) { thatParam = thatParam.getNext(); } // both var_args indicates the end if (thisIsVarArgs && thatIsVarArgs) { thisParam = null; thatParam = null; } } // "that" can't be a supertype, because it's missing a required arguement. if (thisParam != null && !thisParam.isOptionalArg() && !thisParam.isVarArgs() && thatParam == null) { return false; } return true; }
src/com/google/javascript/rhino/jstype/ArrowType.java
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
Closure-168
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (t.inGlobalScope()) { return; } if (n.isReturn() && n.getFirstChild() != null) { data.get(t.getScopeRoot()).recordNonEmptyReturn(); } if (t.getScopeDepth() <= 2) { // The first-order function analyzer looks at two types of variables: // // 1) Local variables that are assigned in inner scopes ("escaped vars") // // 2) Local variables that are assigned more than once. // // We treat all global variables as escaped by default, so there's // no reason to do this extra computation for them. return; } if (n.isName() && NodeUtil.isLValue(n) && // Be careful of bleeding functions, which create variables // in the inner scope, not the scope where the name appears. !NodeUtil.isBleedingFunctionName(n)) { String name = n.getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordAssignedName(name); } if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordEscapedVarName(name); } } } else if (n.isGetProp() && n.isUnscopedQualifiedName() && NodeUtil.isLValue(n)) { String name = NodeUtil.getRootOfQualifiedName(n).getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()) .recordEscapedQualifiedName(n.getQualifiedName()); } } } } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (t.inGlobalScope()) { return; } if (n.isReturn() && n.getFirstChild() != null) { data.get(t.getScopeRoot()).recordNonEmptyReturn(); } if (t.getScopeDepth() <= 1) { // The first-order function analyzer looks at two types of variables: // // 1) Local variables that are assigned in inner scopes ("escaped vars") // // 2) Local variables that are assigned more than once. // // We treat all global variables as escaped by default, so there's // no reason to do this extra computation for them. return; } if (n.isName() && NodeUtil.isLValue(n) && // Be careful of bleeding functions, which create variables // in the inner scope, not the scope where the name appears. !NodeUtil.isBleedingFunctionName(n)) { String name = n.getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordAssignedName(name); } if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()).recordEscapedVarName(name); } } } else if (n.isGetProp() && n.isUnscopedQualifiedName() && NodeUtil.isLValue(n)) { String name = NodeUtil.getRootOfQualifiedName(n).getString(); Scope scope = t.getScope(); Var var = scope.getVar(name); if (var != null) { Scope ownerScope = var.getScope(); if (scope != ownerScope && ownerScope.isLocal()) { data.get(ownerScope.getRootNode()) .recordEscapedQualifiedName(n.getQualifiedName()); } } } }
src/com/google/javascript/jscomp/TypedScopeCreator.java
Closure-17
private JSType getDeclaredType(String sourceName, JSDocInfo info, Node lValue, @Nullable Node rValue) { if (info != null && info.hasType()) { return getDeclaredTypeInAnnotation(sourceName, lValue, info); } else if (rValue != null && rValue.isFunction() && shouldUseFunctionLiteralType( JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) { return rValue.getJSType(); } else if (info != null) { if (info.hasEnumParameterType()) { if (rValue != null && rValue.isObjectLit()) { return rValue.getJSType(); } else { return createEnumTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } } else if (info.isConstructor() || info.isInterface()) { return createFunctionTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } else { // Check if this is constant, and if it has a known type. if (info.isConstant()) { JSType knownType = null; if (rValue != null) { if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) { // If rValue has a type-cast, we use the type in the type-cast. // If rValue's type was already computed during scope creation, // then we can safely use that. return rValue.getJSType(); } else if (rValue.isOr()) { // Check for a very specific JS idiom: // var x = x || TYPE; // This is used by Closure's base namespace for esoteric // reasons. Node firstClause = rValue.getFirstChild(); Node secondClause = firstClause.getNext(); boolean namesMatch = firstClause.isName() && lValue.isName() && firstClause.getString().equals(lValue.getString()); if (namesMatch && secondClause.getJSType() != null && !secondClause.getJSType().isUnknownType()) { return secondClause.getJSType(); } } } } } } return getDeclaredTypeInAnnotation(sourceName, lValue, info); } private JSType getDeclaredType(String sourceName, JSDocInfo info, Node lValue, @Nullable Node rValue) { if (info != null && info.hasType()) { return getDeclaredTypeInAnnotation(sourceName, lValue, info); } else if (rValue != null && rValue.isFunction() && shouldUseFunctionLiteralType( JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) { return rValue.getJSType(); } else if (info != null) { if (info.hasEnumParameterType()) { if (rValue != null && rValue.isObjectLit()) { return rValue.getJSType(); } else { return createEnumTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } } else if (info.isConstructor() || info.isInterface()) { return createFunctionTypeFromNodes( rValue, lValue.getQualifiedName(), info, lValue); } else { // Check if this is constant, and if it has a known type. if (info.isConstant()) { JSType knownType = null; if (rValue != null) { JSDocInfo rValueInfo = rValue.getJSDocInfo(); if (rValueInfo != null && rValueInfo.hasType()) { // If rValue has a type-cast, we use the type in the type-cast. return rValueInfo.getType().evaluate(scope, typeRegistry); } else if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) { // If rValue's type was already computed during scope creation, // then we can safely use that. return rValue.getJSType(); } else if (rValue.isOr()) { // Check for a very specific JS idiom: // var x = x || TYPE; // This is used by Closure's base namespace for esoteric // reasons. Node firstClause = rValue.getFirstChild(); Node secondClause = firstClause.getNext(); boolean namesMatch = firstClause.isName() && lValue.isName() && firstClause.getString().equals(lValue.getString()); if (namesMatch && secondClause.getJSType() != null && !secondClause.getJSType().isUnknownType()) { return secondClause.getJSType(); } } } } } } return getDeclaredTypeInAnnotation(sourceName, lValue, info); }
src/com/google/javascript/jscomp/TypedScopeCreator.java
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
Closure-176
private void updateScopeForTypeChange( FlowScope scope, Node left, JSType leftType, JSType resultType) { Preconditions.checkNotNull(resultType); switch (left.getType()) { case Token.NAME: String varName = left.getString(); Var var = syntacticScope.getVar(varName); boolean isVarDeclaration = left.hasChildren(); // When looking at VAR initializers for declared VARs, we tend // to use the declared type over the type it's being // initialized to in the global scope. // // For example, // /** @param {number} */ var f = goog.abstractMethod; // it's obvious that the programmer wants you to use // the declared function signature, not the inferred signature. // // Or, // /** @type {Object.<string>} */ var x = {}; // the one-time anonymous object on the right side // is as narrow as it can possibly be, but we need to make // sure we back-infer the <string> element constraint on // the left hand side, so we use the left hand side. boolean isVarTypeBetter = !isVarDeclaration || var == null || var.isTypeInferred(); // Makes it easier to check for NPEs. // TODO(nicksantos): This might be a better check once we have // back-inference of object/array constraints. It will probably // introduce more type warnings. It uses the result type iff it's // strictly narrower than the declared var type. // //boolean isVarTypeBetter = isVarDeclaration && // (varType.restrictByNotNullOrUndefined().isSubtype(resultType) // || !resultType.isSubtype(varType)); if (isVarTypeBetter) { redeclareSimpleVar(scope, left, resultType); } left.setJSType(isVarDeclaration || leftType == null ? resultType : null); if (var != null && var.isTypeInferred()) { JSType oldType = var.getType(); var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType)); } break; case Token.GETPROP: String qualifiedName = left.getQualifiedName(); if (qualifiedName != null) { scope.inferQualifiedSlot(left, qualifiedName, leftType == null ? unknownType : leftType, resultType); } left.setJSType(resultType); ensurePropertyDefined(left, resultType); break; } } private void updateScopeForTypeChange( FlowScope scope, Node left, JSType leftType, JSType resultType) { Preconditions.checkNotNull(resultType); switch (left.getType()) { case Token.NAME: String varName = left.getString(); Var var = syntacticScope.getVar(varName); JSType varType = var == null ? null : var.getType(); boolean isVarDeclaration = left.hasChildren() && varType != null && !var.isTypeInferred(); // When looking at VAR initializers for declared VARs, we tend // to use the declared type over the type it's being // initialized to in the global scope. // // For example, // /** @param {number} */ var f = goog.abstractMethod; // it's obvious that the programmer wants you to use // the declared function signature, not the inferred signature. // // Or, // /** @type {Object.<string>} */ var x = {}; // the one-time anonymous object on the right side // is as narrow as it can possibly be, but we need to make // sure we back-infer the <string> element constraint on // the left hand side, so we use the left hand side. boolean isVarTypeBetter = isVarDeclaration && // Makes it easier to check for NPEs. !resultType.isNullType() && !resultType.isVoidType(); // TODO(nicksantos): This might be a better check once we have // back-inference of object/array constraints. It will probably // introduce more type warnings. It uses the result type iff it's // strictly narrower than the declared var type. // //boolean isVarTypeBetter = isVarDeclaration && // (varType.restrictByNotNullOrUndefined().isSubtype(resultType) // || !resultType.isSubtype(varType)); if (isVarTypeBetter) { redeclareSimpleVar(scope, left, varType); } else { redeclareSimpleVar(scope, left, resultType); } left.setJSType(resultType); if (var != null && var.isTypeInferred()) { JSType oldType = var.getType(); var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType)); } break; case Token.GETPROP: String qualifiedName = left.getQualifiedName(); if (qualifiedName != null) { scope.inferQualifiedSlot(left, qualifiedName, leftType == null ? unknownType : leftType, resultType); } left.setJSType(resultType); ensurePropertyDefined(left, resultType); break; } }
src/com/google/javascript/jscomp/TypeInference.java
Closure-18
Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; // If old roots exist (we are parsing a second time), detach each of the // individual file parse trees. if (externsRoot != null) { externsRoot.detachChildren(); } if (jsRoot != null) { jsRoot.detachChildren(); } // Parse main JS sources. jsRoot = IR.block(); jsRoot.setIsSyntheticBlock(true); externsRoot = IR.block(); externsRoot.setIsSyntheticBlock(true); externAndJsRoot = IR.block(externsRoot, jsRoot); externAndJsRoot.setIsSyntheticBlock(true); if (options.tracer.isOn()) { tracker = new PerformanceTracker(jsRoot, options.tracer); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer("parseInputs"); try { // Parse externs sources. for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } // Modules inferred in ProcessCommonJS pass. if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } hoistExterns(externsRoot); // Check if the sources need to be re-ordered. boolean staleInputs = false; if (options.dependencyOptions.needsManagement() && options.closurePass) { for (CompilerInput input : inputs) { // Forward-declare all the provided types, so that they // are not flagged even if they are dropped from the process. for (String provide : input.getProvides()) { getTypeRegistry().forwardDeclareType(provide); } } try { inputs = (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph) .manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (CircularDependencyException e) { report(JSError.make( JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } } hoistNoCompileFiles(); if (staleInputs) { repartitionInputs(); } // Build the AST. for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } if (options.sourceMapOutputPath != null || options.nameReferenceReportPath != null) { // Annotate the nodes in the tree with information from the // input file. This information is used to construct the SourceMap. SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverse(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { stopTracer(tracer, "parseInputs"); } } Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; // If old roots exist (we are parsing a second time), detach each of the // individual file parse trees. if (externsRoot != null) { externsRoot.detachChildren(); } if (jsRoot != null) { jsRoot.detachChildren(); } // Parse main JS sources. jsRoot = IR.block(); jsRoot.setIsSyntheticBlock(true); externsRoot = IR.block(); externsRoot.setIsSyntheticBlock(true); externAndJsRoot = IR.block(externsRoot, jsRoot); externAndJsRoot.setIsSyntheticBlock(true); if (options.tracer.isOn()) { tracker = new PerformanceTracker(jsRoot, options.tracer); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer("parseInputs"); try { // Parse externs sources. for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } // Modules inferred in ProcessCommonJS pass. if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } hoistExterns(externsRoot); // Check if the sources need to be re-ordered. boolean staleInputs = false; if (options.dependencyOptions.needsManagement()) { for (CompilerInput input : inputs) { // Forward-declare all the provided types, so that they // are not flagged even if they are dropped from the process. for (String provide : input.getProvides()) { getTypeRegistry().forwardDeclareType(provide); } } try { inputs = (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph) .manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (CircularDependencyException e) { report(JSError.make( JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } } hoistNoCompileFiles(); if (staleInputs) { repartitionInputs(); } // Build the AST. for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } if (options.sourceMapOutputPath != null || options.nameReferenceReportPath != null) { // Annotate the nodes in the tree with information from the // input file. This information is used to construct the SourceMap. SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverse(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { stopTracer(tracer, "parseInputs"); } }
src/com/google/javascript/jscomp/Compiler.java
Closure-19
protected void declareNameInScope(FlowScope scope, Node node, JSType type) { switch (node.getType()) { case Token.NAME: scope.inferSlotType(node.getString(), type); break; case Token.GETPROP: String qualifiedName = node.getQualifiedName(); Preconditions.checkNotNull(qualifiedName); JSType origType = node.getJSType(); origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType; scope.inferQualifiedSlot(node, qualifiedName, origType, type); break; // "this" references aren't currently modeled in the CFG. default: throw new IllegalArgumentException("Node cannot be refined. \n" + node.toStringTree()); } } protected void declareNameInScope(FlowScope scope, Node node, JSType type) { switch (node.getType()) { case Token.NAME: scope.inferSlotType(node.getString(), type); break; case Token.GETPROP: String qualifiedName = node.getQualifiedName(); Preconditions.checkNotNull(qualifiedName); JSType origType = node.getJSType(); origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType; scope.inferQualifiedSlot(node, qualifiedName, origType, type); break; case Token.THIS: // "this" references aren't currently modeled in the CFG. break; default: throw new IllegalArgumentException("Node cannot be refined. \n" + node.toStringTree()); } }
src/com/google/javascript/jscomp/type/ChainableReverseAbstractInterpreter.java
Closure-2
private void checkInterfaceConflictProperties(NodeTraversal t, Node n, String functionName, HashMap<String, ObjectType> properties, HashMap<String, ObjectType> currentProperties, ObjectType interfaceType) { ObjectType implicitProto = interfaceType.getImplicitPrototype(); Set<String> currentPropertyNames; // This can be the case if interfaceType is proxy to a non-existent // object (which is a bad type annotation, but shouldn't crash). currentPropertyNames = implicitProto.getOwnPropertyNames(); for (String name : currentPropertyNames) { ObjectType oType = properties.get(name); if (oType != null) { if (!interfaceType.getPropertyType(name).isEquivalentTo( oType.getPropertyType(name))) { compiler.report( t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE, functionName, name, oType.toString(), interfaceType.toString())); } } currentProperties.put(name, interfaceType); } for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) { checkInterfaceConflictProperties(t, n, functionName, properties, currentProperties, iType); } } private void checkInterfaceConflictProperties(NodeTraversal t, Node n, String functionName, HashMap<String, ObjectType> properties, HashMap<String, ObjectType> currentProperties, ObjectType interfaceType) { ObjectType implicitProto = interfaceType.getImplicitPrototype(); Set<String> currentPropertyNames; if (implicitProto == null) { // This can be the case if interfaceType is proxy to a non-existent // object (which is a bad type annotation, but shouldn't crash). currentPropertyNames = ImmutableSet.of(); } else { currentPropertyNames = implicitProto.getOwnPropertyNames(); } for (String name : currentPropertyNames) { ObjectType oType = properties.get(name); if (oType != null) { if (!interfaceType.getPropertyType(name).isEquivalentTo( oType.getPropertyType(name))) { compiler.report( t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE, functionName, name, oType.toString(), interfaceType.toString())); } } currentProperties.put(name, interfaceType); } for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) { checkInterfaceConflictProperties(t, n, functionName, properties, currentProperties, iType); } }
src/com/google/javascript/jscomp/TypeCheck.java
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
Closure-21
public void visit(NodeTraversal t, Node n, Node parent) { // VOID nodes appear when there are extra semicolons at the BLOCK level. // I've been unable to think of any cases where this indicates a bug, // and apparently some people like keeping these semicolons around, // so we'll allow it. if (n.isEmpty() || n.isComma()) { return; } if (parent == null) { return; } // Do not try to remove a block or an expr result. We already handle // these cases when we visit the child, and the peephole passes will // fix up the tree in more clever ways when these are removed. if (n.isExprResult()) { return; } // This no-op statement was there so that JSDoc information could // be attached to the name. This check should not complain about it. if (n.isQualifiedName() && n.getJSDocInfo() != null) { return; } boolean isResultUsed = NodeUtil.isExpressionResultUsed(n); boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType()); if (parent.getType() == Token.COMMA) { if (isResultUsed) { return; } if (n == parent.getLastChild()) { for (Node an : parent.getAncestors()) { int ancestorType = an.getType(); if (ancestorType == Token.COMMA) continue; if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK) return; else break; } } } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) { if (! (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() || n == parent.getFirstChild().getNext().getNext()))) { return; } } if ( (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) { String msg = "This code lacks side-effects. Is there a bug?"; if (n.isString()) { msg = "Is there a missing '+' on the previous line?"; } else if (isSimpleOp) { msg = "The result of the '" + Token.name(n.getType()).toLowerCase() + "' operator is not being used."; } t.getCompiler().report( t.makeError(n, level, USELESS_CODE_ERROR, msg)); // TODO(johnlenz): determine if it is necessary to // try to protect side-effect free statements as well. if (!NodeUtil.isStatement(n)) { problemNodes.add(n); } } } public void visit(NodeTraversal t, Node n, Node parent) { // VOID nodes appear when there are extra semicolons at the BLOCK level. // I've been unable to think of any cases where this indicates a bug, // and apparently some people like keeping these semicolons around, // so we'll allow it. if (n.isEmpty() || n.isComma()) { return; } if (parent == null) { return; } // Do not try to remove a block or an expr result. We already handle // these cases when we visit the child, and the peephole passes will // fix up the tree in more clever ways when these are removed. if (n.isExprResult() || n.isBlock()) { return; } // This no-op statement was there so that JSDoc information could // be attached to the name. This check should not complain about it. if (n.isQualifiedName() && n.getJSDocInfo() != null) { return; } boolean isResultUsed = NodeUtil.isExpressionResultUsed(n); boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType()); if (!isResultUsed && (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) { String msg = "This code lacks side-effects. Is there a bug?"; if (n.isString()) { msg = "Is there a missing '+' on the previous line?"; } else if (isSimpleOp) { msg = "The result of the '" + Token.name(n.getType()).toLowerCase() + "' operator is not being used."; } t.getCompiler().report( t.makeError(n, level, USELESS_CODE_ERROR, msg)); // TODO(johnlenz): determine if it is necessary to // try to protect side-effect free statements as well. if (!NodeUtil.isStatement(n)) { problemNodes.add(n); } } }
src/com/google/javascript/jscomp/CheckSideEffects.java
Closure-22
public void visit(NodeTraversal t, Node n, Node parent) { // VOID nodes appear when there are extra semicolons at the BLOCK level. // I've been unable to think of any cases where this indicates a bug, // and apparently some people like keeping these semicolons around, // so we'll allow it. if (n.isEmpty() || n.isComma()) { return; } if (parent == null) { return; } // Do not try to remove a block or an expr result. We already handle // these cases when we visit the child, and the peephole passes will // fix up the tree in more clever ways when these are removed. if (parent.getType() == Token.COMMA) { Node gramps = parent.getParent(); if (gramps.isCall() && parent == gramps.getFirstChild()) { if (n == parent.getFirstChild() && parent.getChildCount() == 2 && n.getNext().isName() && "eval".equals(n.getNext().getString())) { return; } } // This no-op statement was there so that JSDoc information could // be attached to the name. This check should not complain about it. if (n == parent.getLastChild()) { for (Node an : parent.getAncestors()) { int ancestorType = an.getType(); if (ancestorType == Token.COMMA) continue; if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK) return; else break; } } } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) { if (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() || n == parent.getFirstChild().getNext().getNext())) { } else { return; } } boolean isResultUsed = NodeUtil.isExpressionResultUsed(n); boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType()); if (!isResultUsed && (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) { if (n.isQualifiedName() && n.getJSDocInfo() != null) { return; } else if (n.isExprResult()) { return; } String msg = "This code lacks side-effects. Is there a bug?"; if (n.isString()) { msg = "Is there a missing '+' on the previous line?"; } else if (isSimpleOp) { msg = "The result of the '" + Token.name(n.getType()).toLowerCase() + "' operator is not being used."; } t.getCompiler().report( t.makeError(n, level, USELESS_CODE_ERROR, msg)); // TODO(johnlenz): determine if it is necessary to // try to protect side-effect free statements as well. if (!NodeUtil.isStatement(n)) { problemNodes.add(n); } } } public void visit(NodeTraversal t, Node n, Node parent) { // VOID nodes appear when there are extra semicolons at the BLOCK level. // I've been unable to think of any cases where this indicates a bug, // and apparently some people like keeping these semicolons around, // so we'll allow it. if (n.isEmpty() || n.isComma()) { return; } if (parent == null) { return; } // Do not try to remove a block or an expr result. We already handle // these cases when we visit the child, and the peephole passes will // fix up the tree in more clever ways when these are removed. if (n.isExprResult() || n.isBlock()) { return; } // This no-op statement was there so that JSDoc information could // be attached to the name. This check should not complain about it. if (n.isQualifiedName() && n.getJSDocInfo() != null) { return; } boolean isResultUsed = NodeUtil.isExpressionResultUsed(n); boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType()); if (!isResultUsed && (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) { String msg = "This code lacks side-effects. Is there a bug?"; if (n.isString()) { msg = "Is there a missing '+' on the previous line?"; } else if (isSimpleOp) { msg = "The result of the '" + Token.name(n.getType()).toLowerCase() + "' operator is not being used."; } t.getCompiler().report( t.makeError(n, level, USELESS_CODE_ERROR, msg)); // TODO(johnlenz): determine if it is necessary to // try to protect side-effect free statements as well. if (!NodeUtil.isStatement(n)) { problemNodes.add(n); } } }
src/com/google/javascript/jscomp/CheckSideEffects.java
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
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
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
Closure-29
private boolean isInlinableObject(List<Reference> refs) { boolean ret = false; for (Reference ref : refs) { Node name = ref.getNode(); Node parent = ref.getParent(); Node gramps = ref.getGrandparent(); // Ignore indirect references, like x.y (except x.y(), since // the function referenced by y might reference 'this'). // if (parent.isGetProp()) { Preconditions.checkState(parent.getFirstChild() == name); // A call target maybe using the object as a 'this' value. if (gramps.isCall() && gramps.getFirstChild() == parent) { return false; } // NOTE(nicksantos): This pass's object-splitting algorithm has // a blind spot. It assumes that if a property isn't defined on an // object, then the value is undefined. This is not true, because // Object.prototype can have arbitrary properties on it. // // We short-circuit this problem by bailing out if we see a reference // to a property that isn't defined on the object literal. This // isn't a perfect algorithm, but it should catch most cases. continue; } // Only rewrite VAR declarations or simple assignment statements if (!isVarOrAssignExprLhs(name)) { return false; } Node val = ref.getAssignedValue(); if (val == null) { // A var with no assignment. continue; } // We're looking for object literal assignments only. if (!val.isObjectLit()) { return false; } // Make sure that the value is not self-refential. IOW, // disallow things like x = {b: x.a}. // // TODO: Only exclude unorderable self-referential // assignments. i.e. x = {a: x.b, b: x.a} is not orderable, // but x = {a: 1, b: x.a} is. // // Also, ES5 getters/setters aren't handled by this pass. for (Node child = val.getFirstChild(); child != null; child = child.getNext()) { if (child.isGetterDef() || child.isSetterDef()) { // ES5 get/set not supported. return false; } Node childVal = child.getFirstChild(); // Check if childVal is the parent of any of the passed in // references, as that is how self-referential assignments // will happen. for (Reference t : refs) { Node refNode = t.getParent(); while (!NodeUtil.isStatementBlock(refNode)) { if (refNode == childVal) { // There's a self-referential assignment return false; } refNode = refNode.getParent(); } } } // We have found an acceptable object literal assignment. As // long as there are no other assignments that mess things up, // we can inline. ret = true; } return ret; } private boolean isInlinableObject(List<Reference> refs) { boolean ret = false; Set<String> validProperties = Sets.newHashSet(); for (Reference ref : refs) { Node name = ref.getNode(); Node parent = ref.getParent(); Node gramps = ref.getGrandparent(); // Ignore indirect references, like x.y (except x.y(), since // the function referenced by y might reference 'this'). // if (parent.isGetProp()) { Preconditions.checkState(parent.getFirstChild() == name); // A call target maybe using the object as a 'this' value. if (gramps.isCall() && gramps.getFirstChild() == parent) { return false; } // NOTE(nicksantos): This pass's object-splitting algorithm has // a blind spot. It assumes that if a property isn't defined on an // object, then the value is undefined. This is not true, because // Object.prototype can have arbitrary properties on it. // // We short-circuit this problem by bailing out if we see a reference // to a property that isn't defined on the object literal. This // isn't a perfect algorithm, but it should catch most cases. String propName = parent.getLastChild().getString(); if (!validProperties.contains(propName)) { if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) { validProperties.add(propName); } else { return false; } } continue; } // Only rewrite VAR declarations or simple assignment statements if (!isVarOrAssignExprLhs(name)) { return false; } Node val = ref.getAssignedValue(); if (val == null) { // A var with no assignment. continue; } // We're looking for object literal assignments only. if (!val.isObjectLit()) { return false; } // Make sure that the value is not self-refential. IOW, // disallow things like x = {b: x.a}. // // TODO: Only exclude unorderable self-referential // assignments. i.e. x = {a: x.b, b: x.a} is not orderable, // but x = {a: 1, b: x.a} is. // // Also, ES5 getters/setters aren't handled by this pass. for (Node child = val.getFirstChild(); child != null; child = child.getNext()) { if (child.isGetterDef() || child.isSetterDef()) { // ES5 get/set not supported. return false; } validProperties.add(child.getString()); Node childVal = child.getFirstChild(); // Check if childVal is the parent of any of the passed in // references, as that is how self-referential assignments // will happen. for (Reference t : refs) { Node refNode = t.getParent(); while (!NodeUtil.isStatementBlock(refNode)) { if (refNode == childVal) { // There's a self-referential assignment return false; } refNode = refNode.getParent(); } } } // We have found an acceptable object literal assignment. As // long as there are no other assignments that mess things up, // we can inline. ret = true; } return ret; }
src/com/google/javascript/jscomp/InlineObjectLiterals.java
Closure-31
Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; // If old roots exist (we are parsing a second time), detach each of the // individual file parse trees. if (externsRoot != null) { externsRoot.detachChildren(); } if (jsRoot != null) { jsRoot.detachChildren(); } // Parse main js sources. jsRoot = IR.block(); jsRoot.setIsSyntheticBlock(true); externsRoot = IR.block(); externsRoot.setIsSyntheticBlock(true); externAndJsRoot = IR.block(externsRoot, jsRoot); externAndJsRoot.setIsSyntheticBlock(true); if (options.tracer.isOn()) { tracker = new PerformanceTracker(jsRoot, options.tracer); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer("parseInputs"); try { // Parse externs sources. for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } // Modules inferred in ProcessCommonJS pass. if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } // Check if inputs need to be rebuilt from modules. boolean staleInputs = false; // Check if the sources need to be re-ordered. if (options.dependencyOptions.needsManagement() && !options.skipAllPasses && options.closurePass) { for (CompilerInput input : inputs) { // Forward-declare all the provided types, so that they // are not flagged even if they are dropped from the process. for (String provide : input.getProvides()) { getTypeRegistry().forwardDeclareType(provide); } } try { inputs = (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph) .manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (CircularDependencyException e) { report(JSError.make( JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } } for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); // Inputs can have a null AST during initial parse. if (n == null) { continue; } if (n.getJSDocInfo() != null) { JSDocInfo info = n.getJSDocInfo(); if (info.isExterns()) { // If the input file is explicitly marked as an externs file, then // assume the programmer made a mistake and throw it into // the externs pile anyways. externsRoot.addChildToBack(n); input.setIsExtern(true); input.getModule().remove(input); externs.add(input); staleInputs = true; } else if (info.isNoCompile()) { input.getModule().remove(input); staleInputs = true; } } } if (staleInputs) { fillEmptyModules(modules); rebuildInputsFromModules(); } // Build the AST. for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } if (options.sourceMapOutputPath != null || options.nameReferenceReportPath != null) { // Annotate the nodes in the tree with information from the // input file. This information is used to construct the SourceMap. SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverse(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { stopTracer(tracer, "parseInputs"); } } Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; // If old roots exist (we are parsing a second time), detach each of the // individual file parse trees. if (externsRoot != null) { externsRoot.detachChildren(); } if (jsRoot != null) { jsRoot.detachChildren(); } // Parse main js sources. jsRoot = IR.block(); jsRoot.setIsSyntheticBlock(true); externsRoot = IR.block(); externsRoot.setIsSyntheticBlock(true); externAndJsRoot = IR.block(externsRoot, jsRoot); externAndJsRoot.setIsSyntheticBlock(true); if (options.tracer.isOn()) { tracker = new PerformanceTracker(jsRoot, options.tracer); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer("parseInputs"); try { // Parse externs sources. for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } // Modules inferred in ProcessCommonJS pass. if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } // Check if inputs need to be rebuilt from modules. boolean staleInputs = false; // Check if the sources need to be re-ordered. if (options.dependencyOptions.needsManagement() && options.closurePass) { for (CompilerInput input : inputs) { // Forward-declare all the provided types, so that they // are not flagged even if they are dropped from the process. for (String provide : input.getProvides()) { getTypeRegistry().forwardDeclareType(provide); } } try { inputs = (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph) .manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (CircularDependencyException e) { report(JSError.make( JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); // If in IDE mode, we ignore the error and keep going. if (hasErrors()) { return null; } } } for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); // Inputs can have a null AST during initial parse. if (n == null) { continue; } if (n.getJSDocInfo() != null) { JSDocInfo info = n.getJSDocInfo(); if (info.isExterns()) { // If the input file is explicitly marked as an externs file, then // assume the programmer made a mistake and throw it into // the externs pile anyways. externsRoot.addChildToBack(n); input.setIsExtern(true); input.getModule().remove(input); externs.add(input); staleInputs = true; } else if (info.isNoCompile()) { input.getModule().remove(input); staleInputs = true; } } } if (staleInputs) { fillEmptyModules(modules); rebuildInputsFromModules(); } // Build the AST. for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } if (options.sourceMapOutputPath != null || options.nameReferenceReportPath != null) { // Annotate the nodes in the tree with information from the // input file. This information is used to construct the SourceMap. SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverse(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { stopTracer(tracer, "parseInputs"); } }
src/com/google/javascript/jscomp/Compiler.java
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
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