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 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 30