diff --git "a/trigger.csv" "b/trigger.csv"
new file mode 100644--- /dev/null
+++ "b/trigger.csv"
@@ -0,0 +1,86842 @@
+text
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void test2947660() {
+ AbstractCategoryItemRenderer r = new LineAndShapeRenderer();
+ assertNotNull(r.getLegendItems());
+ assertEquals(0, r.getLegendItems().getItemCount());
+
+ DefaultCategoryDataset dataset = new DefaultCategoryDataset();
+ CategoryPlot plot = new CategoryPlot();
+ plot.setDataset(dataset);
+ plot.setRenderer(r);
+ assertEquals(0, r.getLegendItems().getItemCount());
+
+ dataset.addValue(1.0, ""S1"", ""C1"");
+ LegendItemCollection lic = r.getLegendItems();
+ assertEquals(1, lic.getItemCount());
+ assertEquals(""S1"", lic.get(0).getLabel());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String generateToolTipFragment(String toolTipText) {
+ return "" title=\"""" + toolTipText
+ + ""\"" alt=\""\"""";
+ }
+
+// Test Case
+[/INST]
+ public void testGenerateURLFragment() {
+ StandardToolTipTagFragmentGenerator g
+ = new StandardToolTipTagFragmentGenerator();
+ assertEquals("" title=\""abc\"" alt=\""\"""",
+ g.generateToolTipFragment(""abc""));
+ assertEquals("" title=\""Series "A", 100.0\"" alt=\""\"""",
+ g.generateToolTipFragment(""Series \""A\"", 100.0""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testEqualGeneralPaths() {
+ GeneralPath g1 = new GeneralPath();
+ g1.moveTo(1.0f, 2.0f);
+ g1.lineTo(3.0f, 4.0f);
+ g1.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f);
+ g1.quadTo(1.0f, 2.0f, 3.0f, 4.0f);
+ g1.closePath();
+ GeneralPath g2 = new GeneralPath();
+ g2.moveTo(1.0f, 2.0f);
+ g2.lineTo(3.0f, 4.0f);
+ g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f);
+ g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f);
+ g2.closePath();
+ assertTrue(ShapeUtilities.equal(g1, g2));
+
+ g2 = new GeneralPath();
+ g2.moveTo(11.0f, 22.0f);
+ g2.lineTo(3.0f, 4.0f);
+ g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f);
+ g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f);
+ g2.closePath();
+ assertFalse(ShapeUtilities.equal(g1, g2));
+
+ g2 = new GeneralPath();
+ g2.moveTo(1.0f, 2.0f);
+ g2.lineTo(33.0f, 44.0f);
+ g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f);
+ g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f);
+ g2.closePath();
+ assertFalse(ShapeUtilities.equal(g1, g2));
+
+ g2 = new GeneralPath();
+ g2.moveTo(1.0f, 2.0f);
+ g2.lineTo(3.0f, 4.0f);
+ g2.curveTo(55.0f, 66.0f, 77.0f, 88.0f, 99.0f, 100.0f);
+ g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f);
+ g2.closePath();
+ assertFalse(ShapeUtilities.equal(g1, g2));
+
+ g2 = new GeneralPath();
+ g2.moveTo(1.0f, 2.0f);
+ g2.lineTo(3.0f, 4.0f);
+ g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f);
+ g2.quadTo(11.0f, 22.0f, 33.0f, 44.0f);
+ g2.closePath();
+ assertFalse(ShapeUtilities.equal(g1, g2));
+
+ g2 = new GeneralPath();
+ g2.moveTo(1.0f, 2.0f);
+ g2.lineTo(3.0f, 4.0f);
+ g2.curveTo(5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f);
+ g2.quadTo(1.0f, 2.0f, 3.0f, 4.0f);
+ g2.lineTo(3.0f, 4.0f);
+ g2.closePath();
+ assertFalse(ShapeUtilities.equal(g1, g2));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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();
+ }
+
+// Test Case
+[/INST]
+ public void testConstructor() {
+ MultiplePiePlot plot = new MultiplePiePlot();
+ assertNull(plot.getDataset());
+
+ // the following checks that the plot registers itself as a listener
+ // with the dataset passed to the constructor - see patch 1943021
+ DefaultCategoryDataset dataset = new DefaultCategoryDataset();
+ plot = new MultiplePiePlot(dataset);
+ assertTrue(dataset.hasListener(plot));
+ }
+
+ /**
+ * Check that the equals() method distinguishes the required fields.
+ */
+ public void testEquals() {
+ MultiplePiePlot p1 = new MultiplePiePlot();
+ MultiplePiePlot p2 = new MultiplePiePlot();
+ assertTrue(p1.equals(p2));
+ assertTrue(p2.equals(p1));
+
+ p1.setDataExtractOrder(TableOrder.BY_ROW);
+ assertFalse(p1.equals(p2));
+ p2.setDataExtractOrder(TableOrder.BY_ROW);
+ assertTrue(p1.equals(p2));
+
+ p1.setLimit(1.23);
+ assertFalse(p1.equals(p2));
+ p2.setLimit(1.23);
+ assertTrue(p1.equals(p2));
+
+ p1.setAggregatedItemsKey(""Aggregated Items"");
+ assertFalse(p1.equals(p2));
+ p2.setAggregatedItemsKey(""Aggregated Items"");
+ assertTrue(p1.equals(p2));
+
+ p1.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red,
+ 3.0f, 4.0f, Color.yellow));
+ assertFalse(p1.equals(p2));
+ p2.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red,
+ 3.0f, 4.0f, Color.yellow));
+ assertTrue(p1.equals(p2));
+
+ p1.setPieChart(ChartFactory.createPieChart(""Title"", null, true, true,
+ true));
+ assertFalse(p1.equals(p2));
+ p2.setPieChart(ChartFactory.createPieChart(""Title"", null, true, true,
+ true));
+ assertTrue(p1.equals(p2));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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());
+ }
+
+// Test Case
+[/INST]
+ public void testSizingWithWidthConstraint() {
+ RectangleConstraint constraint = new RectangleConstraint(
+ 10.0, new Range(10.0, 10.0), LengthConstraintType.FIXED,
+ 0.0, new Range(0.0, 0.0), LengthConstraintType.NONE
+ );
+
+ BlockContainer container = new BlockContainer(new BorderArrangement());
+ BufferedImage image = new BufferedImage(
+ 200, 100, BufferedImage.TYPE_INT_RGB
+ );
+ Graphics2D g2 = image.createGraphics();
+
+ // TBLRC
+ // 00001 - center item only
+ container.add(new EmptyBlock(5.0, 6.0));
+ Size2D size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(6.0, size.height, EPSILON);
+
+ container.clear();
+ container.add(new EmptyBlock(15.0, 16.0));
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(16.0, size.height, EPSILON);
+
+ // TBLRC
+ // 00010 - right item only
+ container.clear();
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 00011 - right and center items
+ container.clear();
+ container.add(new EmptyBlock(7.0, 20.0));
+ container.add(new EmptyBlock(8.0, 45.6), RectangleEdge.RIGHT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 00100 - left item only
+ container.clear();
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 00101 - left and center items
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0));
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 00110 - left and right items
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 00111 - left, right and center items
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0));
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(5.4, 3.2), RectangleEdge.RIGHT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01000 - bottom item only
+ container.clear();
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01001 - bottom and center only
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0));
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01010 - bottom and right only
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01011 - bottom, right and center
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3));
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01100
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01101 - bottom, left and center
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3));
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01110 - bottom. left and right
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 01111
+ container.clear();
+ container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM);
+ container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(9.0, 10.0));
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(14.0, size.height, EPSILON);
+
+ // TBLRC
+ // 10000 - top item only
+ container.clear();
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(45.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10001 - top and center only
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0));
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10010 - right and top only
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10011 - top, right and center
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3));
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10100 - top and left only
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10101 - top, left and center
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3));
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10110 - top, left and right
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 10111
+ container.clear();
+ container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(9.0, 10.0));
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(12.0, size.height, EPSILON);
+
+ // TBLRC
+ // 11000 - top and bottom only
+ container.clear();
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(65.6, size.height, EPSILON);
+
+ // TBLRC
+ // 11001
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3));
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(77.9, size.height, EPSILON);
+
+ // TBLRC
+ // 11010 - top, bottom and right
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(77.9, size.height, EPSILON);
+
+ // TBLRC
+ // 11011
+ container.clear();
+ container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM);
+ container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(9.0, 10.0));
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(16.0, size.height, EPSILON);
+
+ // TBLRC
+ // 11100
+ container.clear();
+ container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(77.9, size.height, EPSILON);
+
+ // TBLRC
+ // 11101
+ container.clear();
+ container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM);
+ container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(9.0, 10.0));
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(16.0, size.height, EPSILON);
+
+ // TBLRC
+ // 11110
+ container.clear();
+ container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM);
+ container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT);
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(14.0, size.height, EPSILON);
+
+ // TBLRC
+ // 11111 - all
+ container.clear();
+ container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP);
+ container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM);
+ container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT);
+ container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT);
+ container.add(new EmptyBlock(9.0, 10.0));
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(16.0, size.height, EPSILON);
+
+ // TBLRC
+ // 00000 - no items
+ container.clear();
+ size = container.arrange(g2, constraint);
+ assertEquals(10.0, size.width, EPSILON);
+ assertEquals(0.0, size.height, EPSILON);
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean removeDomainMarker(int index, Marker marker, Layer layer,
+ boolean notify) {
+ ArrayList markers;
+ if (layer == Layer.FOREGROUND) {
+ markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(
+ index));
+ }
+ else {
+ markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(
+ index));
+ }
+ boolean removed = markers.remove(marker);
+ if (removed && notify) {
+ fireChangeEvent();
+ }
+ return removed;
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveRangeMarker() {
+ CategoryPlot plot = new CategoryPlot();
+ assertFalse(plot.removeRangeMarker(new ValueMarker(0.5)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean removeDomainMarker(int index, Marker marker, Layer layer,
+ boolean notify) {
+ ArrayList markers;
+ if (layer == Layer.FOREGROUND) {
+ markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(
+ index));
+ }
+ else {
+ markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(
+ index));
+ }
+ boolean removed = markers.remove(marker);
+ if (removed && notify) {
+ fireChangeEvent();
+ }
+ return removed;
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveRangeMarker() {
+ CategoryPlot plot = new CategoryPlot();
+ assertFalse(plot.removeRangeMarker(new ValueMarker(0.5)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean removeRangeMarker(int index, Marker marker, Layer layer,
+ boolean notify) {
+ if (marker == null) {
+ throw new IllegalArgumentException(""Null 'marker' argument."");
+ }
+ ArrayList markers;
+ if (layer == Layer.FOREGROUND) {
+ markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(
+ index));
+ }
+ else {
+ markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(
+ index));
+ }
+ boolean removed = markers.remove(marker);
+ if (removed && notify) {
+ fireChangeEvent();
+ }
+ return removed;
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveRangeMarker() {
+ CategoryPlot plot = new CategoryPlot();
+ assertFalse(plot.removeRangeMarker(new ValueMarker(0.5)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean removeRangeMarker(int index, Marker marker, Layer layer,
+ boolean notify) {
+ if (marker == null) {
+ throw new IllegalArgumentException(""Null 'marker' argument."");
+ }
+ ArrayList markers;
+ if (layer == Layer.FOREGROUND) {
+ markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(
+ index));
+ }
+ else {
+ markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(
+ index));
+ }
+ boolean removed = markers.remove(marker);
+ if (removed && notify) {
+ fireChangeEvent();
+ }
+ return removed;
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveRangeMarker() {
+ CategoryPlot plot = new CategoryPlot();
+ assertFalse(plot.removeRangeMarker(new ValueMarker(0.5)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public double getMaximumExplodePercent() {
+ double result = 0.0;
+ Iterator iterator = this.dataset.getKeys().iterator();
+ while (iterator.hasNext()) {
+ Comparable key = (Comparable) iterator.next();
+ Number explode = (Number) this.explodePercentages.get(key);
+ if (explode != null) {
+ result = Math.max(result, explode.doubleValue());
+ }
+ }
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testDrawWithNullDataset() {
+ JFreeChart chart = ChartFactory.createPieChart3D(""Test"", null, true,
+ false, false);
+ boolean success = false;
+ try {
+ BufferedImage image = new BufferedImage(200 , 100,
+ BufferedImage.TYPE_INT_RGB);
+ Graphics2D g2 = image.createGraphics();
+ chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
+ g2.dispose();
+ success = true;
+ }
+ catch (Exception e) {
+ success = false;
+ }
+ assertTrue(success);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public PiePlotState initialise(Graphics2D g2, Rectangle2D plotArea,
+ PiePlot plot, Integer index, PlotRenderingInfo info) {
+
+ PiePlotState state = new PiePlotState(info);
+ state.setPassesRequired(2);
+ state.setTotal(DatasetUtilities.calculatePieDatasetTotal(
+ plot.getDataset()));
+ state.setLatestAngle(plot.getStartAngle());
+ return state;
+
+ }
+
+// Test Case
+[/INST]
+ public void testDrawWithNullDataset() {
+ JFreeChart chart = ChartFactory.createPieChart3D(""Test"", null, true,
+ false, false);
+ boolean success = false;
+ try {
+ BufferedImage image = new BufferedImage(200 , 100,
+ BufferedImage.TYPE_INT_RGB);
+ Graphics2D g2 = image.createGraphics();
+ chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
+ g2.dispose();
+ success = true;
+ }
+ catch (Exception e) {
+ success = false;
+ }
+ assertTrue(success);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public DefaultIntervalCategoryDataset(Comparable[] seriesKeys,
+ Comparable[] categoryKeys,
+ Number[][] starts,
+ Number[][] ends) {
+
+ this.startData = starts;
+ this.endData = ends;
+
+ if (starts != null && ends != null) {
+
+ String baseName = ""org.jfree.data.resources.DataPackageResources"";
+ ResourceBundle resources = ResourceBundle.getBundle(baseName);
+
+ int seriesCount = starts.length;
+ if (seriesCount != ends.length) {
+ String errMsg = ""DefaultIntervalCategoryDataset: the number ""
+ + ""of series in the start value dataset does ""
+ + ""not match the number of series in the end ""
+ + ""value dataset."";
+ throw new IllegalArgumentException(errMsg);
+ }
+ if (seriesCount > 0) {
+
+ // set up the series names...
+ if (seriesKeys != null) {
+
+ if (seriesKeys.length != seriesCount) {
+ throw new IllegalArgumentException(
+ ""The number of series keys does not ""
+ + ""match the number of series in the data."");
+ }
+
+ this.seriesKeys = seriesKeys;
+ }
+ else {
+ String prefix = resources.getString(
+ ""series.default-prefix"") + "" "";
+ this.seriesKeys = generateKeys(seriesCount, prefix);
+ }
+
+ // set up the category names...
+ int categoryCount = starts[0].length;
+ if (categoryCount != ends[0].length) {
+ String errMsg = ""DefaultIntervalCategoryDataset: the ""
+ + ""number of categories in the start value ""
+ + ""dataset does not match the number of ""
+ + ""categories in the end value dataset."";
+ throw new IllegalArgumentException(errMsg);
+ }
+ if (categoryKeys != null) {
+ if (categoryKeys.length != categoryCount) {
+ throw new IllegalArgumentException(
+ ""The number of category keys does not match ""
+ + ""the number of categories in the data."");
+ }
+ this.categoryKeys = categoryKeys;
+ }
+ else {
+ String prefix = resources.getString(
+ ""categories.default-prefix"") + "" "";
+ this.categoryKeys = generateKeys(categoryCount, prefix);
+ }
+
+ }
+ else {
+ this.seriesKeys = null;
+ this.categoryKeys = null;
+ }
+ }
+
+ }
+
+// Test Case
+[/INST]
+ public void testGetCategoryIndex() {
+ // check an empty dataset
+ DefaultIntervalCategoryDataset empty
+ = new DefaultIntervalCategoryDataset(new double[0][0],
+ new double[0][0]);
+ assertEquals(-1, empty.getCategoryIndex(""ABC""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void setCategoryKeys(Comparable[] categoryKeys) {
+ if (categoryKeys == null) {
+ throw new IllegalArgumentException(""Null 'categoryKeys' argument."");
+ }
+ if (categoryKeys.length != this.startData[0].length) {
+ throw new IllegalArgumentException(
+ ""The number of categories does not match the data."");
+ }
+ for (int i = 0; i < categoryKeys.length; i++) {
+ if (categoryKeys[i] == null) {
+ throw new IllegalArgumentException(
+ ""DefaultIntervalCategoryDataset.setCategoryKeys(): ""
+ + ""null category not permitted."");
+ }
+ }
+ this.categoryKeys = categoryKeys;
+ fireDatasetChanged();
+ }
+
+// Test Case
+[/INST]
+ public void testGetCategoryIndex() {
+ // check an empty dataset
+ DefaultIntervalCategoryDataset empty
+ = new DefaultIntervalCategoryDataset(new double[0][0],
+ new double[0][0]);
+ assertEquals(-1, empty.getCategoryIndex(""ABC""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object clone() throws CloneNotSupportedException {
+ Object clone = createCopy(0, getItemCount() - 1);
+ return clone;
+ }
+
+// Test Case
+[/INST]
+ public void testBug1832432() {
+ TimeSeries s1 = new TimeSeries(""Series"");
+ TimeSeries s2 = null;
+ try {
+ s2 = (TimeSeries) s1.clone();
+ }
+ catch (CloneNotSupportedException e) {
+ e.printStackTrace();
+ }
+ assertTrue(s1 != s2);
+ assertTrue(s1.getClass() == s2.getClass());
+ assertTrue(s1.equals(s2));
+
+ // test independence
+ s1.add(new Day(1, 1, 2007), 100.0);
+ assertFalse(s1.equals(s2));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeValue(int index) {
+ this.keys.remove(index);
+ this.values.remove(index);
+ if (index < this.keys.size()) {
+ rebuildIndex();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBug1835955() {
+ DefaultCategoryDataset d = new DefaultCategoryDataset();
+ d.addValue(1.0, ""R1"", ""C1"");
+ d.addValue(2.0, ""R2"", ""C2"");
+ d.removeColumn(""C2"");
+ d.addValue(3.0, ""R2"", ""C2"");
+ assertEquals(3.0, d.getValue(""R2"", ""C2"").doubleValue(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeValue(Comparable key) {
+ int index = getIndex(key);
+ if (index < 0) {
+ return;
+ }
+ removeValue(index);
+ }
+
+// Test Case
+[/INST]
+ public void testBug1835955() {
+ DefaultCategoryDataset d = new DefaultCategoryDataset();
+ d.addValue(1.0, ""R1"", ""C1"");
+ d.addValue(2.0, ""R2"", ""C2"");
+ d.removeColumn(""C2"");
+ d.addValue(3.0, ""R2"", ""C2"");
+ assertEquals(3.0, d.getValue(""R2"", ""C2"").doubleValue(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeColumn(Comparable columnKey) {
+ Iterator iterator = this.rows.iterator();
+ while (iterator.hasNext()) {
+ DefaultKeyedValues rowData = (DefaultKeyedValues) iterator.next();
+ rowData.removeValue(columnKey);
+ }
+ this.columnKeys.remove(columnKey);
+ }
+
+// Test Case
+[/INST]
+ public void testBug1835955() {
+ DefaultCategoryDataset d = new DefaultCategoryDataset();
+ d.addValue(1.0, ""R1"", ""C1"");
+ d.addValue(2.0, ""R2"", ""C2"");
+ d.removeColumn(""C2"");
+ d.addValue(3.0, ""R2"", ""C2"");
+ assertEquals(3.0, d.getValue(""R2"", ""C2"").doubleValue(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeColumn(Comparable columnKey) {
+ Iterator iterator = this.rows.iterator();
+ while (iterator.hasNext()) {
+ DefaultKeyedValues rowData = (DefaultKeyedValues) iterator.next();
+ rowData.removeValue(columnKey);
+ }
+ this.columnKeys.remove(columnKey);
+ }
+
+// Test Case
+[/INST]
+ public void testBug1835955() {
+ DefaultCategoryDataset d = new DefaultCategoryDataset();
+ d.addValue(1.0, ""R1"", ""C1"");
+ d.addValue(2.0, ""R2"", ""C2"");
+ d.removeColumn(""C2"");
+ d.addValue(3.0, ""R2"", ""C2"");
+ assertEquals(3.0, d.getValue(""R2"", ""C2"").doubleValue(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int getDomainAxisIndex(CategoryAxis axis) {
+ return this.domainAxes.indexOf(axis);
+ }
+
+// Test Case
+[/INST]
+ public void testGetRangeAxisIndex() {
+ CategoryAxis domainAxis1 = new CategoryAxis(""X1"");
+ NumberAxis rangeAxis1 = new NumberAxis(""Y1"");
+ NumberAxis rangeAxis2 = new NumberAxis(""Y2"");
+ CategoryPlot plot = new CategoryPlot(null, domainAxis1, rangeAxis1,
+ null);
+ assertEquals(0, plot.getRangeAxisIndex(rangeAxis1));
+ assertEquals(-1, plot.getRangeAxisIndex(rangeAxis2));
+ plot.setRangeAxis(1, rangeAxis2);
+ assertEquals(1, plot.getRangeAxisIndex(rangeAxis2));
+ assertEquals(-1, plot.getRangeAxisIndex(new NumberAxis(""Y2"")));
+ boolean pass = false;
+ try {
+ plot.getRangeAxisIndex(null);
+ }
+ catch (IllegalArgumentException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int getRangeAxisIndex(ValueAxis axis) {
+ int result = this.rangeAxes.indexOf(axis);
+ if (result < 0) { // try the parent plot
+ Plot parent = getParent();
+ if (parent instanceof CategoryPlot) {
+ CategoryPlot p = (CategoryPlot) parent;
+ result = p.getRangeAxisIndex(axis);
+ }
+ }
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testGetRangeAxisIndex() {
+ CategoryAxis domainAxis1 = new CategoryAxis(""X1"");
+ NumberAxis rangeAxis1 = new NumberAxis(""Y1"");
+ NumberAxis rangeAxis2 = new NumberAxis(""Y2"");
+ CategoryPlot plot = new CategoryPlot(null, domainAxis1, rangeAxis1,
+ null);
+ assertEquals(0, plot.getRangeAxisIndex(rangeAxis1));
+ assertEquals(-1, plot.getRangeAxisIndex(rangeAxis2));
+ plot.setRangeAxis(1, rangeAxis2);
+ assertEquals(1, plot.getRangeAxisIndex(rangeAxis2));
+ assertEquals(-1, plot.getRangeAxisIndex(new NumberAxis(""Y2"")));
+ boolean pass = false;
+ try {
+ plot.getRangeAxisIndex(null);
+ }
+ catch (IllegalArgumentException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Range iterateDomainBounds(XYDataset dataset,
+ boolean includeInterval) {
+ if (dataset == null) {
+ throw new IllegalArgumentException(""Null 'dataset' argument."");
+ }
+ double minimum = Double.POSITIVE_INFINITY;
+ double maximum = Double.NEGATIVE_INFINITY;
+ int seriesCount = dataset.getSeriesCount();
+ double lvalue;
+ double uvalue;
+ if (includeInterval && dataset instanceof IntervalXYDataset) {
+ IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset;
+ for (int series = 0; series < seriesCount; series++) {
+ int itemCount = dataset.getItemCount(series);
+ for (int item = 0; item < itemCount; item++) {
+ lvalue = intervalXYData.getStartXValue(series, item);
+ uvalue = intervalXYData.getEndXValue(series, item);
+ if (!Double.isNaN(lvalue)) {
+ minimum = Math.min(minimum, lvalue);
+ }
+ if (!Double.isNaN(uvalue)) {
+ maximum = Math.max(maximum, uvalue);
+ }
+ }
+ }
+ }
+ else {
+ for (int series = 0; series < seriesCount; series++) {
+ int itemCount = dataset.getItemCount(series);
+ for (int item = 0; item < itemCount; item++) {
+ lvalue = dataset.getXValue(series, item);
+ uvalue = lvalue;
+ if (!Double.isNaN(lvalue)) {
+ minimum = Math.min(minimum, lvalue);
+ maximum = Math.max(maximum, uvalue);
+ }
+ }
+ }
+ }
+ if (minimum > maximum) {
+ return null;
+ }
+ else {
+ return new Range(minimum, maximum);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBug2849731_2() {
+ XYIntervalSeriesCollection d = new XYIntervalSeriesCollection();
+ XYIntervalSeries s = new XYIntervalSeries(""S1"");
+ s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN);
+ d.addSeries(s);
+ Range r = DatasetUtilities.iterateDomainBounds(d);
+ assertEquals(1.0, r.getLowerBound(), EPSILON);
+ assertEquals(1.0, r.getUpperBound(), EPSILON);
+
+ s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN);
+ r = DatasetUtilities.iterateDomainBounds(d);
+ assertEquals(1.0, r.getLowerBound(), EPSILON);
+ assertEquals(1.5, r.getUpperBound(), EPSILON);
+
+ s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN);
+ r = DatasetUtilities.iterateDomainBounds(d);
+ assertEquals(0.5, r.getLowerBound(), EPSILON);
+ assertEquals(1.5, r.getUpperBound(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Range iterateRangeBounds(XYDataset dataset,
+ boolean includeInterval) {
+ double minimum = Double.POSITIVE_INFINITY;
+ double maximum = Double.NEGATIVE_INFINITY;
+ int seriesCount = dataset.getSeriesCount();
+
+ // handle three cases by dataset type
+ if (includeInterval && dataset instanceof IntervalXYDataset) {
+ // handle special case of IntervalXYDataset
+ IntervalXYDataset ixyd = (IntervalXYDataset) dataset;
+ for (int series = 0; series < seriesCount; series++) {
+ int itemCount = dataset.getItemCount(series);
+ for (int item = 0; item < itemCount; item++) {
+ double lvalue = ixyd.getStartYValue(series, item);
+ double uvalue = ixyd.getEndYValue(series, item);
+ if (!Double.isNaN(lvalue)) {
+ minimum = Math.min(minimum, lvalue);
+ }
+ if (!Double.isNaN(uvalue)) {
+ maximum = Math.max(maximum, uvalue);
+ }
+ }
+ }
+ }
+ else if (includeInterval && dataset instanceof OHLCDataset) {
+ // handle special case of OHLCDataset
+ OHLCDataset ohlc = (OHLCDataset) dataset;
+ for (int series = 0; series < seriesCount; series++) {
+ int itemCount = dataset.getItemCount(series);
+ for (int item = 0; item < itemCount; item++) {
+ double lvalue = ohlc.getLowValue(series, item);
+ double uvalue = ohlc.getHighValue(series, item);
+ if (!Double.isNaN(lvalue)) {
+ minimum = Math.min(minimum, lvalue);
+ }
+ if (!Double.isNaN(uvalue)) {
+ maximum = Math.max(maximum, uvalue);
+ }
+ }
+ }
+ }
+ else {
+ // standard case - plain XYDataset
+ for (int series = 0; series < seriesCount; series++) {
+ int itemCount = dataset.getItemCount(series);
+ for (int item = 0; item < itemCount; item++) {
+ double value = dataset.getYValue(series, item);
+ if (!Double.isNaN(value)) {
+ minimum = Math.min(minimum, value);
+ maximum = Math.max(maximum, value);
+ }
+ }
+ }
+ }
+ if (minimum == Double.POSITIVE_INFINITY) {
+ return null;
+ }
+ else {
+ return new Range(minimum, maximum);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBug2849731_2() {
+ XYIntervalSeriesCollection d = new XYIntervalSeriesCollection();
+ XYIntervalSeries s = new XYIntervalSeries(""S1"");
+ s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN);
+ d.addSeries(s);
+ Range r = DatasetUtilities.iterateDomainBounds(d);
+ assertEquals(1.0, r.getLowerBound(), EPSILON);
+ assertEquals(1.0, r.getUpperBound(), EPSILON);
+
+ s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN);
+ r = DatasetUtilities.iterateDomainBounds(d);
+ assertEquals(1.0, r.getLowerBound(), EPSILON);
+ assertEquals(1.5, r.getUpperBound(), EPSILON);
+
+ s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN);
+ r = DatasetUtilities.iterateDomainBounds(d);
+ assertEquals(0.5, r.getLowerBound(), EPSILON);
+ assertEquals(1.5, r.getUpperBound(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ValueMarker(double value, Paint paint, Stroke stroke,
+ Paint outlinePaint, Stroke outlineStroke, float alpha) {
+ super(paint, stroke, paint, stroke, alpha);
+ this.value = value;
+ }
+
+// Test Case
+[/INST]
+ public void test1808376() {
+ Stroke stroke = new BasicStroke(1.0f);
+ Stroke outlineStroke = new BasicStroke(2.0f);
+ ValueMarker m = new ValueMarker(1.0, Color.red, stroke, Color.blue,
+ outlineStroke, 0.5f);
+ assertEquals(1.0, m.getValue(), EPSILON);
+ assertEquals(Color.red, m.getPaint());
+ assertEquals(stroke, m.getStroke());
+ assertEquals(Color.blue, m.getOutlinePaint());
+ assertEquals(outlineStroke, m.getOutlineStroke());
+ assertEquals(0.5f, m.getAlpha(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void add(BoxAndWhiskerItem item, Comparable rowKey,
+ Comparable columnKey) {
+
+ this.data.addObject(item, rowKey, columnKey);
+
+ // update cached min and max values
+ int r = this.data.getRowIndex(rowKey);
+ int c = this.data.getColumnIndex(columnKey);
+ if ((this.maximumRangeValueRow == r && this.maximumRangeValueColumn
+ == c) || (this.minimumRangeValueRow == r
+ && this.minimumRangeValueColumn == c)) {
+ updateBounds();
+ }
+
+ double minval = Double.NaN;
+ if (item.getMinOutlier() != null) {
+ minval = item.getMinOutlier().doubleValue();
+ }
+ double maxval = Double.NaN;
+ if (item.getMaxOutlier() != null) {
+ maxval = item.getMaxOutlier().doubleValue();
+ }
+
+ if (Double.isNaN(this.maximumRangeValue)) {
+ this.maximumRangeValue = maxval;
+ this.maximumRangeValueRow = r;
+ this.maximumRangeValueColumn = c;
+ }
+ else if (maxval > this.maximumRangeValue) {
+ this.maximumRangeValue = maxval;
+ this.maximumRangeValueRow = r;
+ this.maximumRangeValueColumn = c;
+ }
+
+ if (Double.isNaN(this.minimumRangeValue)) {
+ this.minimumRangeValue = minval;
+ this.minimumRangeValueRow = r;
+ this.minimumRangeValueColumn = c;
+ }
+ else if (minval < this.minimumRangeValue) {
+ this.minimumRangeValue = minval;
+ this.minimumRangeValueRow = r;
+ this.minimumRangeValueColumn = c;
+ }
+
+ this.rangeBounds = new Range(this.minimumRangeValue,
+ this.maximumRangeValue);
+ fireDatasetChanged();
+
+ }
+
+// Test Case
+[/INST]
+ public void testGetRangeBounds() {
+ DefaultBoxAndWhiskerCategoryDataset d1
+ = new DefaultBoxAndWhiskerCategoryDataset();
+ d1.add(new BoxAndWhiskerItem(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
+ new ArrayList()), ""R1"", ""C1"");
+ assertEquals(new Range(7.0, 8.0), d1.getRangeBounds(false));
+ assertEquals(new Range(7.0, 8.0), d1.getRangeBounds(true));
+
+ d1.add(new BoxAndWhiskerItem(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5,
+ new ArrayList()), ""R1"", ""C1"");
+ assertEquals(new Range(7.5, 8.5), d1.getRangeBounds(false));
+ assertEquals(new Range(7.5, 8.5), d1.getRangeBounds(true));
+
+ d1.add(new BoxAndWhiskerItem(2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5,
+ new ArrayList()), ""R2"", ""C1"");
+ assertEquals(new Range(7.5, 9.5), d1.getRangeBounds(false));
+ assertEquals(new Range(7.5, 9.5), d1.getRangeBounds(true));
+
+ // this replaces the entry with the current minimum value, but the new
+ // minimum value is now in a different item
+ d1.add(new BoxAndWhiskerItem(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 8.6, 9.6,
+ new ArrayList()), ""R1"", ""C1"");
+ assertEquals(new Range(8.5, 9.6), d1.getRangeBounds(false));
+ assertEquals(new Range(8.5, 9.6), d1.getRangeBounds(true));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateBounds() {
+ this.minimumRangeValue = Double.NaN;
+ this.maximumRangeValue = Double.NaN;
+ }
+
+// Test Case
+[/INST]
+ public void testGetRangeBounds() {
+ DefaultBoxAndWhiskerCategoryDataset d1
+ = new DefaultBoxAndWhiskerCategoryDataset();
+ d1.add(new BoxAndWhiskerItem(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
+ new ArrayList()), ""R1"", ""C1"");
+ assertEquals(new Range(7.0, 8.0), d1.getRangeBounds(false));
+ assertEquals(new Range(7.0, 8.0), d1.getRangeBounds(true));
+
+ d1.add(new BoxAndWhiskerItem(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5,
+ new ArrayList()), ""R1"", ""C1"");
+ assertEquals(new Range(7.5, 8.5), d1.getRangeBounds(false));
+ assertEquals(new Range(7.5, 8.5), d1.getRangeBounds(true));
+
+ d1.add(new BoxAndWhiskerItem(2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5,
+ new ArrayList()), ""R2"", ""C1"");
+ assertEquals(new Range(7.5, 9.5), d1.getRangeBounds(false));
+ assertEquals(new Range(7.5, 9.5), d1.getRangeBounds(true));
+
+ // this replaces the entry with the current minimum value, but the new
+ // minimum value is now in a different item
+ d1.add(new BoxAndWhiskerItem(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 8.6, 9.6,
+ new ArrayList()), ""R1"", ""C1"");
+ assertEquals(new Range(8.5, 9.6), d1.getRangeBounds(false));
+ assertEquals(new Range(8.5, 9.6), d1.getRangeBounds(true));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object getObject(Comparable rowKey, Comparable columnKey) {
+ if (rowKey == null) {
+ throw new IllegalArgumentException(""Null 'rowKey' argument."");
+ }
+ if (columnKey == null) {
+ throw new IllegalArgumentException(""Null 'columnKey' argument."");
+ }
+ int row = this.rowKeys.indexOf(rowKey);
+ if (row < 0) {
+ throw new UnknownKeyException(""Row key ("" + rowKey
+ + "") not recognised."");
+ }
+ int column = this.columnKeys.indexOf(columnKey);
+ if (column < 0) {
+ throw new UnknownKeyException(""Column key ("" + columnKey
+ + "") not recognised."");
+ }
+ if (row >= 0) {
+ KeyedObjects rowData = (KeyedObjects) this.rows.get(row);
+ return rowData.getObject(columnKey);
+ }
+ else {
+ return null;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveColumnByKey() {
+ KeyedObjects2D data = new KeyedObjects2D();
+ data.setObject(""Obj1"", ""R1"", ""C1"");
+ data.setObject(""Obj2"", ""R2"", ""C2"");
+ data.removeColumn(""C2"");
+ assertEquals(1, data.getColumnCount());
+ assertEquals(""Obj1"", data.getObject(0, 0));
+
+ // try unknown column key
+ boolean pass = false;
+ try {
+ data.removeColumn(""XXX"");
+ }
+ catch (UnknownKeyException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+
+ // try null column key
+ pass = false;
+ try {
+ data.removeColumn(null);
+ }
+ catch (IllegalArgumentException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeObject(Comparable rowKey, Comparable columnKey) {
+ setObject(null, rowKey, columnKey);
+
+ // 1. check whether the row is now empty.
+ boolean allNull = true;
+ int rowIndex = getRowIndex(rowKey);
+ KeyedObjects row = (KeyedObjects) this.rows.get(rowIndex);
+
+ for (int item = 0, itemCount = row.getItemCount(); item < itemCount;
+ item++) {
+ if (row.getObject(item) != null) {
+ allNull = false;
+ break;
+ }
+ }
+
+ if (allNull) {
+ this.rowKeys.remove(rowIndex);
+ this.rows.remove(rowIndex);
+ }
+
+ // 2. check whether the column is now empty.
+
+
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveColumnByKey() {
+ KeyedObjects2D data = new KeyedObjects2D();
+ data.setObject(""Obj1"", ""R1"", ""C1"");
+ data.setObject(""Obj2"", ""R2"", ""C2"");
+ data.removeColumn(""C2"");
+ assertEquals(1, data.getColumnCount());
+ assertEquals(""Obj1"", data.getObject(0, 0));
+
+ // try unknown column key
+ boolean pass = false;
+ try {
+ data.removeColumn(""XXX"");
+ }
+ catch (UnknownKeyException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+
+ // try null column key
+ pass = false;
+ try {
+ data.removeColumn(null);
+ }
+ catch (IllegalArgumentException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeRow(Comparable rowKey) {
+ int index = getRowIndex(rowKey);
+ removeRow(index);
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveColumnByKey() {
+ KeyedObjects2D data = new KeyedObjects2D();
+ data.setObject(""Obj1"", ""R1"", ""C1"");
+ data.setObject(""Obj2"", ""R2"", ""C2"");
+ data.removeColumn(""C2"");
+ assertEquals(1, data.getColumnCount());
+ assertEquals(""Obj1"", data.getObject(0, 0));
+
+ // try unknown column key
+ boolean pass = false;
+ try {
+ data.removeColumn(""XXX"");
+ }
+ catch (UnknownKeyException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+
+ // try null column key
+ pass = false;
+ try {
+ data.removeColumn(null);
+ }
+ catch (IllegalArgumentException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeColumn(Comparable columnKey) {
+ int index = getColumnIndex(columnKey);
+ if (index < 0) {
+ throw new UnknownKeyException(""Column key ("" + columnKey
+ + "") not recognised."");
+ }
+ Iterator iterator = this.rows.iterator();
+ while (iterator.hasNext()) {
+ KeyedObjects rowData = (KeyedObjects) iterator.next();
+ rowData.removeValue(columnKey);
+ }
+ this.columnKeys.remove(columnKey);
+ }
+
+// Test Case
+[/INST]
+ public void testRemoveColumnByKey() {
+ KeyedObjects2D data = new KeyedObjects2D();
+ data.setObject(""Obj1"", ""R1"", ""C1"");
+ data.setObject(""Obj2"", ""R2"", ""C2"");
+ data.removeColumn(""C2"");
+ assertEquals(1, data.getColumnCount());
+ assertEquals(""Obj1"", data.getObject(0, 0));
+
+ // try unknown column key
+ boolean pass = false;
+ try {
+ data.removeColumn(""XXX"");
+ }
+ catch (UnknownKeyException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+
+ // try null column key
+ pass = false;
+ try {
+ data.removeColumn(null);
+ }
+ catch (IllegalArgumentException e) {
+ pass = true;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testEquals() {
+ MinMaxCategoryRenderer r1 = new MinMaxCategoryRenderer();
+ MinMaxCategoryRenderer r2 = new MinMaxCategoryRenderer();
+ assertEquals(r1, r2);
+
+ r1.setDrawLines(true);
+ assertFalse(r1.equals(r2));
+ r2.setDrawLines(true);
+ assertTrue(r1.equals(r2));
+
+ r1.setGroupPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f,
+ Color.yellow));
+ assertFalse(r1.equals(r2));
+ r2.setGroupPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f,
+ Color.yellow));
+ assertTrue(r1.equals(r2));
+
+ r1.setGroupStroke(new BasicStroke(1.2f));
+ assertFalse(r1.equals(r2));
+ r2.setGroupStroke(new BasicStroke(1.2f));
+ assertTrue(r1.equals(r2));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+
+// Test Case
+[/INST]
+ public void testGetPaint() {
+ GrayPaintScale gps = new GrayPaintScale();
+ Color c = (Color) gps.getPaint(0.0);
+ assertTrue(c.equals(Color.black));
+ c = (Color) gps.getPaint(1.0);
+ assertTrue(c.equals(Color.white));
+
+ // check lookup values that are outside the bounds - see bug report
+ // 1767315
+ c = (Color) gps.getPaint(-0.5);
+ assertTrue(c.equals(Color.black));
+ c = (Color) gps.getPaint(1.5);
+ assertTrue(c.equals(Color.white));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void drawHorizontalItem(Graphics2D g2,
+ CategoryItemRendererState state,
+ Rectangle2D dataArea,
+ CategoryPlot plot,
+ CategoryAxis domainAxis,
+ ValueAxis rangeAxis,
+ StatisticalCategoryDataset dataset,
+ int row,
+ int column) {
+
+ RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
+
+ // BAR Y
+ double rectY = domainAxis.getCategoryStart(column, getColumnCount(),
+ dataArea, xAxisLocation);
+
+ int seriesCount = getRowCount();
+ int categoryCount = getColumnCount();
+ if (seriesCount > 1) {
+ double seriesGap = dataArea.getHeight() * getItemMargin()
+ / (categoryCount * (seriesCount - 1));
+ rectY = rectY + row * (state.getBarWidth() + seriesGap);
+ }
+ else {
+ rectY = rectY + row * state.getBarWidth();
+ }
+
+ // BAR X
+ Number meanValue = dataset.getMeanValue(row, column);
+
+ double value = meanValue.doubleValue();
+ double base = 0.0;
+ double lclip = getLowerClip();
+ double uclip = getUpperClip();
+
+ if (uclip <= 0.0) { // cases 1, 2, 3 and 4
+ if (value >= uclip) {
+ return; // bar is not visible
+ }
+ base = uclip;
+ if (value <= lclip) {
+ value = lclip;
+ }
+ }
+ else if (lclip <= 0.0) { // cases 5, 6, 7 and 8
+ if (value >= uclip) {
+ value = uclip;
+ }
+ else {
+ if (value <= lclip) {
+ value = lclip;
+ }
+ }
+ }
+ else { // cases 9, 10, 11 and 12
+ if (value <= lclip) {
+ return; // bar is not visible
+ }
+ base = getLowerClip();
+ if (value >= uclip) {
+ value = uclip;
+ }
+ }
+
+ RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
+ double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation);
+ double transY2 = rangeAxis.valueToJava2D(value, dataArea,
+ yAxisLocation);
+ double rectX = Math.min(transY2, transY1);
+
+ double rectHeight = state.getBarWidth();
+ double rectWidth = Math.abs(transY2 - transY1);
+
+ Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth,
+ rectHeight);
+ Paint seriesPaint = getItemPaint(row, column);
+ g2.setPaint(seriesPaint);
+ g2.fill(bar);
+ if (isDrawBarOutline() && state.getBarWidth() > 3) {
+ g2.setStroke(getItemStroke(row, column));
+ g2.setPaint(getItemOutlinePaint(row, column));
+ g2.draw(bar);
+ }
+
+ // standard deviation lines
+ double valueDelta = dataset.getStdDevValue(row, column).doubleValue();
+ double highVal = rangeAxis.valueToJava2D(meanValue.doubleValue()
+ + valueDelta, dataArea, yAxisLocation);
+ double lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue()
+ - valueDelta, dataArea, yAxisLocation);
+
+ if (this.errorIndicatorStroke != null) {
+ g2.setStroke(this.errorIndicatorStroke);
+ }
+ else {
+ g2.setStroke(getItemOutlineStroke(row, column));
+ }
+ if (this.errorIndicatorPaint != null) {
+ g2.setPaint(this.errorIndicatorPaint);
+ }
+ else {
+ g2.setPaint(getItemOutlinePaint(row, column));
+ }
+
+ Line2D line = null;
+ line = new Line2D.Double(lowVal, rectY + rectHeight / 2.0d,
+ highVal, rectY + rectHeight / 2.0d);
+ g2.draw(line);
+ line = new Line2D.Double(highVal, rectY + rectHeight * 0.25,
+ highVal, rectY + rectHeight * 0.75);
+ g2.draw(line);
+ line = new Line2D.Double(lowVal, rectY + rectHeight * 0.25,
+ lowVal, rectY + rectHeight * 0.75);
+ g2.draw(line);
+
+ CategoryItemLabelGenerator generator = getItemLabelGenerator(row,
+ column);
+ if (generator != null && isItemLabelVisible(row, column)) {
+ drawItemLabel(g2, dataset, row, column, plot, generator, bar,
+ (value < 0.0));
+ }
+
+ // add an item entity, if this information is being collected
+ EntityCollection entities = state.getEntityCollection();
+ if (entities != null) {
+ addItemEntity(entities, dataset, row, column, bar);
+ }
+
+ }
+
+// Test Case
+[/INST]
+ public void testDrawWithNullMeanVertical() {
+ boolean success = false;
+ try {
+ DefaultStatisticalCategoryDataset dataset
+ = new DefaultStatisticalCategoryDataset();
+ dataset.add(1.0, 2.0, ""S1"", ""C1"");
+ dataset.add(null, new Double(4.0), ""S1"", ""C2"");
+ CategoryPlot plot = new CategoryPlot(dataset,
+ new CategoryAxis(""Category""), new NumberAxis(""Value""),
+ new StatisticalBarRenderer());
+ JFreeChart chart = new JFreeChart(plot);
+ /* BufferedImage image = */ chart.createBufferedImage(300, 200,
+ null);
+ success = true;
+ }
+ catch (NullPointerException e) {
+ e.printStackTrace();
+ success = false;
+ }
+ assertTrue(success);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void drawVerticalItem(Graphics2D g2,
+ CategoryItemRendererState state,
+ Rectangle2D dataArea,
+ CategoryPlot plot,
+ CategoryAxis domainAxis,
+ ValueAxis rangeAxis,
+ StatisticalCategoryDataset dataset,
+ int row,
+ int column) {
+
+ RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
+
+ // BAR X
+ double rectX = domainAxis.getCategoryStart(
+ column, getColumnCount(), dataArea, xAxisLocation
+ );
+
+ int seriesCount = getRowCount();
+ int categoryCount = getColumnCount();
+ if (seriesCount > 1) {
+ double seriesGap = dataArea.getWidth() * getItemMargin()
+ / (categoryCount * (seriesCount - 1));
+ rectX = rectX + row * (state.getBarWidth() + seriesGap);
+ }
+ else {
+ rectX = rectX + row * state.getBarWidth();
+ }
+
+ // BAR Y
+ Number meanValue = dataset.getMeanValue(row, column);
+
+ double value = meanValue.doubleValue();
+ double base = 0.0;
+ double lclip = getLowerClip();
+ double uclip = getUpperClip();
+
+ if (uclip <= 0.0) { // cases 1, 2, 3 and 4
+ if (value >= uclip) {
+ return; // bar is not visible
+ }
+ base = uclip;
+ if (value <= lclip) {
+ value = lclip;
+ }
+ }
+ else if (lclip <= 0.0) { // cases 5, 6, 7 and 8
+ if (value >= uclip) {
+ value = uclip;
+ }
+ else {
+ if (value <= lclip) {
+ value = lclip;
+ }
+ }
+ }
+ else { // cases 9, 10, 11 and 12
+ if (value <= lclip) {
+ return; // bar is not visible
+ }
+ base = getLowerClip();
+ if (value >= uclip) {
+ value = uclip;
+ }
+ }
+
+ RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
+ double transY1 = rangeAxis.valueToJava2D(base, dataArea, yAxisLocation);
+ double transY2 = rangeAxis.valueToJava2D(value, dataArea,
+ yAxisLocation);
+ double rectY = Math.min(transY2, transY1);
+
+ double rectWidth = state.getBarWidth();
+ double rectHeight = Math.abs(transY2 - transY1);
+
+ Rectangle2D bar = new Rectangle2D.Double(rectX, rectY, rectWidth,
+ rectHeight);
+ Paint seriesPaint = getItemPaint(row, column);
+ g2.setPaint(seriesPaint);
+ g2.fill(bar);
+ if (isDrawBarOutline() && state.getBarWidth() > 3) {
+ g2.setStroke(getItemStroke(row, column));
+ g2.setPaint(getItemOutlinePaint(row, column));
+ g2.draw(bar);
+ }
+
+ // standard deviation lines
+ double valueDelta = dataset.getStdDevValue(row, column).doubleValue();
+ double highVal = rangeAxis.valueToJava2D(meanValue.doubleValue()
+ + valueDelta, dataArea, yAxisLocation);
+ double lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue()
+ - valueDelta, dataArea, yAxisLocation);
+
+ if (this.errorIndicatorStroke != null) {
+ g2.setStroke(this.errorIndicatorStroke);
+ }
+ else {
+ g2.setStroke(getItemOutlineStroke(row, column));
+ }
+ if (this.errorIndicatorPaint != null) {
+ g2.setPaint(this.errorIndicatorPaint);
+ }
+ else {
+ g2.setPaint(getItemOutlinePaint(row, column));
+ }
+ Line2D line = null;
+ line = new Line2D.Double(rectX + rectWidth / 2.0d, lowVal,
+ rectX + rectWidth / 2.0d, highVal);
+ g2.draw(line);
+ line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, highVal,
+ rectX + rectWidth / 2.0d + 5.0d, highVal);
+ g2.draw(line);
+ line = new Line2D.Double(rectX + rectWidth / 2.0d - 5.0d, lowVal,
+ rectX + rectWidth / 2.0d + 5.0d, lowVal);
+ g2.draw(line);
+
+ CategoryItemLabelGenerator generator = getItemLabelGenerator(row,
+ column);
+ if (generator != null && isItemLabelVisible(row, column)) {
+ drawItemLabel(g2, dataset, row, column, plot, generator, bar,
+ (value < 0.0));
+ }
+
+ // add an item entity, if this information is being collected
+ EntityCollection entities = state.getEntityCollection();
+ if (entities != null) {
+ addItemEntity(entities, dataset, row, column, bar);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDrawWithNullMeanVertical() {
+ boolean success = false;
+ try {
+ DefaultStatisticalCategoryDataset dataset
+ = new DefaultStatisticalCategoryDataset();
+ dataset.add(1.0, 2.0, ""S1"", ""C1"");
+ dataset.add(null, new Double(4.0), ""S1"", ""C2"");
+ CategoryPlot plot = new CategoryPlot(dataset,
+ new CategoryAxis(""Category""), new NumberAxis(""Value""),
+ new StatisticalBarRenderer());
+ JFreeChart chart = new JFreeChart(plot);
+ /* BufferedImage image = */ chart.createBufferedImage(300, 200,
+ null);
+ success = true;
+ }
+ catch (NullPointerException e) {
+ e.printStackTrace();
+ success = false;
+ }
+ assertTrue(success);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+
+ }
+
+// Test Case
+[/INST]
+ public void testDrawWithNullInfo() {
+ boolean success = false;
+ try {
+ BufferedImage image = new BufferedImage(200 , 100,
+ BufferedImage.TYPE_INT_RGB);
+ Graphics2D g2 = image.createGraphics();
+ this.chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null,
+ null);
+ g2.dispose();
+ success = true;
+ }
+ catch (Exception e) {
+ success = false;
+ }
+ assertTrue(success);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testCreateCopy3() throws CloneNotSupportedException {
+ TimeSeries s1 = new TimeSeries(""S1"");
+ s1.add(new Year(2009), 100.0);
+ s1.add(new Year(2010), 101.0);
+ s1.add(new Year(2011), 102.0);
+ assertEquals(100.0, s1.getMinY(), EPSILON);
+ assertEquals(102.0, s1.getMaxY(), EPSILON);
+
+ TimeSeries s2 = s1.createCopy(0, 1);
+ assertEquals(100.0, s2.getMinY(), EPSILON);
+ assertEquals(101.0, s2.getMaxY(), EPSILON);
+
+ TimeSeries s3 = s1.createCopy(1, 2);
+ assertEquals(101.0, s3.getMinY(), EPSILON);
+ assertEquals(102.0, s3.getMaxY(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+
+ }
+
+// Test Case
+[/INST]
+ public void testXYAutoRange1() {
+ XYSeries series = new XYSeries(""Series 1"");
+ series.add(1.0, 1.0);
+ series.add(2.0, 2.0);
+ series.add(3.0, 3.0);
+ XYSeriesCollection dataset = new XYSeriesCollection();
+ dataset.addSeries(series);
+ JFreeChart chart = ChartFactory.createScatterPlot(
+ ""Test"",
+ ""X"",
+ ""Y"",
+ dataset,
+ PlotOrientation.VERTICAL,
+ false,
+ false,
+ false
+ );
+ XYPlot plot = (XYPlot) chart.getPlot();
+ LogAxis axis = new LogAxis(""Log(Y)"");
+ plot.setRangeAxis(axis);
+ assertEquals(0.9465508226401592, axis.getLowerBound(), EPSILON);
+ assertEquals(3.1694019256486126, axis.getUpperBound(), EPSILON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testBug1955483() {
+ XYSeries series = new XYSeries(""Series"", true, true);
+ series.addOrUpdate(1.0, 1.0);
+ series.addOrUpdate(1.0, 2.0);
+ assertEquals(new Double(1.0), series.getY(0));
+ assertEquals(new Double(2.0), series.getY(1));
+ assertEquals(2, series.getItemCount());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean equals(Object obj) {
+
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof ShapeList)) {
+ return false;
+ }
+ return super.equals(obj);
+
+ }
+
+// Test Case
+[/INST]
+ public void testSerialization() {
+
+ ShapeList l1 = new ShapeList();
+ l1.setShape(0, new Rectangle(1, 2, 3, 4));
+ l1.setShape(1, new Line2D.Double(1.0, 2.0, 3.0, 4.0));
+ l1.setShape(2, null);
+
+ ShapeList l2 = null;
+
+ try {
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ ObjectOutput out = new ObjectOutputStream(buffer);
+ out.writeObject(l1);
+ out.close();
+
+ ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(
+ buffer.toByteArray()));
+ l2 = (ShapeList) in.readObject();
+ in.close();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ assertEquals(l1, l2);
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+ }
+
+// Test Case
+[/INST]
+ public void testGetMaxMiddleIndex() {
+ TimePeriodValues s = new TimePeriodValues(""Test"");
+ assertEquals(-1, s.getMaxMiddleIndex());
+ s.add(new SimpleTimePeriod(100L, 200L), 1.0);
+ assertEquals(0, s.getMaxMiddleIndex());
+ s.add(new SimpleTimePeriod(300L, 400L), 2.0);
+ assertEquals(1, s.getMaxMiddleIndex());
+ s.add(new SimpleTimePeriod(0L, 50L), 3.0);
+ assertEquals(1, s.getMaxMiddleIndex());
+ s.add(new SimpleTimePeriod(150L, 200L), 4.0);
+ assertEquals(1, s.getMaxMiddleIndex());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Week(Date time, TimeZone zone) {
+ // defer argument checking...
+ this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault());
+ }
+
+// Test Case
+[/INST]
+ public void testConstructor() {
+ Locale savedLocale = Locale.getDefault();
+ TimeZone savedZone = TimeZone.getDefault();
+ Locale.setDefault(new Locale(""da"", ""DK""));
+ TimeZone.setDefault(TimeZone.getTimeZone(""Europe/Copenhagen""));
+ GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(
+ TimeZone.getDefault(), Locale.getDefault());
+
+ // first day of week is monday
+ assertEquals(Calendar.MONDAY, cal.getFirstDayOfWeek());
+ cal.set(2007, Calendar.AUGUST, 26, 1, 0, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+ Date t = cal.getTime();
+ Week w = new Week(t, TimeZone.getTimeZone(""Europe/Copenhagen""));
+ assertEquals(34, w.getWeek());
+
+ Locale.setDefault(Locale.US);
+ TimeZone.setDefault(TimeZone.getTimeZone(""US/Detroit""));
+ cal = (GregorianCalendar) Calendar.getInstance(TimeZone.getDefault());
+ // first day of week is Sunday
+ assertEquals(Calendar.SUNDAY, cal.getFirstDayOfWeek());
+ cal.set(2007, Calendar.AUGUST, 26, 1, 0, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+
+ t = cal.getTime();
+ w = new Week(t, TimeZone.getTimeZone(""Europe/Copenhagen""));
+ assertEquals(35, w.getWeek());
+ w = new Week(t, TimeZone.getTimeZone(""Europe/Copenhagen""),
+ new Locale(""da"", ""DK""));
+ assertEquals(34, w.getWeek());
+
+ Locale.setDefault(savedLocale);
+ TimeZone.setDefault(savedZone);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+
+ }
+
+// Test Case
+[/INST]
+ public void testBug1864222() {
+ TimeSeries s = new TimeSeries(""S"");
+ s.add(new Day(19, 8, 2005), 1);
+ s.add(new Day(31, 1, 2006), 1);
+ boolean pass = true;
+ try {
+ s.createCopy(new Day(1, 12, 2005), new Day(18, 1, 2006));
+ }
+ catch (CloneNotSupportedException e) {
+ pass = false;
+ }
+ assertTrue(pass);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean hasOption(String opt)
+ {
+ return options.containsKey(opt);
+ }
+
+// Test Case
+[/INST]
+public void testCLI13()
+ throws ParseException
+ {
+ final String debugOpt = ""debug"";
+ Option debug = OptionBuilder
+ .withArgName( debugOpt )
+ .withDescription( ""turn on debugging"" )
+ .withLongOpt( debugOpt )
+ .hasArg()
+ .create( 'd' );
+ Options options = new Options();
+ options.addOption( debug );
+ CommandLine commandLine = new PosixParser().parse( options, new String[]{""-d"", ""true""} );
+
+ assertEquals(""true"", commandLine.getOptionValue( debugOpt ));
+ assertEquals(""true"", commandLine.getOptionValue( 'd' ));
+ assertTrue(commandLine.hasOption( 'd'));
+ assertTrue(commandLine.hasOption( debugOpt));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object getOptionObject(String opt)
+ {
+ String res = getOptionValue(opt);
+
+ if (!options.containsKey(opt))
+ {
+ return null;
+ }
+
+ Object type = ((Option) options.get(opt)).getType();
+
+ return (res == null) ? null : TypeHandler.createValue(res, type);
+ }
+
+// Test Case
+[/INST]
+public void testCLI13()
+ throws ParseException
+ {
+ final String debugOpt = ""debug"";
+ Option debug = OptionBuilder
+ .withArgName( debugOpt )
+ .withDescription( ""turn on debugging"" )
+ .withLongOpt( debugOpt )
+ .hasArg()
+ .create( 'd' );
+ Options options = new Options();
+ options.addOption( debug );
+ CommandLine commandLine = new PosixParser().parse( options, new String[]{""-d"", ""true""} );
+
+ assertEquals(""true"", commandLine.getOptionValue( debugOpt ));
+ assertEquals(""true"", commandLine.getOptionValue( 'd' ));
+ assertTrue(commandLine.hasOption( 'd'));
+ assertTrue(commandLine.hasOption( debugOpt));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String[] getOptionValues(String opt)
+ {
+ opt = Util.stripLeadingHyphens(opt);
+
+ String key = opt;
+ if (names.containsKey(opt))
+ {
+ key = (String) names.get(opt);
+ }
+ if (options.containsKey(key))
+ {
+ return ((Option) options.get(key)).getValues();
+ }
+
+ return null;
+ }
+
+// Test Case
+[/INST]
+public void testCLI13()
+ throws ParseException
+ {
+ final String debugOpt = ""debug"";
+ Option debug = OptionBuilder
+ .withArgName( debugOpt )
+ .withDescription( ""turn on debugging"" )
+ .withLongOpt( debugOpt )
+ .hasArg()
+ .create( 'd' );
+ Options options = new Options();
+ options.addOption( debug );
+ CommandLine commandLine = new PosixParser().parse( options, new String[]{""-d"", ""true""} );
+
+ assertEquals(""true"", commandLine.getOptionValue( debugOpt ));
+ assertEquals(""true"", commandLine.getOptionValue( 'd' ));
+ assertTrue(commandLine.hasOption( 'd'));
+ assertTrue(commandLine.hasOption( debugOpt));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void addOption(Option opt)
+ {
+ hashcodeMap.put(new Integer(opt.hashCode()), opt);
+ String key = opt.getKey();
+ if (key == null)
+ {
+ key = opt.getLongOpt();
+ }
+ else
+ {
+ names.put(opt.getLongOpt(), key);
+ }
+ options.put(key, opt);
+ }
+
+// Test Case
+[/INST]
+public void testCLI13()
+ throws ParseException
+ {
+ final String debugOpt = ""debug"";
+ Option debug = OptionBuilder
+ .withArgName( debugOpt )
+ .withDescription( ""turn on debugging"" )
+ .withLongOpt( debugOpt )
+ .hasArg()
+ .create( 'd' );
+ Options options = new Options();
+ options.addOption( debug );
+ CommandLine commandLine = new PosixParser().parse( options, new String[]{""-d"", ""true""} );
+
+ assertEquals(""true"", commandLine.getOptionValue( debugOpt ));
+ assertEquals(""true"", commandLine.getOptionValue( 'd' ));
+ assertTrue(commandLine.hasOption( 'd'));
+ assertTrue(commandLine.hasOption( debugOpt));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Iterator iterator()
+ {
+ return hashcodeMap.values().iterator();
+ }
+
+// Test Case
+[/INST]
+public void testCLI13()
+ throws ParseException
+ {
+ final String debugOpt = ""debug"";
+ Option debug = OptionBuilder
+ .withArgName( debugOpt )
+ .withDescription( ""turn on debugging"" )
+ .withLongOpt( debugOpt )
+ .hasArg()
+ .create( 'd' );
+ Options options = new Options();
+ options.addOption( debug );
+ CommandLine commandLine = new PosixParser().parse( options, new String[]{""-d"", ""true""} );
+
+ assertEquals(""true"", commandLine.getOptionValue( debugOpt ));
+ assertEquals(""true"", commandLine.getOptionValue( 'd' ));
+ assertTrue(commandLine.hasOption( 'd'));
+ assertTrue(commandLine.hasOption( debugOpt));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Option[] getOptions()
+ {
+ Collection processed = options.values();
+
+ // reinitialise array
+ Option[] optionsArray = new Option[processed.size()];
+
+ // return the array
+ return (Option[]) processed.toArray(optionsArray);
+ }
+
+// Test Case
+[/INST]
+public void testCLI13()
+ throws ParseException
+ {
+ final String debugOpt = ""debug"";
+ Option debug = OptionBuilder
+ .withArgName( debugOpt )
+ .withDescription( ""turn on debugging"" )
+ .withLongOpt( debugOpt )
+ .hasArg()
+ .create( 'd' );
+ Options options = new Options();
+ options.addOption( debug );
+ CommandLine commandLine = new PosixParser().parse( options, new String[]{""-d"", ""true""} );
+
+ assertEquals(""true"", commandLine.getOptionValue( debugOpt ));
+ assertEquals(""true"", commandLine.getOptionValue( 'd' ));
+ assertTrue(commandLine.hasOption( 'd'));
+ assertTrue(commandLine.hasOption( debugOpt));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void setOptions(final Options options) {
+ this.options = options;
+ this.requiredOptions = options.getRequiredOptions();
+ }
+
+// Test Case
+[/INST]
+ public void testReuseOptionsTwice() throws Exception
+ {
+ Options opts = new Options();
+ opts.addOption(OptionBuilder.isRequired().create('v'));
+
+ GnuParser parser = new GnuParser();
+
+ // first parsing
+ parser.parse(opts, new String[] { ""-v"" });
+
+ try
+ {
+ // second parsing, with the same Options instance and an invalid command line
+ parser.parse(opts, new String[0]);
+ fail(""MissingOptionException not thrown"");
+ }
+ catch (MissingOptionException e)
+ {
+ // expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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(""]"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPrintOptionWithEmptyArgNameUsage() {
+ Option option = new Option(""f"", true, null);
+ option.setArgName("""");
+ option.setRequired(true);
+
+ Options options = new Options();
+ options.addOption(option);
+
+ StringWriter out = new StringWriter();
+
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printUsage(new PrintWriter(out), 80, ""app"", options);
+
+ assertEquals(""usage: app -f"" + EOL, out.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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()]);
+ }
+
+// Test Case
+[/INST]
+ public void testShortWithEqual() throws Exception
+ {
+ String[] args = new String[] { ""-f=bar"" };
+
+ Options options = new Options();
+ options.addOption(OptionBuilder.withLongOpt(""foo"").hasArg().create('f'));
+
+ Parser parser = new GnuParser();
+ CommandLine cl = parser.parse(options, args);
+
+ assertEquals(""bar"", cl.getOptionValue(""foo""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void processValues(final WriteableCommandLine commandLine,
+ final ListIterator arguments,
+ final Option option)
+ throws OptionException {
+ // count of arguments processed for this option.
+ int argumentCount = 0;
+
+ while (arguments.hasNext() && (argumentCount < maximum)) {
+ final String allValuesQuoted = (String) arguments.next();
+ final String allValues = stripBoundaryQuotes(allValuesQuoted);
+
+ // should we ignore things that look like options?
+ if (allValuesQuoted.equals(consumeRemaining)) {
+ while (arguments.hasNext() && (argumentCount < maximum)) {
+ ++argumentCount;
+ commandLine.addValue(option, arguments.next());
+ }
+ }
+ // does it look like an option?
+ else if (commandLine.looksLikeOption(allValuesQuoted)) {
+ arguments.previous();
+
+ break;
+ }
+ // should we split the string up?
+ else if (subsequentSplit) {
+ final StringTokenizer values =
+ new StringTokenizer(allValues, String.valueOf(subsequentSeparator));
+
+ arguments.remove();
+
+ while (values.hasMoreTokens() && (argumentCount < maximum)) {
+ ++argumentCount;
+
+ final String token = values.nextToken();
+ commandLine.addValue(option, token);
+ arguments.add(token);
+ }
+
+ if (values.hasMoreTokens()) {
+ throw new OptionException(option, ResourceConstants.ARGUMENT_UNEXPECTED_VALUE,
+ values.nextToken());
+ }
+ }
+ // it must be a value as it is
+ else {
+ ++argumentCount;
+ commandLine.addValue(option, allValues);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLoopingOptionLookAlike2() {
+ final ArgumentBuilder abuilder = new ArgumentBuilder();
+ final GroupBuilder gbuilder = new GroupBuilder();
+ final Argument inputfile_opt = abuilder.withName(""input"").withMinimum(1).withMaximum(1).create();
+ final Argument outputfile_opt = abuilder.withName(""output"").withMinimum(1).withMaximum(1).create();
+ final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt);
+ final Group options = gbuilder.withOption(targets).create();
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+ try {
+ parser.parse(new String[] { ""testfile.txt"", ""testfile.txt"", ""testfile.txt"", ""testfile.txt"" });
+ fail(""OptionException"");
+ } catch (OptionException e) {
+ assertEquals(""Unexpected testfile.txt while processing "", e.getMessage());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testLoopingOptionLookAlike2() {
+ final ArgumentBuilder abuilder = new ArgumentBuilder();
+ final GroupBuilder gbuilder = new GroupBuilder();
+ final Argument inputfile_opt = abuilder.withName(""input"").withMinimum(1).withMaximum(1).create();
+ final Argument outputfile_opt = abuilder.withName(""output"").withMinimum(1).withMaximum(1).create();
+ final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt);
+ final Group options = gbuilder.withOption(targets).create();
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+ try {
+ parser.parse(new String[] { ""testfile.txt"", ""testfile.txt"", ""testfile.txt"", ""testfile.txt"" });
+ fail(""OptionException"");
+ } catch (OptionException e) {
+ assertEquals(""Unexpected testfile.txt while processing "", e.getMessage());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testLoopingOptionLookAlike2() {
+ final ArgumentBuilder abuilder = new ArgumentBuilder();
+ final GroupBuilder gbuilder = new GroupBuilder();
+ final Argument inputfile_opt = abuilder.withName(""input"").withMinimum(1).withMaximum(1).create();
+ final Argument outputfile_opt = abuilder.withName(""output"").withMinimum(1).withMaximum(1).create();
+ final Argument targets = new SourceDestArgument(inputfile_opt, outputfile_opt);
+ final Group options = gbuilder.withOption(targets).create();
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+ try {
+ parser.parse(new String[] { ""testfile.txt"", ""testfile.txt"", ""testfile.txt"", ""testfile.txt"" });
+ fail(""OptionException"");
+ } catch (OptionException e) {
+ assertEquals(""Unexpected testfile.txt while processing "", e.getMessage());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testFileValidator() {
+ final DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
+ final ArgumentBuilder abuilder = new ArgumentBuilder();
+ final GroupBuilder gbuilder = new GroupBuilder();
+ DefaultOption fileNameOption = obuilder.withShortName(""f"")
+ .withLongName(""file-name"").withRequired(true).withDescription(
+ ""name of an existing file"").withArgument(
+ abuilder.withName(""file-name"").withValidator(
+ FileValidator.getExistingFileInstance())
+ .create()).create();
+ Group options = gbuilder.withName(""options"").withOption(fileNameOption)
+ .create();
+ Parser parser = new Parser();
+ parser.setHelpTrigger(""--help"");
+ parser.setGroup(options);
+
+ final String fileName = ""src/test/org/apache/commons/cli2/bug/BugCLI144Test.java"";
+ CommandLine cl = parser
+ .parseAndHelp(new String[] { ""--file-name"", fileName });
+ assertNotNull(cl);
+ assertEquals(""Wrong file"", new File(fileName), cl.getValue(fileNameOption));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testSingleOptionSingleArgument() throws Exception {
+ Parser parser = createDefaultValueParser(new String[]{""100"", ""1000""});
+ String enteredValue1 = ""1"";
+ String[] args = new String[]{""-b"", enteredValue1};
+ CommandLine cl = parser.parse(args);
+ CommandLine cmd = cl;
+ assertNotNull(cmd);
+ List b = cmd.getValues(""-b"");
+ assertEquals(""["" + enteredValue1 + "", 1000]"", b + """");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public GroupImpl(final List options,
+ final String name,
+ final String description,
+ final int minimum,
+ final int maximum) {
+ super(0, false);
+
+ this.name = name;
+ this.description = description;
+ this.minimum = minimum;
+ this.maximum = maximum;
+
+ // store a copy of the options to be used by the
+ // help methods
+ this.options = Collections.unmodifiableList(options);
+
+ // anonymous Argument temporary storage
+ final List newAnonymous = new ArrayList();
+
+ // map (key=trigger & value=Option) temporary storage
+ final SortedMap newOptionMap = new TreeMap(ReverseStringComparator.getInstance());
+
+ // prefixes temporary storage
+ final Set newPrefixes = new HashSet();
+
+ // process the options
+ for (final Iterator i = options.iterator(); i.hasNext();) {
+ final Option option = (Option) i.next();
+
+ if (option instanceof Argument) {
+ i.remove();
+ newAnonymous.add(option);
+ } else {
+ final Set triggers = option.getTriggers();
+
+ for (Iterator j = triggers.iterator(); j.hasNext();) {
+ newOptionMap.put(j.next(), option);
+ }
+
+ // store the prefixes
+ newPrefixes.addAll(option.getPrefixes());
+ }
+ }
+
+ this.anonymous = Collections.unmodifiableList(newAnonymous);
+ this.optionMap = Collections.unmodifiableSortedMap(newOptionMap);
+ this.prefixes = Collections.unmodifiableSet(newPrefixes);
+ }
+
+// Test Case
+[/INST]
+ public void testMultipleChildOptions() throws OptionException {
+ CommandLine cl = parser.parse(new String[] { ""--child"", ""test"",
+ ""--sub"", ""anotherTest"" });
+ assertTrue(""Child option not found"", cl.hasOption(childOption1));
+ assertEquals(""Wrong value for option"", ""test"", cl
+ .getValue(childOption1));
+ assertTrue(""Sub option not found"", cl.hasOption(childOption2));
+ assertEquals(""Wrong value for sub option"", ""anotherTest"", cl
+ .getValue(childOption2));
+ assertTrue(""Child group not found"", cl.hasOption(childGroup));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void addOption(Option option) {
+ options.add(option);
+ nameToOption.put(option.getPreferredName(), option);
+
+ for (Iterator i = option.getTriggers().iterator(); i.hasNext();) {
+ nameToOption.put(i.next(), option);
+ }
+
+ // ensure that all parent options are also added
+ }
+
+// Test Case
+[/INST]
+ public void testMultipleChildOptions() throws OptionException {
+ CommandLine cl = parser.parse(new String[] { ""--child"", ""test"",
+ ""--sub"", ""anotherTest"" });
+ assertTrue(""Child option not found"", cl.hasOption(childOption1));
+ assertEquals(""Wrong value for option"", ""test"", cl
+ .getValue(childOption1));
+ assertTrue(""Sub option not found"", cl.hasOption(childOption2));
+ assertEquals(""Wrong value for sub option"", ""anotherTest"", cl
+ .getValue(childOption2));
+ assertTrue(""Child group not found"", cl.hasOption(childGroup));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMultipleChildOptions() throws OptionException {
+ CommandLine cl = parser.parse(new String[] { ""--child"", ""test"",
+ ""--sub"", ""anotherTest"" });
+ assertTrue(""Child option not found"", cl.hasOption(childOption1));
+ assertEquals(""Wrong value for option"", ""test"", cl
+ .getValue(childOption1));
+ assertTrue(""Sub option not found"", cl.hasOption(childOption2));
+ assertEquals(""Wrong value for sub option"", ""anotherTest"", cl
+ .getValue(childOption2));
+ assertTrue(""Child group not found"", cl.hasOption(childGroup));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMultipleChildOptions() throws OptionException {
+ CommandLine cl = parser.parse(new String[] { ""--child"", ""test"",
+ ""--sub"", ""anotherTest"" });
+ assertTrue(""Child option not found"", cl.hasOption(childOption1));
+ assertEquals(""Wrong value for option"", ""test"", cl
+ .getValue(childOption1));
+ assertTrue(""Sub option not found"", cl.hasOption(childOption2));
+ assertEquals(""Wrong value for sub option"", ""anotherTest"", cl
+ .getValue(childOption2));
+ assertTrue(""Child group not found"", cl.hasOption(childGroup));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testStopBursting() throws Exception
+ {
+ String[] args = new String[] { ""-azc"" };
+
+ CommandLine cl = parser.parse(options, args, true);
+ assertTrue( ""Confirm -a is set"", cl.hasOption(""a"") );
+ assertFalse( ""Confirm -c is not set"", cl.hasOption(""c"") );
+
+ assertTrue( ""Confirm 1 extra arg: "" + cl.getArgList().size(), cl.getArgList().size() == 1);
+ assertTrue(cl.getArgList().contains(""zc""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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 SPECIAL TOKEN
+ 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))
+ {
+ processSingleHyphen(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()]);
+ }
+
+// Test Case
+[/INST]
+ public void testStop2() throws Exception
+ {
+ String[] args = new String[]{""-z"",
+ ""-a"",
+ ""-btoast""};
+
+ CommandLine cl = parser.parse(options, args, true);
+ assertFalse(""Confirm -a is not set"", cl.hasOption(""a""));
+ assertTrue(""Confirm 3 extra args: "" + cl.getArgList().size(), cl.getArgList().size() == 3);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processSingleHyphen(String hyphen)
+ {
+ tokens.add(hyphen);
+ }
+
+// Test Case
+[/INST]
+ public void testStop2() throws Exception
+ {
+ String[] args = new String[]{""-z"",
+ ""-a"",
+ ""-btoast""};
+
+ CommandLine cl = parser.parse(options, args, true);
+ assertFalse(""Confirm -a is not set"", cl.hasOption(""a""));
+ assertTrue(""Confirm 3 extra args: "" + cl.getArgList().size(), cl.getArgList().size() == 3);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processOptionToken(String token, boolean stopAtNonOption)
+ {
+ if (options.hasOption(token))
+ {
+ currentOption = options.getOption(token);
+ tokens.add(token);
+ }
+ else if (stopAtNonOption)
+ {
+ eatTheRest = true;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testStop2() throws Exception
+ {
+ String[] args = new String[]{""-z"",
+ ""-a"",
+ ""-btoast""};
+
+ CommandLine cl = parser.parse(options, args, true);
+ assertFalse(""Confirm -a is not set"", cl.hasOption(""a""));
+ assertTrue(""Confirm 3 extra args: "" + cl.getArgList().size(), cl.getArgList().size() == 3);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testUnrecognizedOption2() throws Exception
+ {
+ String[] args = new String[] { ""-z"", ""-abtoast"", ""foo"", ""bar"" };
+
+ try
+ {
+ parser.parse(options, args);
+ fail(""UnrecognizedOptionException wasn't thrown"");
+ }
+ catch (UnrecognizedOptionException e)
+ {
+ assertEquals(""-z"", e.getOption());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void burstToken(String token, boolean stopAtNonOption)
+ {
+ int tokenLength = token.length();
+
+ for (int i = 1; i < tokenLength; i++)
+ {
+ String ch = String.valueOf(token.charAt(i));
+ boolean hasOption = options.hasOption(ch);
+
+ if (hasOption)
+ {
+ tokens.add(""-"" + ch);
+ currentOption = options.getOption(ch);
+
+ if (currentOption.hasArg() && (token.length() != (i + 1)))
+ {
+ tokens.add(token.substring(i + 1));
+
+ break;
+ }
+ }
+ else if (stopAtNonOption)
+ {
+ process(token.substring(i));
+ }
+ else
+ {
+ tokens.add(""-"" + ch);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void test() throws Exception
+ {
+ Options options = buildCommandLineOptions();
+ CommandLineParser parser = new PosixParser();
+ String[] args = new String[] {""-t"", ""-something"" };
+ CommandLine commandLine;
+ commandLine = parser.parse( options, args );
+ assertEquals(""-something"", commandLine.getOptionValue( 't'));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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()]);
+ }
+
+// Test Case
+[/INST]
+ public void testStop3() throws Exception
+ {
+ String[] args = new String[]{""--zop==1"",
+ ""-abtoast"",
+ ""--b=bar""};
+
+ CommandLine cl = parser.parse(options, args, true);
+
+ assertFalse(""Confirm -a is not set"", cl.hasOption(""a""));
+ assertFalse(""Confirm -b is not set"", cl.hasOption(""b""));
+ assertTrue(""Confirm 3 extra args: "" + cl.getArgList().size(), cl.getArgList().size() == 3);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public WriteableCommandLineImpl(final Option rootOption,
+ final List arguments) {
+ this.prefixes = rootOption.getPrefixes();
+ this.normalised = arguments;
+ }
+
+// Test Case
+[/INST]
+ public void testNegativeNumber() throws OptionException
+ {
+ final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder();
+ final ArgumentBuilder aBuilder = new ArgumentBuilder();
+ final GroupBuilder gBuilder = new GroupBuilder();
+
+ final Argument numArg = aBuilder.withValidator(
+ NumberValidator.getNumberInstance()).withMinimum(1)
+ .withMaximum(1).create();
+ final Option numOpt = oBuilder.withLongName(""num"").withArgument(numArg)
+ .create();
+ final Group options = gBuilder.withOption(numOpt).create();
+
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+
+ CommandLine cl = parser.parse(new String[] {
+ ""--num"", ""-42""
+ });
+ Number num = (Number) cl.getValue(numOpt);
+ assertEquals(""Wrong option value"", -42, num.intValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean looksLikeOption(final String trigger)
+ {
+ // this is a reentrant call
+
+ for (final Iterator i = prefixes.iterator(); i.hasNext();)
+ {
+ final String prefix = (String) i.next();
+
+ if (trigger.startsWith(prefix))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testNegativeNumber() throws OptionException
+ {
+ final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder();
+ final ArgumentBuilder aBuilder = new ArgumentBuilder();
+ final GroupBuilder gBuilder = new GroupBuilder();
+
+ final Argument numArg = aBuilder.withValidator(
+ NumberValidator.getNumberInstance()).withMinimum(1)
+ .withMaximum(1).create();
+ final Option numOpt = oBuilder.withLongName(""num"").withArgument(numArg)
+ .create();
+ final Group options = gBuilder.withOption(numOpt).create();
+
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+
+ CommandLine cl = parser.parse(new String[] {
+ ""--num"", ""-42""
+ });
+ Number num = (Number) cl.getValue(numOpt);
+ assertEquals(""Wrong option value"", -42, num.intValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean looksLikeOption(final WriteableCommandLine commandLine,
+ final String trigger) {
+ return commandLine.looksLikeOption(trigger);
+ }
+
+// Test Case
+[/INST]
+ public void testNegativeNumber() throws OptionException
+ {
+ final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder();
+ final ArgumentBuilder aBuilder = new ArgumentBuilder();
+ final GroupBuilder gBuilder = new GroupBuilder();
+
+ final Argument numArg = aBuilder.withValidator(
+ NumberValidator.getNumberInstance()).withMinimum(1)
+ .withMaximum(1).create();
+ final Option numOpt = oBuilder.withLongName(""num"").withArgument(numArg)
+ .create();
+ final Group options = gBuilder.withOption(numOpt).create();
+
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+
+ CommandLine cl = parser.parse(new String[] {
+ ""--num"", ""-42""
+ });
+ Number num = (Number) cl.getValue(numOpt);
+ assertEquals(""Wrong option value"", -42, num.intValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testNegativeNumber() throws OptionException
+ {
+ final DefaultOptionBuilder oBuilder = new DefaultOptionBuilder();
+ final ArgumentBuilder aBuilder = new ArgumentBuilder();
+ final GroupBuilder gBuilder = new GroupBuilder();
+
+ final Argument numArg = aBuilder.withValidator(
+ NumberValidator.getNumberInstance()).withMinimum(1)
+ .withMaximum(1).create();
+ final Option numOpt = oBuilder.withLongName(""num"").withArgument(numArg)
+ .create();
+ final Group options = gBuilder.withOption(numOpt).create();
+
+ final Parser parser = new Parser();
+ parser.setGroup(options);
+
+ CommandLine cl = parser.parse(new String[] {
+ ""--num"", ""-42""
+ });
+ Number num = (Number) cl.getValue(numOpt);
+ assertEquals(""Wrong option value"", -42, num.intValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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))
+ {
+ processNonOptionToken(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 || options.hasOption(token))
+ {
+ processOptionToken(token, stopAtNonOption);
+ }
+ // requires bursting
+ else
+ {
+ burstToken(token, stopAtNonOption);
+ }
+ }
+ else if (stopAtNonOption)
+ {
+ processNonOptionToken(token);
+ }
+ else
+ {
+ tokens.add(token);
+ }
+
+ gobble(iter);
+ }
+
+ return (String[]) tokens.toArray(new String[tokens.size()]);
+ }
+
+// Test Case
+[/INST]
+ public void testGroovy() throws Exception {
+ Options options = new Options();
+
+ options.addOption(
+ OptionBuilder.withLongOpt(""define"").
+ withDescription(""define a system property"").
+ hasArg(true).
+ withArgName(""name=value"").
+ create('D'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""usage information"")
+ .withLongOpt(""help"")
+ .create('h'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""debug mode will print out full stack traces"")
+ .withLongOpt(""debug"")
+ .create('d'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""display the Groovy and JVM versions"")
+ .withLongOpt(""version"")
+ .create('v'));
+ options.addOption(
+ OptionBuilder.withArgName(""charset"")
+ .hasArg()
+ .withDescription(""specify the encoding of the files"")
+ .withLongOpt(""encoding"")
+ .create('c'));
+ options.addOption(
+ OptionBuilder.withArgName(""script"")
+ .hasArg()
+ .withDescription(""specify a command line script"")
+ .create('e'));
+ options.addOption(
+ OptionBuilder.withArgName(""extension"")
+ .hasOptionalArg()
+ .withDescription(""modify files in place; create backup if extension is given (e.g. \'.bak\')"")
+ .create('i'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line using implicit 'line' variable"")
+ .create('n'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line and print result (see also -n)"")
+ .create('p'));
+ options.addOption(
+ OptionBuilder.withArgName(""port"")
+ .hasOptionalArg()
+ .withDescription(""listen on a port and process inbound lines"")
+ .create('l'));
+ options.addOption(
+ OptionBuilder.withArgName(""splitPattern"")
+ .hasOptionalArg()
+ .withDescription(""split lines using splitPattern (default '\\s') using implicit 'split' variable"")
+ .withLongOpt(""autosplit"")
+ .create('a'));
+
+ Parser parser = new PosixParser();
+ CommandLine line = parser.parse(options, new String[] { ""-e"", ""println 'hello'"" }, true);
+
+ assertTrue(line.hasOption('e'));
+ assertEquals(""println 'hello'"", line.getOptionValue('e'));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processNonOptionToken(String value)
+ {
+ eatTheRest = true;
+ tokens.add(""--"");
+
+ tokens.add(value);
+ }
+
+// Test Case
+[/INST]
+ public void testGroovy() throws Exception {
+ Options options = new Options();
+
+ options.addOption(
+ OptionBuilder.withLongOpt(""define"").
+ withDescription(""define a system property"").
+ hasArg(true).
+ withArgName(""name=value"").
+ create('D'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""usage information"")
+ .withLongOpt(""help"")
+ .create('h'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""debug mode will print out full stack traces"")
+ .withLongOpt(""debug"")
+ .create('d'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""display the Groovy and JVM versions"")
+ .withLongOpt(""version"")
+ .create('v'));
+ options.addOption(
+ OptionBuilder.withArgName(""charset"")
+ .hasArg()
+ .withDescription(""specify the encoding of the files"")
+ .withLongOpt(""encoding"")
+ .create('c'));
+ options.addOption(
+ OptionBuilder.withArgName(""script"")
+ .hasArg()
+ .withDescription(""specify a command line script"")
+ .create('e'));
+ options.addOption(
+ OptionBuilder.withArgName(""extension"")
+ .hasOptionalArg()
+ .withDescription(""modify files in place; create backup if extension is given (e.g. \'.bak\')"")
+ .create('i'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line using implicit 'line' variable"")
+ .create('n'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line and print result (see also -n)"")
+ .create('p'));
+ options.addOption(
+ OptionBuilder.withArgName(""port"")
+ .hasOptionalArg()
+ .withDescription(""listen on a port and process inbound lines"")
+ .create('l'));
+ options.addOption(
+ OptionBuilder.withArgName(""splitPattern"")
+ .hasOptionalArg()
+ .withDescription(""split lines using splitPattern (default '\\s') using implicit 'split' variable"")
+ .withLongOpt(""autosplit"")
+ .create('a'));
+
+ Parser parser = new PosixParser();
+ CommandLine line = parser.parse(options, new String[] { ""-e"", ""println 'hello'"" }, true);
+
+ assertTrue(line.hasOption('e'));
+ assertEquals(""println 'hello'"", line.getOptionValue('e'));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processOptionToken(String token, boolean stopAtNonOption)
+ {
+ if (stopAtNonOption && !options.hasOption(token))
+ {
+ eatTheRest = true;
+ }
+
+
+ tokens.add(token);
+ }
+
+// Test Case
+[/INST]
+ public void testGroovy() throws Exception {
+ Options options = new Options();
+
+ options.addOption(
+ OptionBuilder.withLongOpt(""define"").
+ withDescription(""define a system property"").
+ hasArg(true).
+ withArgName(""name=value"").
+ create('D'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""usage information"")
+ .withLongOpt(""help"")
+ .create('h'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""debug mode will print out full stack traces"")
+ .withLongOpt(""debug"")
+ .create('d'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""display the Groovy and JVM versions"")
+ .withLongOpt(""version"")
+ .create('v'));
+ options.addOption(
+ OptionBuilder.withArgName(""charset"")
+ .hasArg()
+ .withDescription(""specify the encoding of the files"")
+ .withLongOpt(""encoding"")
+ .create('c'));
+ options.addOption(
+ OptionBuilder.withArgName(""script"")
+ .hasArg()
+ .withDescription(""specify a command line script"")
+ .create('e'));
+ options.addOption(
+ OptionBuilder.withArgName(""extension"")
+ .hasOptionalArg()
+ .withDescription(""modify files in place; create backup if extension is given (e.g. \'.bak\')"")
+ .create('i'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line using implicit 'line' variable"")
+ .create('n'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line and print result (see also -n)"")
+ .create('p'));
+ options.addOption(
+ OptionBuilder.withArgName(""port"")
+ .hasOptionalArg()
+ .withDescription(""listen on a port and process inbound lines"")
+ .create('l'));
+ options.addOption(
+ OptionBuilder.withArgName(""splitPattern"")
+ .hasOptionalArg()
+ .withDescription(""split lines using splitPattern (default '\\s') using implicit 'split' variable"")
+ .withLongOpt(""autosplit"")
+ .create('a'));
+
+ Parser parser = new PosixParser();
+ CommandLine line = parser.parse(options, new String[] { ""-e"", ""println 'hello'"" }, true);
+
+ assertTrue(line.hasOption('e'));
+ assertEquals(""println 'hello'"", line.getOptionValue('e'));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void burstToken(String token, boolean stopAtNonOption)
+ {
+ Option currentOption;
+ 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)
+ {
+ processNonOptionToken(token.substring(i));
+ break;
+ }
+ else
+ {
+ tokens.add(token);
+ break;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testGroovy() throws Exception {
+ Options options = new Options();
+
+ options.addOption(
+ OptionBuilder.withLongOpt(""define"").
+ withDescription(""define a system property"").
+ hasArg(true).
+ withArgName(""name=value"").
+ create('D'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""usage information"")
+ .withLongOpt(""help"")
+ .create('h'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""debug mode will print out full stack traces"")
+ .withLongOpt(""debug"")
+ .create('d'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""display the Groovy and JVM versions"")
+ .withLongOpt(""version"")
+ .create('v'));
+ options.addOption(
+ OptionBuilder.withArgName(""charset"")
+ .hasArg()
+ .withDescription(""specify the encoding of the files"")
+ .withLongOpt(""encoding"")
+ .create('c'));
+ options.addOption(
+ OptionBuilder.withArgName(""script"")
+ .hasArg()
+ .withDescription(""specify a command line script"")
+ .create('e'));
+ options.addOption(
+ OptionBuilder.withArgName(""extension"")
+ .hasOptionalArg()
+ .withDescription(""modify files in place; create backup if extension is given (e.g. \'.bak\')"")
+ .create('i'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line using implicit 'line' variable"")
+ .create('n'));
+ options.addOption(
+ OptionBuilder.hasArg(false)
+ .withDescription(""process files line by line and print result (see also -n)"")
+ .create('p'));
+ options.addOption(
+ OptionBuilder.withArgName(""port"")
+ .hasOptionalArg()
+ .withDescription(""listen on a port and process inbound lines"")
+ .create('l'));
+ options.addOption(
+ OptionBuilder.withArgName(""splitPattern"")
+ .hasOptionalArg()
+ .withDescription(""split lines using splitPattern (default '\\s') using implicit 'split' variable"")
+ .withLongOpt(""autosplit"")
+ .create('a'));
+
+ Parser parser = new PosixParser();
+ CommandLine line = parser.parse(options, new String[] { ""-e"", ""println 'hello'"" }, true);
+
+ assertTrue(line.hasOption('e'));
+ assertEquals(""println 'hello'"", line.getOptionValue('e'));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testInfiniteLoop() {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.setWidth(20);
+ formatter.printHelp(""app"", options); // used to hang & crash
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLongLineChunkingIndentIgnored() throws ParseException, IOException {
+ Options options = new Options();
+ options.addOption(""x"", ""extralongarg"", false, ""This description is Long."" );
+ HelpFormatter formatter = new HelpFormatter();
+ StringWriter sw = new StringWriter();
+ formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), ""Header"", options, 0, 5, ""Footer"");
+ String expected = ""usage:\n"" +
+ "" org.apache.comm\n"" +
+ "" ons.cli.bug.Bug\n"" +
+ "" CLI162Test\n"" +
+ ""Header\n"" +
+ ""-x,--extralongarg\n"" +
+ "" T\n"" +
+ "" h\n"" +
+ "" i\n"" +
+ "" s\n"" +
+ "" d\n"" +
+ "" e\n"" +
+ "" s\n"" +
+ "" c\n"" +
+ "" r\n"" +
+ "" i\n"" +
+ "" p\n"" +
+ "" t\n"" +
+ "" i\n"" +
+ "" o\n"" +
+ "" n\n"" +
+ "" i\n"" +
+ "" s\n"" +
+ "" L\n"" +
+ "" o\n"" +
+ "" n\n"" +
+ "" g\n"" +
+ "" .\n"" +
+ ""Footer\n"";
+ assertEquals( ""Long arguments did not split as expected"", expected, sw.toString() );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLongLineChunkingIndentIgnored() throws ParseException, IOException {
+ Options options = new Options();
+ options.addOption(""x"", ""extralongarg"", false, ""This description is Long."" );
+ HelpFormatter formatter = new HelpFormatter();
+ StringWriter sw = new StringWriter();
+ formatter.printHelp(new PrintWriter(sw), 22, this.getClass().getName(), ""Header"", options, 0, 5, ""Footer"");
+ System.err.println(sw.toString());
+ String expected = ""usage:\n"" +
+ "" org.apache.comm\n"" +
+ "" ons.cli.bug.Bug\n"" +
+ "" CLI162Test\n"" +
+ ""Header\n"" +
+ ""-x,--extralongarg\n"" +
+ "" This description is\n"" +
+ "" Long.\n"" +
+ ""Footer\n"";
+ assertEquals( ""Long arguments did not split as expected"", expected, sw.toString() );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testBuilderIsResettedAlways() {
+ try
+ {
+ OptionBuilder.withDescription(""JUnit"").create('""');
+ fail(""IllegalArgumentException expected"");
+ }
+ catch (IllegalArgumentException e)
+ {
+ // expected
+ }
+ assertNull(""we inherited a description"", OptionBuilder.create('x').getDescription());
+
+ try
+ {
+ OptionBuilder.withDescription(""JUnit"").create();
+ fail(""IllegalArgumentException expected"");
+ }
+ catch (IllegalArgumentException e)
+ {
+ // expected
+ }
+ assertNull(""we inherited a description"", OptionBuilder.create('x').getDescription());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOptionGroupLong() throws Exception
+ {
+ OptionGroup group = new OptionGroup();
+ group.addOption(OptionBuilder.withLongOpt(""foo"").create());
+ group.addOption(OptionBuilder.withLongOpt(""bar"").create());
+
+ Options options = new Options();
+ options.addOptionGroup(group);
+
+ CommandLine cl = parser.parse(options, new String[] { ""--bar"" });
+
+ assertTrue(cl.hasOption(""bar""));
+ assertEquals(""selected option"", ""bar"", group.getSelected());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPropertyOptionFlags() throws Exception
+ {
+ Properties properties = new Properties();
+ properties.setProperty( ""a"", ""true"" );
+ properties.setProperty( ""c"", ""yes"" );
+ properties.setProperty( ""e"", ""1"" );
+
+ Parser parser = new PosixParser();
+
+ CommandLine cmd = parser.parse(opts, null, properties);
+ assertTrue( cmd.hasOption(""a"") );
+ assertTrue( cmd.hasOption(""c"") );
+ assertTrue( cmd.hasOption(""e"") );
+
+
+ properties = new Properties();
+ properties.setProperty( ""a"", ""false"" );
+ properties.setProperty( ""c"", ""no"" );
+ properties.setProperty( ""e"", ""0"" );
+
+ cmd = parser.parse(opts, null, properties);
+ assertTrue( !cmd.hasOption(""a"") );
+ assertTrue( !cmd.hasOption(""c"") );
+ assertTrue( cmd.hasOption(""e"") ); // this option accepts as argument
+
+
+ properties = new Properties();
+ properties.setProperty( ""a"", ""TRUE"" );
+ properties.setProperty( ""c"", ""nO"" );
+ properties.setProperty( ""e"", ""TrUe"" );
+
+ cmd = parser.parse(opts, null, properties);
+ assertTrue( cmd.hasOption(""a"") );
+ assertTrue( !cmd.hasOption(""c"") );
+ assertTrue( cmd.hasOption(""e"") );
+
+
+ properties = new Properties();
+ properties.setProperty( ""a"", ""just a string"" );
+ properties.setProperty( ""e"", """" );
+
+ cmd = parser.parse(opts, null, properties);
+ assertTrue( !cmd.hasOption(""a"") );
+ assertTrue( !cmd.hasOption(""c"") );
+ assertTrue( cmd.hasOption(""e"") );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testStripLeadingAndTrailingQuotes()
+ {
+ assertEquals(""foo"", Util.stripLeadingAndTrailingQuotes(""\""foo\""""));
+ assertEquals(""foo \""bar\"""", Util.stripLeadingAndTrailingQuotes(""foo \""bar\""""));
+ assertEquals(""\""foo\"" bar"", Util.stripLeadingAndTrailingQuotes(""\""foo\"" bar""));
+ assertEquals(""\""foo\"" and \""bar\"""", Util.stripLeadingAndTrailingQuotes(""\""foo\"" and \""bar\""""));
+ assertEquals(""\"""", Util.stripLeadingAndTrailingQuotes(""\""""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Number createNumber(String str)
+ {
+ try
+ {
+ return NumberUtils.createNumber(str);
+ }
+ catch (NumberFormatException nfe)
+ {
+ System.err.println(nfe.getMessage());
+ }
+
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testSimplePattern()
+ {
+ try {
+ Options options = PatternOptionBuilder.parsePattern(""a:b@cde>f+n%t/"");
+ String[] args = new String[] { ""-c"", ""-a"", ""foo"", ""-b"", ""java.util.Vector"", ""-e"", ""build.xml"", ""-f"", ""java.util.Calendar"", ""-n"", ""4.5"", ""-t"", ""http://jakarta.apache.org/"" };
+
+ CommandLineParser parser = new PosixParser();
+ CommandLine line = parser.parse(options,args);
+
+ // tests the char methods of CommandLine that delegate to
+ // the String methods
+ assertEquals(""flag a"", ""foo"", line.getOptionValue(""a""));
+ assertEquals(""flag a"", ""foo"", line.getOptionValue('a'));
+ assertEquals(""string flag a"", ""foo"", line.getOptionObject(""a""));
+ assertEquals(""string flag a"", ""foo"", line.getOptionObject('a'));
+ assertEquals(""object flag b"", new java.util.Vector(), line.getOptionObject(""b""));
+ assertEquals(""object flag b"", new java.util.Vector(), line.getOptionObject('b'));
+ assertEquals(""boolean true flag c"", true, line.hasOption(""c""));
+ assertEquals(""boolean true flag c"", true, line.hasOption('c'));
+ assertEquals(""boolean false flag d"", false, line.hasOption(""d""));
+ assertEquals(""boolean false flag d"", false, line.hasOption('d'));
+ assertEquals(""file flag e"", new java.io.File(""build.xml""), line.getOptionObject(""e""));
+ assertEquals(""file flag e"", new java.io.File(""build.xml""), line.getOptionObject('e'));
+ assertEquals(""class flag f"", java.util.Calendar.class, line.getOptionObject(""f""));
+ assertEquals(""class flag f"", java.util.Calendar.class, line.getOptionObject('f'));
+ assertEquals(""number flag n"", new Double(4.5), line.getOptionObject(""n""));
+ assertEquals(""number flag n"", new Double(4.5), line.getOptionObject('n'));
+ assertEquals(""url flag t"", new java.net.URL(""http://jakarta.apache.org/""), line.getOptionObject(""t""));
+ assertEquals(""url flag t"", new java.net.URL(""http://jakarta.apache.org/""), line.getOptionObject('t'));
+ /// DATES NOT SUPPORTED YET.
+ // assertEquals(""number flag t"", new java.util.Date(1023400137276L), line.getOptionObject('z'));
+ // input is: ""Thu Jun 06 17:48:57 EDT 2002""
+ }
+ catch( ParseException exp ) {
+ fail( exp.getMessage() );
+ }
+ catch( java.net.MalformedURLException exp ) {
+ fail( exp.getMessage() );
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void handleProperties(Properties properties) throws ParseException
+ {
+ if (properties == null)
+ {
+ return;
+ }
+
+ for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
+ {
+ String option = e.nextElement().toString();
+
+ if (!cmd.hasOption(option))
+ {
+ Option opt = options.getOption(option);
+
+ // if the option is part of a group, check if another option of the group has been selected
+
+ // get the value from the properties
+ String value = properties.getProperty(option);
+
+ if (opt.hasArg())
+ {
+ if (opt.getValues() == null || opt.getValues().length == 0)
+ {
+ opt.addValueForProcessing(value);
+ }
+ }
+ 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;
+ }
+
+ handleOption(opt);
+ currentOption = null;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPropertyOptionGroup() throws Exception
+ {
+ Options opts = new Options();
+
+ OptionGroup group1 = new OptionGroup();
+ group1.addOption(new Option(""a"", null));
+ group1.addOption(new Option(""b"", null));
+ opts.addOptionGroup(group1);
+
+ OptionGroup group2 = new OptionGroup();
+ group2.addOption(new Option(""x"", null));
+ group2.addOption(new Option(""y"", null));
+ opts.addOptionGroup(group2);
+
+ String[] args = new String[] { ""-a"" };
+
+ Properties properties = new Properties();
+ properties.put(""b"", ""true"");
+ properties.put(""x"", ""true"");
+
+ CommandLine cmd = parse(parser, opts, args, properties);
+
+ assertTrue(cmd.hasOption(""a""));
+ assertFalse(cmd.hasOption(""b""));
+ assertTrue(cmd.hasOption(""x""));
+ assertFalse(cmd.hasOption(""y""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void processProperties(Properties properties) throws ParseException
+ {
+ 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);
+
+ // if the option is part of a group, check if another option of the group has been selected
+
+ // 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);
+ updateRequiredOptions(opt);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPropertyOptionGroup() throws Exception
+ {
+ Options opts = new Options();
+
+ OptionGroup group1 = new OptionGroup();
+ group1.addOption(new Option(""a"", null));
+ group1.addOption(new Option(""b"", null));
+ opts.addOptionGroup(group1);
+
+ OptionGroup group2 = new OptionGroup();
+ group2.addOption(new Option(""x"", null));
+ group2.addOption(new Option(""y"", null));
+ opts.addOptionGroup(group2);
+
+ String[] args = new String[] { ""-a"" };
+
+ Properties properties = new Properties();
+ properties.put(""b"", ""true"");
+ properties.put(""x"", ""true"");
+
+ CommandLine cmd = parse(parser, opts, args, properties);
+
+ assertTrue(cmd.hasOption(""a""));
+ assertFalse(cmd.hasOption(""b""));
+ assertTrue(cmd.hasOption(""x""));
+ assertFalse(cmd.hasOption(""y""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static void reset()
+ {
+ description = null;
+ argName = ""arg"";
+ longopt = null;
+ type = null;
+ required = false;
+ numberOfArgs = Option.UNINITIALIZED;
+ optionalArg = false;
+ valuesep = (char) 0;
+ }
+
+// Test Case
+[/INST]
+ public void testDefaultArgName()
+ {
+ Option option = OptionBuilder.hasArg().isRequired().create(""f"");
+
+ Options options = new Options();
+ options.addOption(option);
+
+ StringWriter out = new StringWriter();
+
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.setArgName(""argument"");
+ formatter.printUsage(new PrintWriter(out), 80, ""app"", options);
+
+ assertEquals(""usage: app -f "" + EOL, out.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private 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 and a non blank argname
+ if (option.hasArg() && option.hasArgName())
+ {
+ buff.append(option.getOpt() == null ? longOptSeparator : "" "");
+ buff.append(""<"").append(option.getArgName()).append("">"");
+ }
+
+ // if the Option is not a required option
+ if (!required)
+ {
+ buff.append(""]"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDefaultArgName()
+ {
+ Option option = OptionBuilder.hasArg().isRequired().create(""f"");
+
+ Options options = new Options();
+ options.addOption(option);
+
+ StringWriter out = new StringWriter();
+
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.setArgName(""argument"");
+ formatter.printUsage(new PrintWriter(out), 80, ""app"", options);
+
+ assertEquals(""usage: app -f "" + EOL, out.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testDefaultArgName()
+ {
+ Option option = OptionBuilder.hasArg().isRequired().create(""f"");
+
+ Options options = new Options();
+ options.addOption(option);
+
+ StringWriter out = new StringWriter();
+
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.setArgName(""argument"");
+ formatter.printUsage(new PrintWriter(out), 80, ""app"", options);
+
+ assertEquals(""usage: app -f "" + EOL, out.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testRenderWrappedTextWordCut()
+ {
+ int width = 7;
+ int padding = 0;
+ String text = ""Thisisatest."";
+ String expected = ""Thisisa"" + EOL +
+ ""test."";
+
+ StringBuffer sb = new StringBuffer();
+ new HelpFormatter().renderWrappedText(sb, width, padding, text);
+ assertEquals(""cut and wrap"", expected, sb.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text)
+ {
+ StringBuffer sb = new StringBuffer(text.length());
+
+ renderWrappedText(sb, width, nextLineTabStop, text);
+ pw.println(sb.toString());
+ }
+
+// Test Case
+[/INST]
+ public void testIndentedHeaderAndFooter()
+ {
+ // related to CLI-207
+ Options options = new Options();
+ HelpFormatter formatter = new HelpFormatter();
+ String header = "" Header1\n Header2"";
+ String footer = "" Footer1\n Footer2"";
+ StringWriter out = new StringWriter();
+ formatter.printHelp(new PrintWriter(out), 80, ""foobar"", header, options, 2, 2, footer, true);
+
+ assertEquals(
+ ""usage: foobar"" + EOL +
+ "" Header1"" + EOL +
+ "" Header2"" + EOL +
+ """" + EOL +
+ "" Footer1"" + EOL +
+ "" Footer2"" + EOL
+ , out.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static void reset()
+ {
+ description = null;
+ argName = null;
+ longopt = null;
+ type = null;
+ required = false;
+ numberOfArgs = Option.UNINITIALIZED;
+ optionalArg = false;
+ valuesep = (char) 0;
+ }
+
+// Test Case
+[/INST]
+ public void testGetParsedOptionValue() throws Exception {
+ Options options = new Options();
+ options.addOption(OptionBuilder.hasArg().withType(Number.class).create(""i""));
+ options.addOption(OptionBuilder.hasArg().create(""f""));
+
+ CommandLineParser parser = new DefaultParser();
+ CommandLine cmd = parser.parse(options, new String[] { ""-i"", ""123"", ""-f"", ""foo"" });
+
+ assertEquals(123, ((Number) cmd.getParsedOptionValue(""i"")).intValue());
+ assertEquals(""foo"", cmd.getParsedOptionValue(""f""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testGetParsedOptionValue() throws Exception {
+ Options options = new Options();
+ options.addOption(OptionBuilder.hasArg().withType(Number.class).create(""i""));
+ options.addOption(OptionBuilder.hasArg().create(""f""));
+
+ CommandLineParser parser = new DefaultParser();
+ CommandLine cmd = parser.parse(options, new String[] { ""-i"", ""123"", ""-f"", ""foo"" });
+
+ assertEquals(123, ((Number) cmd.getParsedOptionValue(""i"")).intValue());
+ assertEquals(""foo"", cmd.getParsedOptionValue(""f""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public List getMatchingOptions(String opt)
+ {
+ opt = Util.stripLeadingHyphens(opt);
+
+ List matchingOpts = new ArrayList();
+
+ // for a perfect match return the single option only
+
+ for (String longOpt : longOpts.keySet())
+ {
+ if (longOpt.startsWith(opt))
+ {
+ matchingOpts.add(longOpt);
+ }
+ }
+
+ return matchingOpts;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testExactOptionNameMatch() throws ParseException {
+ new DefaultParser().parse(getOptions(), new String[]{""--prefix""});
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testOptionComparatorInsertedOrder() throws ParseException {
+ Collection"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testOptionComparatorInsertedOrder() throws ParseException {
+ Collection"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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""
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void shouldParseShortOptionWithoutValue() throws Exception {
+ String[] twoShortOptions = new String[]{""-t1"", ""-last""};
+
+ final CommandLine commandLine = parser.parse(options, twoShortOptions);
+
+ assertTrue(commandLine.hasOption(""t1""));
+ assertNotEquals(""Second option has been used as value for first option"", ""-last"", commandLine.getOptionValue(""t1""));
+ assertTrue(""Second option has not been detected"", commandLine.hasOption(""last""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void shouldParseConcatenatedShortOptions() throws Exception {
+ String[] concatenatedShortOptions = new String[] { ""-t1"", ""-ab"" };
+
+ final CommandLine commandLine = parser.parse(options, concatenatedShortOptions);
+
+ assertTrue(commandLine.hasOption(""t1""));
+ assertNull(commandLine.getOptionValue(""t1""));
+ assertTrue(commandLine.hasOption(""a""));
+ assertTrue(commandLine.hasOption(""b""));
+ assertFalse(commandLine.hasOption(""last""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Object createValue(final String str, final Class> clazz) throws ParseException
+ {
+ if (PatternOptionBuilder.STRING_VALUE == clazz)
+ {
+ return str;
+ }
+ else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
+ {
+ return createObject(str);
+ }
+ else if (PatternOptionBuilder.NUMBER_VALUE == clazz)
+ {
+ return createNumber(str);
+ }
+ else if (PatternOptionBuilder.DATE_VALUE == clazz)
+ {
+ return createDate(str);
+ }
+ else if (PatternOptionBuilder.CLASS_VALUE == clazz)
+ {
+ return createClass(str);
+ }
+ else if (PatternOptionBuilder.FILE_VALUE == clazz)
+ {
+ return createFile(str);
+ }
+ else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)
+ {
+ return createFile(str);
+ }
+ else if (PatternOptionBuilder.FILES_VALUE == clazz)
+ {
+ return createFiles(str);
+ }
+ else if (PatternOptionBuilder.URL_VALUE == clazz)
+ {
+ return createURL(str);
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testExistingFilePattern() throws Exception
+ {
+ final Options options = PatternOptionBuilder.parsePattern(""g<"");
+ final CommandLineParser parser = new PosixParser();
+ final CommandLine line = parser.parse(options, new String[] { ""-g"", ""src/test/resources/existing-readable.file"" });
+
+ final Object parsedReadableFileStream = line.getOptionObject(""g"");
+
+ assertNotNull(""option g not parsed"", parsedReadableFileStream);
+ assertTrue(""option g not FileInputStream"", parsedReadableFileStream instanceof FileInputStream);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testMissingOptionsException() throws ParseException {
+ Options options = new Options();
+ options.addOption(OptionBuilder.isRequired().create(""f""));
+ options.addOption(OptionBuilder.isRequired().create(""x""));
+ try {
+ new PosixParser().parse(options, new String[0]);
+ fail(""Expected MissingOptionException to be thrown"");
+ } catch (MissingOptionException e) {
+ assertEquals(""Missing required options: fx"", e.getMessage());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static T createValue(final String str, final Class 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;
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = ParseException.class)
+ public void testCreateValueInteger_failure()
+ throws Exception
+ {
+ TypeHandler.createValue(""just-a-string"", Integer.class);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testStripLeadingHyphens() {
+ assertEquals(""f"", Util.stripLeadingHyphens(""-f""));
+ assertEquals(""foo"", Util.stripLeadingHyphens(""--foo""));
+ assertNull(Util.stripLeadingHyphens(null));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testRequiredOptions(){
+ PatternBuilder builder = new PatternBuilder();
+ builder.withPattern(""hc!<"");
+ Option option = builder.create();
+ assertTrue(option instanceof GroupImpl);
+
+ GroupImpl group = (GroupImpl)option;
+ Iterator i = group.getOptions().iterator();
+ assertEquals(""[-h]"",i.next().toString());
+ assertEquals(""-c "",i.next().toString());
+ assertFalse(i.hasNext());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPrintWrapped()
+ throws Exception
+ {
+ StringBuffer sb = new StringBuffer();
+ HelpFormatter hf = new HelpFormatter();
+
+ String text = ""This is a test."";
+ String expected;
+
+ expected = ""This is a"" + hf.getNewLine() + ""test."";
+ hf.renderWrappedText(sb, 12, 0, text);
+ assertEquals(""single line text"", expected, sb.toString());
+
+ sb.setLength(0);
+ expected = ""This is a"" + hf.getNewLine() + "" test."";
+ hf.renderWrappedText(sb, 12, 4, text);
+ assertEquals(""single line padded text"", expected, sb.toString());
+
+ text = "" -p,--period PERIOD is time duration of form "" +
+ ""DATE[-DATE] where DATE has form YYYY[MM[DD]]"";
+
+ sb.setLength(0);
+ expected = "" -p,--period PERIOD is time duration of"" +
+ hf.getNewLine() +
+ "" form DATE[-DATE] where DATE"" +
+ hf.getNewLine() +
+ "" has form YYYY[MM[DD]]"";
+ hf.renderWrappedText(sb, 53, 24, text);
+ assertEquals(""single line padded text 2"", expected, sb.toString());
+
+ text =
+ ""aaaa aaaa aaaa"" + hf.getNewLine() +
+ ""aaaaaa"" + hf.getNewLine() +
+ ""aaaaa"";
+
+ expected = text;
+ sb.setLength(0);
+ hf.renderWrappedText(sb, 16, 0, text);
+ assertEquals(""multi line text"", expected, sb.toString());
+
+ expected =
+ ""aaaa aaaa aaaa"" + hf.getNewLine() +
+ "" aaaaaa"" + hf.getNewLine() +
+ "" aaaaa"";
+ sb.setLength(0);
+ hf.renderWrappedText(sb, 16, 4, text);
+ assertEquals(""multi-line padded text"", expected, sb.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testMissingOptionsException() throws ParseException {
+ Options options = new Options();
+ options.addOption(OptionBuilder.isRequired().create(""f""));
+ options.addOption(OptionBuilder.isRequired().create(""x""));
+ try {
+ new PosixParser().parse(options, new String[0]);
+ fail(""Expected MissingOptionException to be thrown"");
+ } catch (MissingOptionException e) {
+ assertEquals(""Missing required options: f, x"", e.getMessage());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleModeLeavesUnusedParams() {
+ args.add(""--compilation_level=SIMPLE_OPTIMIZATIONS"");
+ testSame(""window.f = function(a) {};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean mayBeString(Node n, boolean recurse) {
+ if (recurse) {
+ return allResultsMatch(n, MAY_BE_STRING_PREDICATE);
+ } else {
+ return mayBeStringHelper(n);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue821() {
+ foldSame(""var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;"");
+ foldSame(""var a = ((Math.random() ? 0 : 1) ||"" +
+ ""(Math.random()>0.5? '1' : 2 )) + 3 + 4;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
+
+ if (n.getType() == Token.FUNCTION) {
+ // Don't traverse functions that are constructors or have the @this
+ // annotation.
+ JSDocInfo jsDoc = getFunctionJsDocInfo(n);
+ if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.hasThisType())) {
+ return false;
+ }
+
+ // Don't traverse functions unless they would normally
+ // be able to have a @this annotation associated with them. e.g.,
+ // var a = function() { }; // or
+ // function a() {} // or
+ // a.x = function() {};
+ }
+
+ if (parent != null && parent.getType() == Token.ASSIGN) {
+ Node lhs = parent.getFirstChild();
+ Node rhs = lhs.getNext();
+
+ if (n == lhs) {
+ // Always traverse the left side of the assignment. To handle
+ // nested assignments properly (e.g., (a = this).property = c;),
+ // assignLhsChild should not be overridden.
+ if (assignLhsChild == null) {
+ assignLhsChild = lhs;
+ }
+ } else {
+ // Only traverse the right side if it's not an assignment to a prototype
+ // property or subproperty.
+ if (lhs.getType() == Token.GETPROP) {
+ if (lhs.getLastChild().getString().equals(""prototype"")) {
+ return false;
+ }
+ String leftName = lhs.getQualifiedName();
+ if (leftName != null && leftName.contains("".prototype."")) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testStaticFunction6() {
+ testSame(""function a() { return function() { this = 8; } }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean shouldReportThis(Node n, Node parent) {
+ if (assignLhsChild != null) {
+ // Always report a THIS on the left side of an assign.
+ return true;
+ }
+
+ // Also report a THIS with a property access.
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testStaticFunction6() {
+ testSame(""function a() { return function() { this = 8; } }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testProcessClosurePrimitives() {
+ test(""var goog = {}; goog.provide('goog.dom');"",
+ ""var goog = {}; goog.dom = {};"");
+ args.add(""--process_closure_primitives=false"");
+ testSame(""var goog = {}; goog.provide('goog.dom');"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue115() {
+ CompilerRunner.FLAG_compilation_level.setForTest(
+ CompilationLevel.SIMPLE_OPTIMIZATIONS);
+ CompilerRunner.FLAG_warning_level.setForTest(
+ WarningLevel.VERBOSE);
+ test(""function f() { "" +
+ "" var arguments = Array.prototype.slice.call(arguments, 0);"" +
+ "" return arguments[0]; "" +
+ ""}"",
+ ""function f() { "" +
+ "" arguments = Array.prototype.slice.call(arguments, 0);"" +
+ "" return arguments[0]; "" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override public ObjectType getTypeWithProperty(String field, JSType type) {
+ if (!(type instanceof ObjectType)) {
+ if (type.autoboxesTo() != null) {
+ type = type.autoboxesTo();
+ } else {
+ return null;
+ }
+ }
+
+ // Ignore the prototype itself at all times.
+ if (""prototype"".equals(field)) {
+ return null;
+ }
+
+ // We look up the prototype chain to find the highest place (if any) that
+ // this appears. This will make references to overriden properties look
+ // like references to the initial property, so they are renamed alike.
+ ObjectType foundType = null;
+ ObjectType objType = ObjectType.cast(type);
+ while (objType != null && objType.getImplicitPrototype() != objType) {
+ if (objType.hasOwnProperty(field)) {
+ foundType = objType;
+ }
+ objType = objType.getImplicitPrototype();
+ }
+ // If the property does not exist on the referenced type but the original
+ // type is an object type, see if any subtype has the property.
+ // getGreatestSubtypeWithProperty does not guarantee that the property
+ // is defined on the returned type, it just indicates that it might be,
+ // so we have to double check.
+ return foundType;
+ }
+
+// Test Case
+[/INST]
+ public void testInstanceOfThrowsException() {
+ testSame(""function f() {try { if (value instanceof type) return true; } "" +
+ ""catch (e) { }}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static boolean mayThrowException(Node n) {
+ switch (n.getType()) {
+ case Token.CALL:
+ case Token.GETPROP:
+ case Token.GETELEM:
+ case Token.THROW:
+ case Token.NEW:
+ case Token.ASSIGN:
+ case Token.INC:
+ case Token.DEC:
+ return true;
+ case Token.FUNCTION:
+ return false;
+ }
+ for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
+ if (!ControlFlowGraph.isEnteringNewCfgNode(c) && mayThrowException(c)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testInstanceOfThrowsException() {
+ testSame(""function f() {try { if (value instanceof type) return true; } "" +
+ ""catch (e) { }}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testGreatestSubtypeUnionTypes5() throws Exception {
+ JSType errUnion = createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE);
+ assertEquals(NO_OBJECT_TYPE,
+ errUnion.getGreatestSubtype(STRING_OBJECT_TYPE));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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 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();
+ }
+
+// Test Case
+[/INST]
+ public void testStringJoinAdd() {
+ fold(""x = ['a', 'b', 'c'].join('')"", ""x = \""abc\"""");
+ fold(""x = [].join(',')"", ""x = \""\"""");
+ fold(""x = ['a'].join(',')"", ""x = \""a\"""");
+ fold(""x = ['a', 'b', 'c'].join(',')"", ""x = \""a,b,c\"""");
+ fold(""x = ['a', foo, 'b', 'c'].join(',')"", ""x = [\""a\"",foo,\""b,c\""].join(\"",\"")"");
+ fold(""x = [foo, 'a', 'b', 'c'].join(',')"", ""x = [foo,\""a,b,c\""].join(\"",\"")"");
+ fold(""x = ['a', 'b', 'c', foo].join(',')"", ""x = [\""a,b,c\"",foo].join(\"",\"")"");
+
+ // Works with numbers
+ fold(""x = ['a=', 5].join('')"", ""x = \""a=5\"""");
+ fold(""x = ['a', '5'].join(7)"", ""x = \""a75\"""");
+
+ // Works on boolean
+ fold(""x = ['a=', false].join('')"", ""x = \""a=false\"""");
+ fold(""x = ['a', '5'].join(true)"", ""x = \""atrue5\"""");
+ fold(""x = ['a', '5'].join(false)"", ""x = \""afalse5\"""");
+
+ // Only optimize if it's a size win.
+ fold(""x = ['a', '5', 'c'].join('a very very very long chain')"",
+ ""x = [\""a\"",\""5\"",\""c\""].join(\""a very very very long chain\"")"");
+
+ // TODO(user): Its possible to fold this better.
+ foldSame(""x = ['', foo].join(',')"");
+ foldSame(""x = ['', foo, ''].join(',')"");
+
+ fold(""x = ['', '', foo, ''].join(',')"", ""x = [',', foo, ''].join(',')"");
+ fold(""x = ['', '', foo, '', ''].join(',')"",
+ ""x = [',', foo, ','].join(',')"");
+
+ fold(""x = ['', '', foo, '', '', bar].join(',')"",
+ ""x = [',', foo, ',', bar].join(',')"");
+
+ fold(""x = [1,2,3].join('abcdef')"",
+ ""x = '1abcdef2abcdef3'"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean recordBlockDescription(String description) {
+ if (parseDocumentation) {
+ populated = true;
+ }
+ return currentInfo.documentBlock(description);
+ }
+
+// Test Case
+[/INST]
+ public void testJSDocComments() {
+ test(""function A() { /** This is a jsdoc comment */ this.foo; }"", ok);
+ test(""function A() { /* This is a normal comment */ this.foo; }"", e);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean canCollapseUnannotatedChildNames() {
+ if (type == Type.OTHER || globalSets != 1 || localSets != 0) {
+ return false;
+ }
+
+ // Don't try to collapse if the one global set is a twin reference.
+ // We could theoretically handle this case in CollapseProperties, but
+ // it's probably not worth the effort.
+
+ if (isClassOrEnum) {
+ return true;
+ }
+ return (type == Type.FUNCTION || aliasingGets == 0) &&
+ (parent == null || parent.canCollapseUnannotatedChildNames());
+ }
+
+// Test Case
+[/INST]
+ public void testJSDocComments() {
+ test(""function A() { /** This is a jsdoc comment */ this.foo; }"", ok);
+ test(""function A() { /* This is a normal comment */ this.foo; }"", e);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testGetMsgWiringNoWarnings() throws Exception {
+ args.add(""--compilation_level=ADVANCED_OPTIMIZATIONS"");
+ test(""/** @desc A bad foo. */ var MSG_FOO = 1;"", """");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void exitScope(NodeTraversal t) {
+ if (t.getScopeDepth() > 2) {
+ findNamespaceShadows(t);
+ }
+
+ if (t.getScopeDepth() == 2) {
+ renameNamespaceShadows(t);
+ aliases.clear();
+ forbiddenLocals.clear();
+ transformation = null;
+ hasNamespaceShadows = false;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1144() {
+ test(""var ns = {};"" +
+ ""ns.sub = {};"" +
+ ""/** @constructor */ ns.sub.C = function () {};"" +
+ ""goog.scope(function () {"" +
+ "" var sub = ns.sub;"" +
+ "" /** @type {sub.C} */"" +
+ "" var x = null;"" +
+ ""});"",
+ SCOPE_NAMESPACE +
+ ""var ns = {};"" +
+ ""ns.sub = {};"" +
+ ""/** @constructor */ ns.sub.C = function () {};"" +
+ ""$jscomp.scope.x = null;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void findAliases(NodeTraversal t) {
+ Scope scope = t.getScope();
+ for (Var v : scope.getVarIterable()) {
+ Node n = v.getNode();
+ Node parent = n.getParent();
+ boolean isVar = parent.isVar();
+ boolean isFunctionDecl = NodeUtil.isFunctionDeclaration(parent);
+ if (isVar && n.getFirstChild() != null && n.getFirstChild().isQualifiedName()) {
+ recordAlias(v);
+ } else if (v.isBleedingFunction()) {
+ // Bleeding functions already get a BAD_PARAMETERS error, so just
+ // do nothing.
+ } else if (parent.getType() == Token.LP) {
+ // Parameters of the scope function also get a BAD_PARAMETERS
+ // error.
+ } else if (isVar || isFunctionDecl) {
+ boolean isHoisted = NodeUtil.isHoistedFunctionDeclaration(parent);
+ Node grandparent = parent.getParent();
+ Node value = v.getInitialValue() != null ?
+ v.getInitialValue() :
+ null;
+ Node varNode = null;
+
+ String name = n.getString();
+ int nameCount = scopedAliasNames.count(name);
+ scopedAliasNames.add(name);
+ String globalName =
+ ""$jscomp.scope."" + name + (nameCount == 0 ? """" : (""$"" + nameCount));
+
+ compiler.ensureLibraryInjected(""base"");
+
+ // First, we need to free up the function expression (EXPR)
+ // to be used in another expression.
+ if (isFunctionDecl) {
+ // Replace ""function NAME() { ... }"" with ""var NAME;"".
+ Node existingName = v.getNameNode();
+
+ // We can't keep the local name on the function expression,
+ // because IE is buggy and will leak the name into the global
+ // scope. This is covered in more detail here:
+ // http://wiki.ecmascript.org/lib/exe/fetch.php?id=resources:resources&cache=cache&media=resources:jscriptdeviationsfromes3.pdf
+ //
+ // This will only cause problems if this is a hoisted, recursive
+ // function, and the programmer is using the hoisting.
+ Node newName = IR.name("""").useSourceInfoFrom(existingName);
+ value.replaceChild(existingName, newName);
+
+ varNode = IR.var(existingName).useSourceInfoFrom(existingName);
+ grandparent.replaceChild(parent, varNode);
+ } else {
+ if (value != null) {
+ // If this is a VAR, we can just detach the expression and
+ // the tree will still be valid.
+ value.detachFromParent();
+ }
+ varNode = parent;
+ }
+
+ // Add $jscomp.scope.name = EXPR;
+ // Make sure we copy over all the jsdoc and debug info.
+ if (value != null || v.getJSDocInfo() != null) {
+ Node newDecl = NodeUtil.newQualifiedNameNodeDeclaration(
+ compiler.getCodingConvention(),
+ globalName,
+ value,
+ v.getJSDocInfo())
+ .useSourceInfoIfMissingFromForTree(n);
+ NodeUtil.setDebugInformation(
+ newDecl.getFirstChild().getFirstChild(), n, name);
+
+ if (isHoisted) {
+ grandparent.addChildToFront(newDecl);
+ } else {
+ grandparent.addChildBefore(newDecl, varNode);
+ }
+ }
+
+ // Rewrite ""var name = EXPR;"" to ""var name = $jscomp.scope.name;""
+ v.getNameNode().addChildToFront(
+ NodeUtil.newQualifiedNameNode(
+ compiler.getCodingConvention(), globalName, n, name));
+
+ recordAlias(v);
+ } else {
+ // Do not other kinds of local symbols, like catch params.
+ report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1144() {
+ test(""var ns = {};"" +
+ ""ns.sub = {};"" +
+ ""/** @constructor */ ns.sub.C = function () {};"" +
+ ""goog.scope(function () {"" +
+ "" var sub = ns.sub;"" +
+ "" /** @type {sub.C} */"" +
+ "" var x = null;"" +
+ ""});"",
+ SCOPE_NAMESPACE +
+ ""var ns = {};"" +
+ ""ns.sub = {};"" +
+ ""/** @constructor */ ns.sub.C = function () {};"" +
+ ""$jscomp.scope.x = null;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (isCallToScopeMethod(n)) {
+ validateScopeCall(t, n, n.getParent());
+ }
+
+ if (t.getScopeDepth() < 2) {
+ return;
+ }
+
+ int type = n.getType();
+ Var aliasVar = null;
+ if (type == Token.NAME) {
+ String name = n.getString();
+ Var lexicalVar = t.getScope().getVar(n.getString());
+ if (lexicalVar != null && lexicalVar == aliases.get(name)) {
+ aliasVar = lexicalVar;
+ }
+ }
+
+ // Validate the top-level of the goog.scope block.
+ if (t.getScopeDepth() == 2) {
+ if (aliasVar != null && NodeUtil.isLValue(n)) {
+ if (aliasVar.getNode() == n) {
+ aliasDefinitionsInOrder.add(n);
+
+ // Return early, to ensure that we don't record a definition
+ // twice.
+ return;
+ } else {
+ report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString());
+ }
+ }
+
+ if (type == Token.RETURN) {
+ report(t, n, GOOG_SCOPE_USES_RETURN);
+ } else if (type == Token.THIS) {
+ report(t, n, GOOG_SCOPE_REFERENCES_THIS);
+ } else if (type == Token.THROW) {
+ report(t, n, GOOG_SCOPE_USES_THROW);
+ }
+ }
+
+ // Validate all descendent scopes of the goog.scope block.
+ if (t.getScopeDepth() >= 2) {
+ // Check if this name points to an alias.
+ if (aliasVar != null) {
+ // Note, to support the transitive case, it's important we don't
+ // clone aliasedNode here. For example,
+ // var g = goog; var d = g.dom; d.createElement('DIV');
+ // The node in aliasedNode (which is ""g"") will be replaced in the
+ // changes pass above with ""goog"". If we cloned here, we'd end up
+ // with g.dom.createElement('DIV').
+ aliasUsages.add(new AliasedNode(aliasVar, n));
+ }
+
+ // When we inject declarations, we duplicate jsdoc. Make sure
+ // we only process that jsdoc once.
+ JSDocInfo info = n.getJSDocInfo();
+ if (info != null) {
+ for (Node node : info.getTypeNodes()) {
+ fixTypeNode(node);
+ }
+ }
+
+ // TODO(robbyw): Error for goog.scope not at root.
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1144() {
+ test(""var ns = {};"" +
+ ""ns.sub = {};"" +
+ ""/** @constructor */ ns.sub.C = function () {};"" +
+ ""goog.scope(function () {"" +
+ "" var sub = ns.sub;"" +
+ "" /** @type {sub.C} */"" +
+ "" var x = null;"" +
+ ""});"",
+ SCOPE_NAMESPACE +
+ ""var ns = {};"" +
+ ""ns.sub = {};"" +
+ ""/** @constructor */ ns.sub.C = function () {};"" +
+ ""$jscomp.scope.x = null;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node parseContextTypeExpression(JsDocToken token) {
+ return parseTypeName(token);
+ }
+
+// Test Case
+[/INST]
+ public void testStructuralConstructor2() throws Exception {
+ JSType type = testParseType(
+ ""function (new:?)"",
+ // toString skips unknowns, but isConstructor reveals the truth.
+ ""function (): ?"");
+ assertTrue(type.isConstructor());
+ assertFalse(type.isNominalConstructor());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+
+// Test Case
+[/INST]
+ public void testGetprop4() throws Exception {
+ testTypes(""var x = null; x.prop = 3;"",
+ ""No properties on this expression\n"" +
+ ""found : null\n"" +
+ ""required: Object"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void findAliases(NodeTraversal t) {
+ Scope scope = t.getScope();
+ for (Var v : scope.getVarIterable()) {
+ Node n = v.getNode();
+ Node parent = n.getParent();
+ boolean isVar = parent.isVar();
+ if (isVar && n.getFirstChild() != null && n.getFirstChild().isQualifiedName()) {
+ recordAlias(v);
+ } else if (v.isBleedingFunction()) {
+ // Bleeding functions already get a BAD_PARAMETERS error, so just
+ // do nothing.
+ } else if (parent.getType() == Token.LP) {
+ // Parameters of the scope function also get a BAD_PARAMETERS
+ // error.
+ } else if (isVar) {
+ Node grandparent = parent.getParent();
+ Node value = n.hasChildren() ?
+ v.getInitialValue().detachFromParent() :
+ null;
+ Node varNode = parent;
+
+ String name = n.getString();
+ int nameCount = scopedAliasNames.count(name);
+ scopedAliasNames.add(name);
+ String globalName =
+ ""$jscomp.scope."" + name + (nameCount == 0 ? """" : (""$"" + nameCount));
+
+ compiler.ensureLibraryInjected(""base"");
+
+ // First, we need to free up the function expression (EXPR)
+ // to be used in another expression.
+ // Replace ""function NAME() { ... }"" with ""var NAME;"".
+
+ // We can't keep the local name on the function expression,
+ // because IE is buggy and will leak the name into the global
+ // scope. This is covered in more detail here:
+ // http://wiki.ecmascript.org/lib/exe/fetch.php?id=resources:resources&cache=cache&media=resources:jscriptdeviationsfromes3.pdf
+ //
+ // This will only cause problems if this is a hoisted, recursive
+ // function, and the programmer is using the hoisting.
+
+ // If this is a VAR, we can just detach the expression and
+ // the tree will still be valid.
+
+ // Add $jscomp.scope.name = EXPR;
+ // Make sure we copy over all the jsdoc and debug info.
+ if (value != null || v.getJSDocInfo() != null) {
+ Node newDecl = NodeUtil.newQualifiedNameNodeDeclaration(
+ compiler.getCodingConvention(),
+ globalName,
+ value,
+ v.getJSDocInfo())
+ .useSourceInfoIfMissingFromForTree(n);
+ NodeUtil.setDebugInformation(
+ newDecl.getFirstChild().getFirstChild(), n, name);
+
+ grandparent.addChildBefore(newDecl, varNode);
+ }
+
+ // Rewrite ""var name = EXPR;"" to ""var name = $jscomp.scope.name;""
+ v.getNameNode().addChildToFront(
+ NodeUtil.newQualifiedNameNode(
+ compiler.getCodingConvention(), globalName, n, name));
+
+ recordAlias(v);
+ } else {
+ // Do not other kinds of local symbols, like catch params.
+ report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testHoistedFunctionDeclaration() {
+ testScoped("" g(f); function f() {} "",
+ SCOPE_NAMESPACE +
+ "" $jscomp.scope.f = function () {}; "" +
+ ""g($jscomp.scope.f); "");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Node getChildBefore(Node child) {
+ if (child == first) {
+ return null;
+ }
+ Node n = first;
+
+ while (n.next != child) {
+ n = n.next;
+ if (n == null) {
+ throw new RuntimeException(""node is not a child"");
+ }
+ }
+ return n;
+ }
+
+// Test Case
+[/INST]
+ public void testHoistedFunctionDeclaration() {
+ testScoped("" g(f); function f() {} "",
+ SCOPE_NAMESPACE +
+ "" $jscomp.scope.f = function () {}; "" +
+ ""g($jscomp.scope.f); "");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JSType caseTopType(JSType topType) {
+ return topType;
+ }
+
+// Test Case
+[/INST]
+ public void testGoogIsArray2() throws Exception {
+ testClosureFunction(""goog.isArray"",
+ ALL_TYPE,
+ ARRAY_TYPE,
+ ALL_TYPE);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean inferTemplatedTypesForCall(
+ Node n, FunctionType fnType) {
+ final ImmutableList keys = fnType.getTemplateTypeMap()
+ .getTemplateKeys();
+ if (keys.isEmpty()) {
+ return false;
+ }
+
+ // Try to infer the template types
+ Map 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;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1058() throws Exception {
+ testTypes(
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" * @template CLASS\n"" +
+ "" */\n"" +
+ ""var Class = function() {};\n"" +
+ ""\n"" +
+ ""/**\n"" +
+ "" * @param {function(CLASS):CLASS} a\n"" +
+ "" * @template T\n"" +
+ "" */\n"" +
+ ""Class.prototype.foo = function(a) {\n"" +
+ "" return 'string';\n"" +
+ ""};\n"" +
+ ""\n"" +
+ ""/** @param {number} a\n"" +
+ "" * @return {string} */\n"" +
+ ""var a = function(a) { return '' };\n"" +
+ ""\n"" +
+ ""new Class().foo(a);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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();
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNoUndeclaredVarWhenUsingClosurePass() {
+ enableClosurePass();
+ // We don't want to get goog as an undeclared var here.
+ test(""goog.require('namespace.Class1');\n"", null,
+ ProcessClosurePrimitives.MISSING_PROVIDE_ERROR);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testAssignWithCall() {
+ test(""var fun, x; (fun = function(){ x; })();"",
+ ""var x; (function(){ x; })();"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testBug4944818() {
+ test(
+ ""var getDomServices_ = function(self) {\n"" +
+ "" if (!self.domServices_) {\n"" +
+ "" self.domServices_ = goog$component$DomServices.get("" +
+ "" self.appContext_);\n"" +
+ "" }\n"" +
+ ""\n"" +
+ "" return self.domServices_;\n"" +
+ ""};\n"" +
+ ""\n"" +
+ ""var getOwnerWin_ = function(self) {\n"" +
+ "" return getDomServices_(self).getDomHelper().getWindow();\n"" +
+ ""};\n"" +
+ ""\n"" +
+ ""HangoutStarter.prototype.launchHangout = function() {\n"" +
+ "" var self = a.b;\n"" +
+ "" var myUrl = new goog.Uri(getOwnerWin_(self).location.href);\n"" +
+ ""};"",
+ ""HangoutStarter.prototype.launchHangout = function() { "" +
+ "" var self$$2 = a.b;"" +
+ "" var JSCompiler_temp_const$$0 = goog.Uri;"" +
+ "" var JSCompiler_inline_result$$1;"" +
+ "" {"" +
+ "" var self$$inline_2 = self$$2;"" +
+ "" if (!self$$inline_2.domServices_) {"" +
+ "" self$$inline_2.domServices_ = goog$component$DomServices.get("" +
+ "" self$$inline_2.appContext_);"" +
+ "" }"" +
+ "" JSCompiler_inline_result$$1=self$$inline_2.domServices_;"" +
+ "" }"" +
+ "" var myUrl = new JSCompiler_temp_const$$0("" +
+ "" JSCompiler_inline_result$$1.getDomHelper()."" +
+ "" getWindow().location.href)"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1101a() {
+ helperCanInlineReferenceToFunction(CanInlineResult.NO,
+ ""function foo(a){return modifiyX() + a;} foo(x);"", ""foo"",
+ INLINE_DIRECT);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1047() throws Exception {
+ testTypes(
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""function C2() {}\n"" +
+ ""\n"" +
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""function C3(c2) {\n"" +
+ "" /**\n"" +
+ "" * @type {C2} \n"" +
+ "" * @private\n"" +
+ "" */\n"" +
+ "" this.c2_;\n"" +
+ ""\n"" +
+ "" var x = this.c2_.prop;\n"" +
+ ""}"",
+ ""Property prop never defined on C2"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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(), """"));
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOneType4() {
+ String js = """"
+ + ""/** @constructor */ function Foo() {}\n""
+ + ""Foo.prototype = {'a': 0};\n""
+ + ""/** @type Foo */\n""
+ + ""var F = new Foo;\n""
+ + ""F['a'] = 0;"";
+ String expected = ""{}"";
+ testSets(false, js, js, expected);
+ testSets(true, js, js, expected);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testGlobalCatch() throws Exception {
+ testSame(
+ ""try {"" +
+ "" throw Error();"" +
+ ""} catch (e) {"" +
+ "" console.log(e.name)"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean hasExceptionHandler(Node cfgNode) {
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue794b() {
+ noInline(
+ ""var x = 1; "" +
+ ""try { x = x + someFunction(); } catch (e) {}"" +
+ ""x = x + 1;"" +
+ ""try { x = x + someFunction(); } catch (e) {}"" +
+ ""return x;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testExternalIssue1053() {
+ testSame(
+ ""var u; function f() { u = Random(); var x = u; f(); alert(x===u)}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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 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);
+ }
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testExternalIssue1053() {
+ testSame(
+ ""var u; function f() { u = Random(); var x = u; f(); alert(x===u)}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void handleBlockComment(Comment comment) {
+ if (comment.getValue().indexOf(""/* @"") != -1 || comment.getValue().indexOf(""\n * @"") != -1) {
+ errorReporter.warning(
+ SUSPICIOUS_COMMENT_WARNING,
+ sourceName,
+ comment.getLineno(), """", 0);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSuspiciousBlockCommentWarning3() {
+ parse(""/* \n *@type {number} */ var x = 3;"", SUSPICIOUS_COMMENT_WARNING);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void add(Node n, Context context) {
+ if (!cc.continueProcessing()) {
+ return;
+ }
+
+ int type = n.getType();
+ String opstr = NodeUtil.opToStr(type);
+ int childCount = n.getChildCount();
+ Node first = n.getFirstChild();
+ Node last = n.getLastChild();
+
+ // Handle all binary operators
+ if (opstr != null && first != last) {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad binary operator \""%s\"": expected 2 arguments but got %s"",
+ opstr, childCount);
+ int p = NodeUtil.precedence(type);
+
+ // For right-hand-side of operations, only pass context if it's
+ // the IN_FOR_INIT_CLAUSE one.
+ Context rhsContext = getContextForNoInOperator(context);
+
+ // Handle associativity.
+ // e.g. if the parse tree is a * (b * c),
+ // we can simply generate a * b * c.
+ if (last.getType() == type &&
+ NodeUtil.isAssociative(type)) {
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p, rhsContext);
+ } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {
+ // Assignments are the only right-associative binary operators
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p, rhsContext);
+ } else {
+ unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1);
+ }
+ return;
+ }
+
+ cc.startSourceMapping(n);
+
+ switch (type) {
+ case Token.TRY: {
+ Preconditions.checkState(first.getNext().isBlock() &&
+ !first.getNext().hasMoreThanOneChild());
+ Preconditions.checkState(childCount >= 2 && childCount <= 3);
+
+ add(""try"");
+ add(first, Context.PRESERVE_BLOCK);
+
+ // second child contains the catch block, or nothing if there
+ // isn't a catch block
+ Node catchblock = first.getNext().getFirstChild();
+ if (catchblock != null) {
+ add(catchblock);
+ }
+
+ if (childCount == 3) {
+ add(""finally"");
+ add(last, Context.PRESERVE_BLOCK);
+ }
+ break;
+ }
+
+ case Token.CATCH:
+ Preconditions.checkState(childCount == 2);
+ add(""catch("");
+ add(first);
+ add("")"");
+ add(last, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.THROW:
+ Preconditions.checkState(childCount == 1);
+ add(""throw"");
+ add(first);
+
+ // Must have a ';' after a throw statement, otherwise safari can't
+ // parse this.
+ cc.endStatement(true);
+ break;
+
+ case Token.RETURN:
+ add(""return"");
+ if (childCount == 1) {
+ add(first);
+ } else {
+ Preconditions.checkState(childCount == 0);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.VAR:
+ if (first != null) {
+ add(""var "");
+ addList(first, false, getContextForNoInOperator(context));
+ }
+ break;
+
+ case Token.LABEL_NAME:
+ Preconditions.checkState(!n.getString().isEmpty());
+ addIdentifier(n.getString());
+ break;
+
+ case Token.NAME:
+ if (first == null || first.isEmpty()) {
+ addIdentifier(n.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ addIdentifier(n.getString());
+ cc.addOp(""="", true);
+ if (first.isComma()) {
+ addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);
+ } else {
+ // Add expression, consider nearby code at lowest level of
+ // precedence.
+ addExpr(first, 0, getContextForNoInOperator(context));
+ }
+ }
+ break;
+
+ case Token.ARRAYLIT:
+ add(""["");
+ addArrayList(first);
+ add(""]"");
+ break;
+
+ case Token.PARAM_LIST:
+ add(""("");
+ addList(first);
+ add("")"");
+ break;
+
+ case Token.COMMA:
+ Preconditions.checkState(childCount == 2);
+ unrollBinaryOperator(n, Token.COMMA, "","", context,
+ getContextForNoInOperator(context), 0, 0);
+ break;
+
+ case Token.NUMBER:
+ Preconditions.checkState(childCount == 0);
+ cc.addNumber(n.getDouble());
+ break;
+
+ case Token.TYPEOF:
+ case Token.VOID:
+ case Token.NOT:
+ case Token.BITNOT:
+ case Token.POS: {
+ // All of these unary operators are right-associative
+ Preconditions.checkState(childCount == 1);
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type), Context.OTHER);
+ break;
+ }
+
+ case Token.NEG: {
+ Preconditions.checkState(childCount == 1);
+
+ // It's important to our sanity checker that the code
+ // we print produces the same AST as the code we parse back.
+ // NEG is a weird case because Rhino parses ""- -2"" as ""2"".
+ if (n.getFirstChild().isNumber()) {
+ cc.addNumber(-n.getFirstChild().getDouble());
+ } else {
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type), Context.OTHER);
+ }
+
+ break;
+ }
+
+ case Token.HOOK: {
+ Preconditions.checkState(childCount == 3);
+ int p = NodeUtil.precedence(type);
+ Context rhsContext = Context.OTHER;
+ addExpr(first, p + 1, context);
+ cc.addOp(""?"", true);
+ addExpr(first.getNext(), 1, rhsContext);
+ cc.addOp("":"", true);
+ addExpr(last, 1, rhsContext);
+ break;
+ }
+
+ case Token.REGEXP:
+ if (!first.isString() ||
+ !last.isString()) {
+ throw new Error(""Expected children to be strings"");
+ }
+
+ String regexp = regexpEscape(first.getString(), outputCharsetEncoder);
+
+ // I only use one .add because whitespace matters
+ if (childCount == 2) {
+ add(regexp + last.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ add(regexp);
+ }
+ break;
+
+ case Token.FUNCTION:
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ Preconditions.checkState(childCount == 3);
+ boolean funcNeedsParens = (context == Context.START_OF_EXPR);
+ if (funcNeedsParens) {
+ add(""("");
+ }
+
+ add(""function"");
+ add(first);
+
+ add(first.getNext());
+ add(last, Context.PRESERVE_BLOCK);
+ cc.endFunction(context == Context.STATEMENT);
+
+ if (funcNeedsParens) {
+ add("")"");
+ }
+ break;
+
+ case Token.GETTER_DEF:
+ case Token.SETTER_DEF:
+ Preconditions.checkState(n.getParent().isObjectLit());
+ Preconditions.checkState(childCount == 1);
+ Preconditions.checkState(first.isFunction());
+
+ // Get methods are unnamed
+ Preconditions.checkState(first.getFirstChild().getString().isEmpty());
+ if (type == Token.GETTER_DEF) {
+ // Get methods have no parameters.
+ Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());
+ add(""get "");
+ } else {
+ // Set methods have one parameter.
+ Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());
+ add(""set "");
+ }
+
+ // The name is on the GET or SET node.
+ String name = n.getString();
+ Node fn = first;
+ Node parameters = fn.getChildAtIndex(1);
+ Node body = fn.getLastChild();
+
+ // Add the property name.
+ if (!n.isQuotedString() &&
+ TokenStream.isJSIdentifier(name) &&
+ // do not encode literally any non-literal characters that were
+ // Unicode escaped.
+ NodeUtil.isLatin(name)) {
+ add(name);
+ } else {
+ // Determine if the string is a simple number.
+ double d = getSimpleNumber(name);
+ if (!Double.isNaN(d)) {
+ cc.addNumber(d);
+ } else {
+ addJsString(n);
+ }
+ }
+
+ add(parameters);
+ add(body, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.SCRIPT:
+ case Token.BLOCK: {
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ boolean preserveBlock = context == Context.PRESERVE_BLOCK;
+ if (preserveBlock) {
+ cc.beginBlock();
+ }
+
+ boolean preferLineBreaks =
+ type == Token.SCRIPT ||
+ (type == Token.BLOCK &&
+ !preserveBlock &&
+ n.getParent() != null &&
+ n.getParent().isScript());
+ for (Node c = first; c != null; c = c.getNext()) {
+ add(c, Context.STATEMENT);
+
+ // VAR doesn't include ';' since it gets used in expressions
+ if (c.isVar()) {
+ cc.endStatement();
+ }
+
+ if (c.isFunction()) {
+ cc.maybeLineBreak();
+ }
+
+ // Prefer to break lines in between top-level statements
+ // because top-level statements are more homogeneous.
+ if (preferLineBreaks) {
+ cc.notePreferredLineBreak();
+ }
+ }
+ if (preserveBlock) {
+ cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
+ }
+ break;
+ }
+
+ case Token.FOR:
+ if (childCount == 4) {
+ add(""for("");
+ if (first.isVar()) {
+ add(first, Context.IN_FOR_INIT_CLAUSE);
+ } else {
+ addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);
+ }
+ add("";"");
+ add(first.getNext());
+ add("";"");
+ add(first.getNext().getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ Preconditions.checkState(childCount == 3);
+ add(""for("");
+ add(first);
+ add(""in"");
+ add(first.getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ }
+ break;
+
+ case Token.DO:
+ Preconditions.checkState(childCount == 2);
+ add(""do"");
+ addNonEmptyStatement(first, Context.OTHER, false);
+ add(""while("");
+ add(last);
+ add("")"");
+ cc.endStatement();
+ break;
+
+ case Token.WHILE:
+ Preconditions.checkState(childCount == 2);
+ add(""while("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.EMPTY:
+ Preconditions.checkState(childCount == 0);
+ break;
+
+ case Token.GETPROP: {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETPROP: expected 2 children, but got %s"", childCount);
+ Preconditions.checkState(
+ last.isString(),
+ ""Bad GETPROP: RHS should be STRING"");
+ boolean needsParens = (first.isNumber());
+ if (needsParens) {
+ add(""("");
+ }
+ addExpr(first, NodeUtil.precedence(type), context);
+ if (needsParens) {
+ add("")"");
+ }
+ if (this.languageMode == LanguageMode.ECMASCRIPT3
+ && TokenStream.isKeyword(last.getString())) {
+ // Check for ECMASCRIPT3 keywords.
+ add(""["");
+ add(last);
+ add(""]"");
+ } else {
+ add(""."");
+ addIdentifier(last.getString());
+ }
+ break;
+ }
+
+ case Token.GETELEM:
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETELEM: expected 2 children but got %s"", childCount);
+ addExpr(first, NodeUtil.precedence(type), context);
+ add(""["");
+ add(first.getNext());
+ add(""]"");
+ break;
+
+ case Token.WITH:
+ Preconditions.checkState(childCount == 2);
+ add(""with("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.INC:
+ case Token.DEC: {
+ Preconditions.checkState(childCount == 1);
+ String o = type == Token.INC ? ""++"" : ""--"";
+ int postProp = n.getIntProp(Node.INCRDECR_PROP);
+ // A non-zero post-prop value indicates a post inc/dec, default of zero
+ // is a pre-inc/dec.
+ if (postProp != 0) {
+ addExpr(first, NodeUtil.precedence(type), context);
+ cc.addOp(o, false);
+ } else {
+ cc.addOp(o, false);
+ add(first);
+ }
+ break;
+ }
+
+ case Token.CALL:
+ // We have two special cases here:
+ // 1) If the left hand side of the call is a direct reference to eval,
+ // then it must have a DIRECT_EVAL annotation. If it does not, then
+ // that means it was originally an indirect call to eval, and that
+ // indirectness must be preserved.
+ // 2) If the left hand side of the call is a property reference,
+ // then the call must not a FREE_CALL annotation. If it does, then
+ // that means it was originally an call without an explicit this and
+ // that must be preserved.
+ if (isIndirectEval(first)
+ || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {
+ add(""(0,"");
+ addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);
+ add("")"");
+ } else {
+ addExpr(first, NodeUtil.precedence(type), context);
+ }
+ add(""("");
+ addList(first.getNext());
+ add("")"");
+ break;
+
+ case Token.IF:
+ boolean hasElse = childCount == 3;
+ boolean ambiguousElseClause =
+ context == Context.BEFORE_DANGLING_ELSE && !hasElse;
+ if (ambiguousElseClause) {
+ cc.beginBlock();
+ }
+
+ add(""if("");
+ add(first);
+ add("")"");
+
+ if (hasElse) {
+ addNonEmptyStatement(
+ first.getNext(), Context.BEFORE_DANGLING_ELSE, false);
+ add(""else"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ addNonEmptyStatement(first.getNext(), Context.OTHER, false);
+ Preconditions.checkState(childCount == 2);
+ }
+
+ if (ambiguousElseClause) {
+ cc.endBlock();
+ }
+ break;
+
+ case Token.NULL:
+ Preconditions.checkState(childCount == 0);
+ cc.addConstant(""null"");
+ break;
+
+ case Token.THIS:
+ Preconditions.checkState(childCount == 0);
+ add(""this"");
+ break;
+
+ case Token.FALSE:
+ Preconditions.checkState(childCount == 0);
+ cc.addConstant(""false"");
+ break;
+
+ case Token.TRUE:
+ Preconditions.checkState(childCount == 0);
+ cc.addConstant(""true"");
+ break;
+
+ case Token.CONTINUE:
+ Preconditions.checkState(childCount <= 1);
+ add(""continue"");
+ if (childCount == 1) {
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.DEBUGGER:
+ Preconditions.checkState(childCount == 0);
+ add(""debugger"");
+ cc.endStatement();
+ break;
+
+ case Token.BREAK:
+ Preconditions.checkState(childCount <= 1);
+ add(""break"");
+ if (childCount == 1) {
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.EXPR_RESULT:
+ Preconditions.checkState(childCount == 1);
+ add(first, Context.START_OF_EXPR);
+ cc.endStatement();
+ break;
+
+ case Token.NEW:
+ add(""new "");
+ int precedence = NodeUtil.precedence(type);
+
+ // If the first child contains a CALL, then claim higher precedence
+ // to force parentheses. Otherwise, when parsed, NEW will bind to the
+ // first viable parentheses (don't traverse into functions).
+ if (NodeUtil.containsType(
+ first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {
+ precedence = NodeUtil.precedence(first.getType()) + 1;
+ }
+ addExpr(first, precedence, Context.OTHER);
+
+ // '()' is optional when no arguments are present
+ Node next = first.getNext();
+ if (next != null) {
+ add(""("");
+ addList(next);
+ add("")"");
+ }
+ break;
+
+ case Token.STRING_KEY:
+ Preconditions.checkState(
+ childCount == 1, ""Object lit key must have 1 child"");
+ addJsString(n);
+ break;
+
+ case Token.STRING:
+ Preconditions.checkState(
+ childCount == 0, ""A string may not have children"");
+ addJsString(n);
+ break;
+
+ case Token.DELPROP:
+ Preconditions.checkState(childCount == 1);
+ add(""delete "");
+ add(first);
+ break;
+
+ case Token.OBJECTLIT: {
+ boolean needsParens = (context == Context.START_OF_EXPR);
+ if (needsParens) {
+ add(""("");
+ }
+ add(""{"");
+ for (Node c = first; c != null; c = c.getNext()) {
+ if (c != first) {
+ cc.listSeparator();
+ }
+
+ if (c.isGetterDef() || c.isSetterDef()) {
+ add(c);
+ } else {
+ Preconditions.checkState(c.isStringKey());
+ String key = c.getString();
+ // Object literal property names don't have to be quoted if they
+ // are not JavaScript keywords
+ if (!c.isQuotedString()
+ && !(languageMode == LanguageMode.ECMASCRIPT3
+ && TokenStream.isKeyword(key))
+ && TokenStream.isJSIdentifier(key)
+ // do not encode literally any non-literal characters that
+ // were Unicode escaped.
+ && NodeUtil.isLatin(key)) {
+ add(key);
+ } else {
+ // Determine if the string is a simple number.
+ double d = getSimpleNumber(key);
+ if (!Double.isNaN(d)) {
+ cc.addNumber(d);
+ } else {
+ addExpr(c, 1, Context.OTHER);
+ }
+ }
+ add("":"");
+ addExpr(c.getFirstChild(), 1, Context.OTHER);
+ }
+ }
+ add(""}"");
+ if (needsParens) {
+ add("")"");
+ }
+ break;
+ }
+
+ case Token.SWITCH:
+ add(""switch("");
+ add(first);
+ add("")"");
+ cc.beginBlock();
+ addAllSiblings(first.getNext());
+ cc.endBlock(context == Context.STATEMENT);
+ break;
+
+ case Token.CASE:
+ Preconditions.checkState(childCount == 2);
+ add(""case "");
+ add(first);
+ addCaseBody(last);
+ break;
+
+ case Token.DEFAULT_CASE:
+ Preconditions.checkState(childCount == 1);
+ add(""default"");
+ addCaseBody(first);
+ break;
+
+ case Token.LABEL:
+ Preconditions.checkState(childCount == 2);
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add(first);
+ add("":"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), true);
+ break;
+
+ case Token.CAST:
+ add(""("");
+ add(first);
+ add("")"");
+ break;
+
+ default:
+ throw new Error(""Unknown type "" + type + ""\n"" + n.toStringTree());
+ }
+
+ cc.endSourceMapping(n);
+ }
+
+// Test Case
+[/INST]
+ public void testPrintInOperatorInForLoop() {
+ // Check for in expression in for's init expression.
+ // Check alone, with + (higher precedence), with ?: (lower precedence),
+ // and with conditional.
+ assertPrint(""var a={}; for (var i = (\""length\"" in a); i;) {}"",
+ ""var a={};for(var i=(\""length\""in a);i;);"");
+ assertPrint(""var a={}; for (var i = (\""length\"" in a) ? 0 : 1; i;) {}"",
+ ""var a={};for(var i=(\""length\""in a)?0:1;i;);"");
+ assertPrint(""var a={}; for (var i = (\""length\"" in a) + 1; i;) {}"",
+ ""var a={};for(var i=(\""length\""in a)+1;i;);"");
+ assertPrint(""var a={};for (var i = (\""length\"" in a|| \""size\"" in a);;);"",
+ ""var a={};for(var i=(\""length\""in a)||(\""size\""in a);;);"");
+ assertPrint(""var a={};for (var i = a || a || (\""size\"" in a);;);"",
+ ""var a={};for(var i=a||a||(\""size\""in a);;);"");
+
+ // Test works with unary operators and calls.
+ assertPrint(""var a={}; for (var i = -(\""length\"" in a); i;) {}"",
+ ""var a={};for(var i=-(\""length\""in a);i;);"");
+ assertPrint(""var a={};function b_(p){ return p;};"" +
+ ""for(var i=1,j=b_(\""length\"" in a);;) {}"",
+ ""var a={};function b_(p){return p}"" +
+ ""for(var i=1,j=b_(\""length\""in a);;);"");
+
+ // Test we correctly handle an in operator in the test clause.
+ assertPrint(""var a={}; for (;(\""length\"" in a);) {}"",
+ ""var a={};for(;\""length\""in a;);"");
+
+ // Test we correctly handle an in operator inside a comma.
+ assertPrintSame(""for(x,(y in z);;)foo()"");
+ assertPrintSame(""for(var x,w=(y in z);;)foo()"");
+
+ // And in operator inside a hook.
+ assertPrintSame(""for(a=c?0:(0 in d);;)foo()"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isSafeReplacement(Node node, Node replacement) {
+ // No checks are needed for simple names.
+ if (node.isName()) {
+ return true;
+ }
+ Preconditions.checkArgument(node.isGetProp());
+
+ node = node.getFirstChild();
+ if (node.isName()
+ && isNameAssignedTo(node.getString(), replacement)) {
+ return false;
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1017() {
+ testSame(""x = x.parentNode.parentNode; x = x.parentNode.parentNode;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitNew(NodeTraversal t, Node n) {
+ Node constructor = n.getFirstChild();
+ JSType type = getJSType(constructor).restrictByNotNullOrUndefined();
+ if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {
+ FunctionType fnType = type.toMaybeFunctionType();
+ if (fnType != null) {
+ visitParameterList(t, n, fnType);
+ ensureTyped(t, n, fnType.getInstanceType());
+ } else {
+ ensureTyped(t, n);
+ }
+ } else {
+ report(t, n, NOT_A_CONSTRUCTOR);
+ ensureTyped(t, n);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1002() throws Exception {
+ testTypes(
+ ""/** @interface */"" +
+ ""var I = function() {};"" +
+ ""/** @constructor @implements {I} */"" +
+ ""var A = function() {};"" +
+ ""/** @constructor @implements {I} */"" +
+ ""var B = function() {};"" +
+ ""var f = function() {"" +
+ "" if (A === B) {"" +
+ "" new B();"" +
+ "" }"" +
+ ""};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void tryMinimizeExits(Node n, int exitType, String labelName) {
+
+ // Just an 'exit'.
+ if (matchingExitNode(n, exitType, labelName)) {
+ NodeUtil.removeChild(n.getParent(), n);
+ compiler.reportCodeChange();
+ return;
+ }
+
+ // Just an 'if'.
+ if (n.isIf()) {
+ Node ifBlock = n.getFirstChild().getNext();
+ tryMinimizeExits(ifBlock, exitType, labelName);
+ Node elseBlock = ifBlock.getNext();
+ if (elseBlock != null) {
+ tryMinimizeExits(elseBlock, exitType, labelName);
+ }
+ return;
+ }
+
+ // Just a 'try/catch/finally'.
+ if (n.isTry()) {
+ Node tryBlock = n.getFirstChild();
+ tryMinimizeExits(tryBlock, exitType, labelName);
+ Node allCatchNodes = NodeUtil.getCatchBlock(n);
+ if (NodeUtil.hasCatchHandler(allCatchNodes)) {
+ Preconditions.checkState(allCatchNodes.hasOneChild());
+ Node catchNode = allCatchNodes.getFirstChild();
+ Node catchCodeBlock = catchNode.getLastChild();
+ tryMinimizeExits(catchCodeBlock, exitType, labelName);
+ }
+ /* Don't try to minimize the exits of finally blocks, as this
+ * can cause problems if it changes the completion type of the finally
+ * block. See ECMA 262 Sections 8.9 & 12.14
+ */
+ if (NodeUtil.hasFinally(n)) {
+ Node finallyBlock = n.getLastChild();
+ tryMinimizeExits(finallyBlock, exitType, labelName);
+ }
+ }
+
+ // Just a 'label'.
+ if (n.isLabel()) {
+ Node labelBlock = n.getLastChild();
+ tryMinimizeExits(labelBlock, exitType, labelName);
+ }
+
+ // TODO(johnlenz): The last case of SWITCH statement?
+
+ // The rest assumes a block with at least one child, bail on anything else.
+ if (!n.isBlock() || n.getLastChild() == null) {
+ return;
+ }
+
+ // Multiple if-exits can be converted in a single pass.
+ // Convert ""if (blah) break; if (blah2) break; other_stmt;"" to
+ // become ""if (blah); else { if (blah2); else { other_stmt; } }""
+ // which will get converted to ""if (!blah && !blah2) { other_stmt; }"".
+ for (Node c : n.children()) {
+
+ // An 'if' block to process below.
+ if (c.isIf()) {
+ Node ifTree = c;
+ Node trueBlock, falseBlock;
+
+ // First, the true condition block.
+ trueBlock = ifTree.getFirstChild().getNext();
+ falseBlock = trueBlock.getNext();
+ tryMinimizeIfBlockExits(trueBlock, falseBlock,
+ ifTree, exitType, labelName);
+
+ // Now the else block.
+ // The if blocks may have changed, get them again.
+ trueBlock = ifTree.getFirstChild().getNext();
+ falseBlock = trueBlock.getNext();
+ if (falseBlock != null) {
+ tryMinimizeIfBlockExits(falseBlock, trueBlock,
+ ifTree, exitType, labelName);
+ }
+ }
+
+ if (c == n.getLastChild()) {
+ break;
+ }
+ }
+
+ // Now try to minimize the exits of the last child, if it is removed
+ // look at what has become the last child.
+ for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) {
+ tryMinimizeExits(c, exitType, labelName);
+ // If the node is still the last child, we are done.
+ if (c == n.getLastChild()) {
+ break;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDontRemoveBreakInTryFinally() throws Exception {
+ foldSame(""function f() {b:try{throw 9} finally {break b} return 1;}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""fallthrough"")
+ private void tryRemoveUnconditionalBranching(Node n) {
+ /*
+ * For each unconditional branching control flow node, check to see
+ * if the ControlFlowAnalysis.computeFollowNode of that node is same as
+ * the branching target. If it is, the branch node is safe to be removed.
+ *
+ * This is not as clever as MinimizeExitPoints because it doesn't do any
+ * if-else conversion but it handles more complicated switch statements
+ * much more nicely.
+ */
+
+ // If n is null the target is the end of the function, nothing to do.
+ if (n == null) {
+ return;
+ }
+
+ DiGraphNode gNode = cfg.getDirectedGraphNode(n);
+
+ if (gNode == null) {
+ return;
+ }
+
+ switch (n.getType()) {
+ case Token.RETURN:
+ if (n.hasChildren()) {
+ break;
+ }
+ case Token.BREAK:
+ case Token.CONTINUE:
+ // We are looking for a control flow changing statement that always
+ // branches to the same node. If after removing it control still
+ // branches to the same node, it is safe to remove.
+ List> outEdges = gNode.getOutEdges();
+ if (outEdges.size() == 1 &&
+ // If there is a next node, this jump is not useless.
+ (n.getNext() == null || n.getNext().isFunction())) {
+
+ Preconditions.checkState(
+ outEdges.get(0).getValue() == Branch.UNCOND);
+ Node fallThrough = computeFollowing(n);
+ Node nextCfgNode = outEdges.get(0).getDestination().getValue();
+ if (nextCfgNode == fallThrough) {
+ removeNode(n);
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue4177428_return() {
+ test(
+ ""f = function() {\n"" +
+ "" var action;\n"" +
+ "" a: {\n"" +
+ "" var proto = null;\n"" +
+ "" try {\n"" +
+ "" proto = new Proto\n"" +
+ "" } finally {\n"" +
+ "" action = proto;\n"" +
+ "" return\n"" + // Keep this...
+ "" }\n"" +
+ "" }\n"" +
+ "" alert(action)\n"" + // and remove this.
+ ""};"",
+ ""f = function() {\n"" +
+ "" var action;\n"" +
+ "" a: {\n"" +
+ "" var proto = null;\n"" +
+ "" try {\n"" +
+ "" proto = new Proto\n"" +
+ "" } finally {\n"" +
+ "" action = proto;\n"" +
+ "" return\n"" +
+ "" }\n"" +
+ "" }\n"" +
+ ""};""
+ );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean isSimpleNumber(String s) {
+ int len = s.length();
+ for (int index = 0; index < len; index++) {
+ char c = s.charAt(index);
+ if (c < '0' || c > '9') {
+ return false;
+ }
+ }
+ return len > 0 && s.charAt(0) != '0';
+ }
+
+// Test Case
+[/INST]
+ public void testIssue942() {
+ assertPrint(""var x = {0: 1};"", ""var x={0:1}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void annotateCalls(Node n) {
+ Preconditions.checkState(n.isCall());
+
+ // Keep track of of the ""this"" context of a call. A call without an
+ // explicit ""this"" is a free call.
+ Node first = n.getFirstChild();
+
+ // ignore cast nodes.
+
+ if (!NodeUtil.isGet(first)) {
+ n.putBooleanProp(Node.FREE_CALL, true);
+ }
+
+ // Keep track of the context in which eval is called. It is important
+ // to distinguish between ""(0, eval)()"" and ""eval()"".
+ if (first.isName() &&
+ ""eval"".equals(first.getString())) {
+ first.putBooleanProp(Node.DIRECT_EVAL, true);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue937() {
+ CompilerOptions options = createCompilerOptions();
+ CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
+ level.setOptionsForCompilationLevel(options);
+ WarningLevel warnings = WarningLevel.DEFAULT;
+ warnings.setOptionsForWarningLevel(options);
+
+ String code = """" +
+ ""console.log("" +
+ ""/** @type {function():!string} */ ((new x())['abc'])() );"";
+ String result = """" +
+ ""console.log((new x()).abc());"";
+ test(options, code, result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void traverse(Node node) {
+ // The goal here is to avoid retraversing
+ // the entire AST to catch newly created opportunities.
+ // So we track whether a ""unit of code"" has changed,
+ // and revisit immediately.
+ if (!shouldVisit(node)) {
+ return;
+ }
+
+ int visits = 0;
+ do {
+ Node c = node.getFirstChild();
+ while(c != null) {
+ traverse(c);
+ Node next = c.getNext();
+ c = next;
+ }
+
+ visit(node);
+ visits++;
+
+ Preconditions.checkState(visits < 10000, ""too many interations"");
+ } while (shouldRetraverse(node));
+
+ exitNode(node);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue787() {
+ CompilerOptions options = createCompilerOptions();
+ CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
+ level.setOptionsForCompilationLevel(options);
+ WarningLevel warnings = WarningLevel.DEFAULT;
+ warnings.setOptionsForWarningLevel(options);
+
+ String code = """" +
+ ""function some_function() {\n"" +
+ "" var fn1;\n"" +
+ "" var fn2;\n"" +
+ ""\n"" +
+ "" if (any_expression) {\n"" +
+ "" fn2 = external_ref;\n"" +
+ "" fn1 = function (content) {\n"" +
+ "" return fn2();\n"" +
+ "" }\n"" +
+ "" }\n"" +
+ ""\n"" +
+ "" return {\n"" +
+ "" method1: function () {\n"" +
+ "" if (fn1) fn1();\n"" +
+ "" return true;\n"" +
+ "" },\n"" +
+ "" method2: function () {\n"" +
+ "" return false;\n"" +
+ "" }\n"" +
+ "" }\n"" +
+ ""}"";
+
+ String result = """" +
+ ""function some_function() {\n"" +
+ "" var a, b;\n"" +
+ "" any_expression && (b = external_ref, a = function() {\n"" +
+ "" return b()\n"" +
+ "" });\n"" +
+ "" return{method1:function() {\n"" +
+ "" a && a();\n"" +
+ "" return !0\n"" +
+ "" }, method2:function() {\n"" +
+ "" return !1\n"" +
+ "" }}\n"" +
+ ""}\n"" +
+ """";
+
+ test(options, code, result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void inlineAliases(GlobalNamespace namespace) {
+ // Invariant: All the names in the worklist meet condition (a).
+ Deque workList = new ArrayDeque(namespace.getNameForest());
+ while (!workList.isEmpty()) {
+ Name name = workList.pop();
+
+ // Don't attempt to inline a getter or setter property as a variable.
+ if (name.type == Name.Type.GET || name.type == Name.Type.SET) {
+ continue;
+ }
+
+ if (name.globalSets == 1 && name.localSets == 0 &&
+ name.aliasingGets > 0) {
+ // {@code name} meets condition (b). Find all of its local aliases
+ // and try to inline them.
+ List refs = Lists.newArrayList(name.getRefs());
+ for (Ref ref : refs) {
+ if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) {
+ // {@code name} meets condition (c). Try to inline it.
+ if (inlineAliasIfPossible(ref, namespace)) {
+ name.removeRef(ref);
+ }
+ }
+ }
+ }
+
+ // Check if {@code name} has any aliases left after the
+ // local-alias-inlining above.
+ if ((name.type == Name.Type.OBJECTLIT ||
+ name.type == Name.Type.FUNCTION) &&
+ name.aliasingGets == 0 && name.props != null) {
+ // All of {@code name}'s children meet condition (a), so they can be
+ // added to the worklist.
+ workList.addAll(name.props);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue931() {
+ collapsePropertiesOnExternTypes = true;
+ testSame(
+ ""function f() {\n"" +
+ "" return function () {\n"" +
+ "" var args = arguments;\n"" +
+ "" setTimeout(function() { alert(args); }, 0);\n"" +
+ "" }\n"" +
+ ""};\n"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static boolean isJSIdentifier(String s) {
+ int length = s.length();
+
+ if (length == 0 ||
+ !Character.isJavaIdentifierStart(s.charAt(0))) {
+ return false;
+ }
+
+ for (int i = 1; i < length; i++) {
+ if (
+ !Character.isJavaIdentifierPart(s.charAt(i))) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testQuotedProps() {
+ testSame(""({'':0})"");
+ testSame(""({'1.0':0})"");
+ testSame(""({'\u1d17A':0})"");
+ testSame(""({'a\u0004b':0})"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryMinimizeIf(Node n) {
+
+ Node parent = n.getParent();
+
+ Node cond = n.getFirstChild();
+
+ /* If the condition is a literal, we'll let other
+ * optimizations try to remove useless code.
+ */
+ if (NodeUtil.isLiteralValue(cond, true)) {
+ return n;
+ }
+
+ Node thenBranch = cond.getNext();
+ Node elseBranch = thenBranch.getNext();
+
+ if (elseBranch == null) {
+ if (isFoldableExpressBlock(thenBranch)) {
+ Node expr = getBlockExpression(thenBranch);
+ if (!late && isPropertyAssignmentInExpression(expr)) {
+ // Keep opportunities for CollapseProperties such as
+ // a.longIdentifier || a.longIdentifier = ... -> var a = ...;
+ // until CollapseProperties has been run.
+ return n;
+ }
+
+ if (cond.isNot()) {
+ // if(!x)bar(); -> x||bar();
+ if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) &&
+ isLowerPrecedenceInExpression(expr.getFirstChild(),
+ OR_PRECEDENCE)) {
+ // It's not okay to add two sets of parentheses.
+ return n;
+ }
+
+ Node or = IR.or(
+ cond.removeFirstChild(),
+ expr.removeFirstChild()).srcref(n);
+ Node newExpr = NodeUtil.newExpr(or);
+ parent.replaceChild(n, newExpr);
+ reportCodeChange();
+
+ return newExpr;
+ }
+
+ // if(x)foo(); -> x&&foo();
+ if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&
+ isLowerPrecedenceInExpression(expr.getFirstChild(),
+ AND_PRECEDENCE)) {
+ // One additional set of parentheses is worth the change even if
+ // there is no immediate code size win. However, two extra pair of
+ // {}, we would have to think twice. (unless we know for sure the
+ // we can further optimize its parent.
+ return n;
+ }
+
+ n.removeChild(cond);
+ Node and = IR.and(cond, expr.removeFirstChild()).srcref(n);
+ Node newExpr = NodeUtil.newExpr(and);
+ parent.replaceChild(n, newExpr);
+ reportCodeChange();
+
+ return newExpr;
+ } else {
+
+ // Try to combine two IF-ELSE
+ if (NodeUtil.isStatementBlock(thenBranch) &&
+ thenBranch.hasOneChild()) {
+ Node innerIf = thenBranch.getFirstChild();
+
+ if (innerIf.isIf()) {
+ Node innerCond = innerIf.getFirstChild();
+ Node innerThenBranch = innerCond.getNext();
+ Node innerElseBranch = innerThenBranch.getNext();
+
+ if (innerElseBranch == null &&
+ !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&
+ isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) {
+ n.detachChildren();
+ n.addChildToBack(
+ IR.and(
+ cond,
+ innerCond.detachFromParent())
+ .srcref(cond));
+ n.addChildrenToBack(innerThenBranch.detachFromParent());
+ reportCodeChange();
+ // Not worth trying to fold the current IF-ELSE into && because
+ // the inner IF-ELSE wasn't able to be folded into && anyways.
+ return n;
+ }
+ }
+ }
+ }
+
+ return n;
+ }
+
+ /* TODO(dcc) This modifies the siblings of n, which is undesirable for a
+ * peephole optimization. This should probably get moved to another pass.
+ */
+ tryRemoveRepeatedStatements(n);
+
+ // if(!x)foo();else bar(); -> if(x)bar();else foo();
+ // An additional set of curly braces isn't worth it.
+ if (cond.isNot() && !consumesDanglingElse(elseBranch)) {
+ n.replaceChild(cond, cond.removeFirstChild());
+ n.removeChild(thenBranch);
+ n.addChildToBack(thenBranch);
+ reportCodeChange();
+ return n;
+ }
+
+ // if(x)return 1;else return 2; -> return x?1:2;
+ if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) {
+ Node thenExpr = getBlockReturnExpression(thenBranch);
+ Node elseExpr = getBlockReturnExpression(elseBranch);
+ n.removeChild(cond);
+ thenExpr.detachFromParent();
+ elseExpr.detachFromParent();
+
+ // note - we ignore any cases with ""return;"", technically this
+ // can be converted to ""return undefined;"" or some variant, but
+ // that does not help code size.
+ Node returnNode = IR.returnNode(
+ IR.hook(cond, thenExpr, elseExpr)
+ .srcref(n));
+ parent.replaceChild(n, returnNode);
+ reportCodeChange();
+ return returnNode;
+ }
+
+ boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch);
+ boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch);
+
+ if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) {
+ Node thenOp = getBlockExpression(thenBranch).getFirstChild();
+ Node elseOp = getBlockExpression(elseBranch).getFirstChild();
+ if (thenOp.getType() == elseOp.getType()) {
+ // if(x)a=1;else a=2; -> a=x?1:2;
+ if (NodeUtil.isAssignmentOp(thenOp)) {
+ Node lhs = thenOp.getFirstChild();
+ if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) &&
+ // if LHS has side effects, don't proceed [since the optimization
+ // evaluates LHS before cond]
+ // NOTE - there are some circumstances where we can
+ // proceed even if there are side effects...
+ !mayEffectMutableState(lhs)) {
+
+ n.removeChild(cond);
+ Node assignName = thenOp.removeFirstChild();
+ Node thenExpr = thenOp.removeFirstChild();
+ Node elseExpr = elseOp.getLastChild();
+ elseOp.removeChild(elseExpr);
+
+ Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n);
+ Node assign = new Node(thenOp.getType(), assignName, hookNode)
+ .srcref(thenOp);
+ Node expr = NodeUtil.newExpr(assign);
+ parent.replaceChild(n, expr);
+ reportCodeChange();
+
+ return expr;
+ }
+ }
+ }
+ // if(x)foo();else bar(); -> x?foo():bar()
+ n.removeChild(cond);
+ thenOp.detachFromParent();
+ elseOp.detachFromParent();
+ Node expr = IR.exprResult(
+ IR.hook(cond, thenOp, elseOp).srcref(n));
+ parent.replaceChild(n, expr);
+ reportCodeChange();
+ return expr;
+ }
+
+ boolean thenBranchIsVar = isVarBlock(thenBranch);
+ boolean elseBranchIsVar = isVarBlock(elseBranch);
+
+ // if(x)var y=1;else y=2 -> var y=x?1:2
+ if (thenBranchIsVar && elseBranchIsExpressionBlock &&
+ getBlockExpression(elseBranch).getFirstChild().isAssign()) {
+
+ Node var = getBlockVar(thenBranch);
+ Node elseAssign = getBlockExpression(elseBranch).getFirstChild();
+
+ Node name1 = var.getFirstChild();
+ Node maybeName2 = elseAssign.getFirstChild();
+
+ if (name1.hasChildren()
+ && maybeName2.isName()
+ && name1.getString().equals(maybeName2.getString())) {
+ Node thenExpr = name1.removeChildren();
+ Node elseExpr = elseAssign.getLastChild().detachFromParent();
+ cond.detachFromParent();
+ Node hookNode = IR.hook(cond, thenExpr, elseExpr)
+ .srcref(n);
+ var.detachFromParent();
+ name1.addChildrenToBack(hookNode);
+ parent.replaceChild(n, var);
+ reportCodeChange();
+ return var;
+ }
+
+ // if(x)y=1;else var y=2 -> var y=x?1:2
+ } else if (elseBranchIsVar && thenBranchIsExpressionBlock &&
+ getBlockExpression(thenBranch).getFirstChild().isAssign()) {
+
+ Node var = getBlockVar(elseBranch);
+ Node thenAssign = getBlockExpression(thenBranch).getFirstChild();
+
+ Node maybeName1 = thenAssign.getFirstChild();
+ Node name2 = var.getFirstChild();
+
+ if (name2.hasChildren()
+ && maybeName1.isName()
+ && maybeName1.getString().equals(name2.getString())) {
+ Node thenExpr = thenAssign.getLastChild().detachFromParent();
+ Node elseExpr = name2.removeChildren();
+ cond.detachFromParent();
+ Node hookNode = IR.hook(cond, thenExpr, elseExpr)
+ .srcref(n);
+ var.detachFromParent();
+ name2.addChildrenToBack(hookNode);
+ parent.replaceChild(n, var);
+ reportCodeChange();
+
+ return var;
+ }
+ }
+
+ return n;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue925() {
+ test(
+ ""if (x[--y] === 1) {\n"" +
+ "" x[y] = 0;\n"" +
+ ""} else {\n"" +
+ "" x[y] = 1;\n"" +
+ ""}"",
+ ""(x[--y] === 1) ? x[y] = 0 : x[y] = 1;"");
+
+ test(
+ ""if (x[--y]) {\n"" +
+ "" a = 0;\n"" +
+ ""} else {\n"" +
+ "" a = 1;\n"" +
+ ""}"",
+ ""a = (x[--y]) ? 0 : 1;"");
+
+ test(""if (x++) { x += 2 } else { x += 3 }"",
+ ""x++ ? x += 2 : x += 3"");
+
+ test(""if (x++) { x = x + 2 } else { x = x + 3 }"",
+ ""x = x++ ? x + 2 : x + 3"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private String getRemainingJSDocLine() {
+ String result = stream.getRemainingJSDocLine();
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testTextExtents() {
+ parse(""@return {@code foo} bar \n * baz. */"",
+ true, ""Bad type annotation. type not recognized due to syntax error"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void process(Node externs, Node root) {
+ NodeTraversal.traverse(compiler, externs, new ProcessExterns());
+ NodeTraversal.traverse(compiler, root, new ProcessProperties());
+
+ Set reservedNames =
+ new HashSet(externedNames.size() + quotedNames.size());
+ reservedNames.addAll(externedNames);
+ reservedNames.addAll(quotedNames);
+
+ int numRenamedPropertyNames = 0;
+ int numSkippedPropertyNames = 0;
+ Set propsByFreq = new TreeSet(FREQUENCY_COMPARATOR);
+ for (Property p : propertyMap.values()) {
+ if (!p.skipAmbiguating) {
+ ++numRenamedPropertyNames;
+ computeRelatedTypes(p.type);
+ propsByFreq.add(p);
+ } else {
+ ++numSkippedPropertyNames;
+ reservedNames.add(p.oldName);
+ }
+ }
+
+ PropertyGraph graph = new PropertyGraph(Lists.newLinkedList(propsByFreq));
+ GraphColoring coloring =
+ new GreedyGraphColoring(graph, FREQUENCY_COMPARATOR);
+ int numNewPropertyNames = coloring.color();
+
+ NameGenerator nameGen = new NameGenerator(
+ reservedNames, """", reservedCharacters);
+ for (int i = 0; i < numNewPropertyNames; ++i) {
+ colorMap.put(i, nameGen.generateNextName());
+ }
+ for (GraphNode node : graph.getNodes()) {
+ node.getValue().newName = colorMap.get(node.getAnnotation().hashCode());
+ renamingMap.put(node.getValue().oldName, node.getValue().newName);
+ }
+
+ // Update the string nodes.
+ for (Node n : stringNodesToRename) {
+ String oldName = n.getString();
+ Property p = propertyMap.get(oldName);
+ if (p != null && p.newName != null) {
+ Preconditions.checkState(oldName.equals(p.oldName));
+ if (!p.newName.equals(oldName)) {
+ n.setString(p.newName);
+ compiler.reportCodeChange();
+ }
+ }
+ }
+
+ logger.info(""Collapsed "" + numRenamedPropertyNames + "" properties into ""
+ + numNewPropertyNames + "" and skipped renaming ""
+ + numSkippedPropertyNames + "" properties."");
+ }
+
+// Test Case
+[/INST]
+ public void testImplementsAndExtends() {
+ String js = """"
+ + ""/** @interface */ function Foo() {}\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" */\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.y = function() { return 3; };\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" * @extends {Bar}\n""
+ + "" * @implements {Foo}\n""
+ + "" */\n""
+ + ""function SubBar(){ }\n""
+ + ""/** @param {Foo} x */ function f(x) { x.z = 3; }\n""
+ + ""/** @param {SubBar} x */ function g(x) { x.z = 3; }"";
+ String output = """"
+ + ""function Foo(){}\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.b = function() { return 3; };\n""
+ + ""function SubBar(){}\n""
+ + ""function f(x) { x.a = 3; }\n""
+ + ""function g(x) { x.a = 3; }"";
+ test(js, output);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean isIndependentOf(Property prop) {
+ if (typesRelatedToSet.intersects(prop.typesSet)) {
+ return false;
+ }
+ return !getRelated(prop.type).intersects(typesInSet);
+ }
+
+// Test Case
+[/INST]
+ public void testImplementsAndExtends() {
+ String js = """"
+ + ""/** @interface */ function Foo() {}\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" */\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.y = function() { return 3; };\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" * @extends {Bar}\n""
+ + "" * @implements {Foo}\n""
+ + "" */\n""
+ + ""function SubBar(){ }\n""
+ + ""/** @param {Foo} x */ function f(x) { x.z = 3; }\n""
+ + ""/** @param {SubBar} x */ function g(x) { x.z = 3; }"";
+ String output = """"
+ + ""function Foo(){}\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.b = function() { return 3; };\n""
+ + ""function SubBar(){}\n""
+ + ""function f(x) { x.a = 3; }\n""
+ + ""function g(x) { x.a = 3; }"";
+ test(js, output);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void addNode(Property prop) {
+ typesInSet.or(prop.typesSet);
+ typesRelatedToSet.or(getRelated(prop.type));
+ }
+
+// Test Case
+[/INST]
+ public void testImplementsAndExtends() {
+ String js = """"
+ + ""/** @interface */ function Foo() {}\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" */\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.y = function() { return 3; };\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" * @extends {Bar}\n""
+ + "" * @implements {Foo}\n""
+ + "" */\n""
+ + ""function SubBar(){ }\n""
+ + ""/** @param {Foo} x */ function f(x) { x.z = 3; }\n""
+ + ""/** @param {SubBar} x */ function g(x) { x.z = 3; }"";
+ String output = """"
+ + ""function Foo(){}\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.b = function() { return 3; };\n""
+ + ""function SubBar(){}\n""
+ + ""function f(x) { x.a = 3; }\n""
+ + ""function g(x) { x.a = 3; }"";
+ test(js, output);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FunctionType findOverriddenFunction(
+ ObjectType ownerType, String propName) {
+ // First, check to see if the property is implemented
+ // on a superclass.
+ JSType propType = ownerType.getPropertyType(propName);
+ if (propType instanceof FunctionType) {
+ return (FunctionType) propType;
+ }
+ // If it's not, then check to see if it's implemented
+ // on an implemented interface.
+
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testImplementsAndExtends() {
+ String js = """"
+ + ""/** @interface */ function Foo() {}\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" */\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.y = function() { return 3; };\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" * @extends {Bar}\n""
+ + "" * @implements {Foo}\n""
+ + "" */\n""
+ + ""function SubBar(){ }\n""
+ + ""/** @param {Foo} x */ function f(x) { x.z = 3; }\n""
+ + ""/** @param {SubBar} x */ function g(x) { x.z = 3; }"";
+ String output = """"
+ + ""function Foo(){}\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.b = function() { return 3; };\n""
+ + ""function SubBar(){}\n""
+ + ""function f(x) { x.a = 3; }\n""
+ + ""function g(x) { x.a = 3; }"";
+ test(js, output);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void addNonUnionType(JSType newType) {
+ if (skipAmbiguating || isInvalidatingType(newType)) {
+ skipAmbiguating = true;
+ return;
+ }
+
+ if (type == null) {
+ type = newType;
+ } else {
+ type = type.getLeastSupertype(newType);
+ }
+ typesSet.set(getIntForType(newType));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testImplementsAndExtends() {
+ String js = """"
+ + ""/** @interface */ function Foo() {}\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" */\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.y = function() { return 3; };\n""
+ + ""/**\n""
+ + "" * @constructor\n""
+ + "" * @extends {Bar}\n""
+ + "" * @implements {Foo}\n""
+ + "" */\n""
+ + ""function SubBar(){ }\n""
+ + ""/** @param {Foo} x */ function f(x) { x.z = 3; }\n""
+ + ""/** @param {SubBar} x */ function g(x) { x.z = 3; }"";
+ String output = """"
+ + ""function Foo(){}\n""
+ + ""function Bar(){}\n""
+ + ""Bar.prototype.b = function() { return 3; };\n""
+ + ""function SubBar(){}\n""
+ + ""function f(x) { x.a = 3; }\n""
+ + ""function g(x) { x.a = 3; }"";
+ test(js, output);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void replaceReferencesToThis(Node node, String name) {
+ if (NodeUtil.isFunction(node)) {
+ return;
+ }
+
+ for (Node child : node.children()) {
+ if (NodeUtil.isThis(child)) {
+ Node newName = Node.newString(Token.NAME, name);
+ node.replaceChild(child, newName);
+ } else {
+ replaceReferencesToThis(child, name);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testRewritePrototypeMethods2() throws Exception {
+ // type checking on
+ enableTypeCheck(CheckLevel.ERROR);
+ checkTypes(RewritePrototypeMethodTestInput.INPUT,
+ RewritePrototypeMethodTestInput.EXPECTED,
+ RewritePrototypeMethodTestInput.EXPECTED_TYPE_CHECKING_ON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ boolean defineProperty(String name, JSType type,
+ boolean inferred, boolean inExterns) {
+ if (""prototype"".equals(name)) {
+ ObjectType objType = type.toObjectType();
+ if (objType != null) {
+ return setPrototype(
+ new FunctionPrototypeType(
+ registry, this, objType, isNativeObjectType()));
+ } else {
+ return false;
+ }
+ }
+ return super.defineProperty(name, type, inferred, inExterns);
+ }
+
+
+// Test Case
+[/INST]
+ public void testRewritePrototypeMethods2() throws Exception {
+ // type checking on
+ enableTypeCheck(CheckLevel.ERROR);
+ checkTypes(RewritePrototypeMethodTestInput.INPUT,
+ RewritePrototypeMethodTestInput.EXPECTED,
+ RewritePrototypeMethodTestInput.EXPECTED_TYPE_CHECKING_ON);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void addPossibleSignature(String name, Node node, NodeTraversal t) {
+ boolean signatureAdded = false;
+ if (node.getType() == Token.FUNCTION) {
+ // The node we're looking at is a function, so we can add it directly
+ addSignature(name, node, t.getSourceName());
+ signatureAdded = true;
+ } else if (node.getType() == Token.NAME) {
+ String functionName = node.getString();
+ Scope.Var v = t.getScope().getVar(functionName);
+ if (v == null) {
+ if (compiler.isIdeMode()) {
+ return;
+ } else {
+ throw new IllegalStateException(
+ ""VarCheck should have caught this undefined function"");
+ }
+ }
+ Node function = v.getInitialValue();
+ if (function != null &&
+ function.getType() == Token.FUNCTION) {
+ addSignature(name, function, v.getInputName());
+ signatureAdded = true;
+ }
+ }
+ if (!signatureAdded) {
+ nonMethodProperties.add(name);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue2508576_1() {
+ // Method defined by an extern should be left alone.
+ String externs = ""function alert(a) {}"";
+ testSame(externs, ""({a:alert,b:alert}).a(\""a\"")"", null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (n.getType() != Token.NAME) {
+ return;
+ }
+
+ String name = n.getString();
+
+ // Ignore anonymous functions
+ if (name.length() == 0) {
+ return;
+ }
+
+ // Is this local or Global?
+ Scope.Var var = t.getScope().getVar(name);
+ boolean local = (var != null) && var.isLocal();
+
+ // Are we renaming global variables?
+ if (!local && localRenamingOnly) {
+ reservedNames.add(name);
+ return;
+ }
+
+ // Are we renaming anonymous function names?
+ if (preserveAnonymousFunctionNames
+ && var != null
+ && NodeUtil.isAnonymousFunction(var.getParentNode())) {
+ reservedNames.add(name);
+ return;
+ }
+
+ // Check if we can rename this.
+ if (!okToRenameVar(name, local)) {
+ // Blindly de-uniquify for the Prototype library for issue 103.
+ return;
+ }
+
+ if (isExternsPass_) {
+ // Keep track of extern globals.
+ if (!local) {
+ externNames.add(name);
+ }
+ return;
+ }
+
+ if (local) {
+ // Local var: assign a new name
+ String tempName = LOCAL_VAR_PREFIX + var.getLocalVarIndex();
+ incCount(tempName, null);
+ localNameNodes.add(n);
+ localTempNames.add(tempName);
+ } else if (var != null) { // Not an extern
+ // If it's global, increment global count
+ incCount(name, var.input);
+ globalNameNodes.add(n);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue2508576_1() {
+ // Method defined by an extern should be left alone.
+ String externs = ""function alert(a) {}"";
+ testSame(externs, ""({a:alert,b:alert}).a(\""a\"")"", null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void process(Node externs, Node root) {
+ NodeTraversal.traverse(compiler, root,
+ new NormalizeStatements(compiler, assertOnChange));
+ removeDuplicateDeclarations(root);
+ if (MAKE_LOCAL_NAMES_UNIQUE) {
+ MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
+ NodeTraversal t = new NodeTraversal(compiler, renamer);
+ t.traverseRoots(externs, root);
+ }
+ // It is important that removeDuplicateDeclarations runs after
+ // MakeDeclaredNamesUnique in order for catch block exception names to be
+ // handled properly. Specifically, catch block exception names are
+ // only valid within the catch block, but our currect Scope logic
+ // has no concept of this and includes it in the containing function
+ // (or global scope). MakeDeclaredNamesUnique makes the catch exception
+ // names unique so that removeDuplicateDeclarations() will properly handle
+ // cases where a function scope variable conflict with a exception name:
+ // function f() {
+ // try {throw 0;} catch(e) {e; /* catch scope 'e'*/}
+ // var e = 1; // f scope 'e'
+ // }
+ // otherwise 'var e = 1' would be rewritten as 'e = 1'.
+ // TODO(johnlenz): Introduce a seperate scope for catch nodes.
+ new PropogateConstantAnnotations(compiler, assertOnChange)
+ .process(externs, root);
+ }
+
+// Test Case
+[/INST]
+ public void testOnlyInversion3() {
+ invert = true;
+ test(
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a$$2;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a$$3;"" +
+ "" }"" +
+ ""}"",
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a;"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static String getOrginalNameInternal(String name, int index) {
+ return name.substring(0, index);
+ }
+
+// Test Case
+[/INST]
+ public void testOnlyInversion3() {
+ invert = true;
+ test(
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a$$2;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a$$3;"" +
+ "" }"" +
+ ""}"",
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a;"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node node, Node parent) {
+ if (node.getType() == Token.NAME) {
+ String oldName = node.getString();
+ if (containsSeparator(oldName)) {
+ Scope scope = t.getScope();
+ Var var = t.getScope().getVar(oldName);
+ if (var == null || var.isGlobal()) {
+ return;
+ }
+
+ if (nameMap.containsKey(var)) {
+ node.setString(nameMap.get(var));
+ } else {
+ int index = indexOfSeparator(oldName);
+ String newName = getOrginalNameInternal(oldName, index);
+ String suffix = getNameSuffix(oldName, index);
+
+ // Merge any names that were referenced but not declared in the current
+ // scope.
+ // If there isn't anything left in the stack we will be going into the
+ // global scope: don't try to build a set of referenced names for the
+ // global scope.
+ boolean recurseScopes = false;
+ if (!suffix.matches(""\\d+"")) {
+ recurseScopes = true;
+ }
+
+ /**
+ * For the Var declared in the current scope determine if it is possible
+ * to revert the name to its orginal form without conflicting with other
+ * values.
+ */
+ // Check if the new name is valid and if it would cause conflicts.
+ if (var.scope.isDeclared(newName, recurseScopes) ||
+ !TokenStream.isJSIdentifier(newName)) {
+ newName = oldName;
+ } else {
+ var.scope.declare(newName, var.nameNode, null, null);
+ // Adding a reference to the new name to prevent either the parent
+ // scopes or the current scope renaming another var to this new name.
+ Node parentNode = var.getParentNode();
+ if (parentNode.getType() == Token.FUNCTION &&
+ parentNode == var.scope.getRootNode()) {
+ var.getNameNode().setString(newName);
+ }
+ node.setString(newName);
+ compiler.reportCodeChange();
+ }
+
+ nameMap.put(var, newName);
+
+ }
+
+ // Add all referenced names to the set so it is possible to check for
+ // conflicts.
+ // Store only references to candidate names in the node map.
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOnlyInversion3() {
+ invert = true;
+ test(
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a$$2;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a$$3;"" +
+ "" }"" +
+ ""}"",
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a;"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void addDeclaredName(String name) {
+ if (global) {
+ reserveName(name);
+ } else {
+ // It hasn't been declared locally yet, so increment the count.
+ if (!declarations.containsKey(name)) {
+ int id = incrementNameCount(name);
+ String newName = null;
+ if (id != 0) {
+ newName = getUniqueName(name, id);
+ }
+ declarations.put(name, newName);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOnlyInversion3() {
+ invert = true;
+ test(
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a$$2;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a$$3;"" +
+ "" }"" +
+ ""}"",
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a;"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void addDeclaredName(String name) {
+ if (!declarations.containsKey(name)) {
+ declarations.put(name, getUniqueName(name));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOnlyInversion3() {
+ invert = true;
+ test(
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a$$2;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a$$3;"" +
+ "" }"" +
+ ""}"",
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a;"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testOnlyInversion3() {
+ invert = true;
+ test(
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a$$2;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a$$3;"" +
+ "" }"" +
+ ""}"",
+ ""function x1() {"" +
+ "" var a$$1;"" +
+ "" function x2() {"" +
+ "" var a;"" +
+ "" }"" +
+ "" function x3() {"" +
+ "" var a;"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public FlowScope getPreciserScopeKnowingConditionOutcome(Node condition,
+ FlowScope blindScope, boolean outcome) {
+ if (condition.getType() == CALL && condition.getChildCount() == 2) {
+ Node callee = condition.getFirstChild();
+ Node param = condition.getLastChild();
+ if (callee.getType() == GETPROP && param.isQualifiedName()) {
+ JSType paramType = getTypeIfRefinable(param, blindScope);
+ if (paramType != null) {
+ Node left = callee.getFirstChild();
+ Node right = callee.getLastChild();
+ if (left.getType() == NAME && ""goog"".equals(left.getString()) &&
+ right.getType() == STRING) {
+ Function restricter =
+ restricters.get(right.getString());
+ if (restricter != null) {
+ return restrictParameter(param, paramType, blindScope, restricter,
+ outcome);
+ }
+ }
+ }
+ }
+ }
+ return nextPreciserScopeKnowingConditionOutcome(
+ condition, blindScope, outcome);
+ }
+
+// Test Case
+[/INST]
+ public void testGoogIsArrayOnNull() throws Exception {
+ testClosureFunction(""goog.isArray"",
+ null,
+ ARRAY_TYPE,
+ null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope traverseName(Node n, FlowScope scope) {
+ String varName = n.getString();
+ Node value = n.getFirstChild();
+ JSType type = n.getJSType();
+ if (value != null) {
+ scope = traverse(value, scope);
+ updateScopeForTypeChange(scope, n, n.getJSType() /* could be null */,
+ getJSType(value));
+ return scope;
+ } else {
+ StaticSlot var = scope.getSlot(varName);
+ if (var != null &&
+ !(var.isTypeInferred() && unflowableVarNames.contains(varName))) {
+ // There are two situations where we don't want to use type information
+ // from the scope, even if we have it.
+
+ // 1) The var is escaped in a weird way, e.g.,
+ // function f() { var x = 3; function g() { x = null } (x); }
+
+ // 2) We're reading type information from another scope for an
+ // inferred variable.
+ // var t = null; function f() { (t); }
+
+ type = var.getType();
+ if (type == null) {
+ type = getNativeType(UNKNOWN_TYPE);
+ }
+ }
+ }
+ n.setJSType(type);
+ return scope;
+ }
+
+// Test Case
+[/INST]
+ public void testGoogIsArrayOnNull() throws Exception {
+ testClosureFunction(""goog.isArray"",
+ null,
+ ARRAY_TYPE,
+ null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ switch (n.getType()) {
+ case Token.WHILE:
+ if (CONVERT_WHILE_TO_FOR) {
+ Node expr = n.getFirstChild();
+ n.setType(Token.FOR);
+ n.addChildBefore(new Node(Token.EMPTY), expr);
+ n.addChildAfter(new Node(Token.EMPTY), expr);
+ reportCodeChange(""WHILE node"");
+ }
+ break;
+
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNormalizeFunctionDeclarations() throws Exception {
+ testSame(""function f() {}"");
+ testSame(""var f = function () {}"");
+ test(""var f = function f() {}"",
+ ""var f = function f$$1() {}"");
+ testSame(""var f = function g() {}"");
+ test(""a:function g() {}"",
+ ""a:{ var g = function () {} }"");
+ test(""{function g() {}}"",
+ ""{var g = function () {}}"");
+ testSame(""if (function g() {}) {}"");
+ test(""if (true) {function g() {}}"",
+ ""if (true) {var g = function () {}}"");
+ test(""if (true) {} else {function g() {}}"",
+ ""if (true) {} else {var g = function () {}}"");
+ testSame(""switch (function g() {}) {}"");
+ test(""switch (1) { case 1: function g() {}}"",
+ ""switch (1) { case 1: var g = function () {}}"");
+
+
+ testSameInFunction(""function f() {}"");
+ testInFunction(""f(); a:function g() {}"",
+ ""f(); a:{ var g = function () {} }"");
+ testInFunction(""f(); {function g() {}}"",
+ ""f(); {var g = function () {}}"");
+ testInFunction(""f(); if (true) {function g() {}}"",
+ ""f(); if (true) {var g = function () {}}"");
+ testInFunction(""if (true) {} else {function g() {}}"",
+ ""if (true) {} else {var g = function () {}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void onRedeclaration(
+ Scope s, String name, Node n, Node parent, Node gramps,
+ Node nodeWithLineNumber) {
+ Preconditions.checkState(n.getType() == Token.NAME);
+ if (parent.getType() == Token.VAR) {
+ // If name is ""arguments"", Var maybe null.
+ Preconditions.checkState(parent.hasOneChild());
+
+ replaceVarWithAssignment(n, parent, gramps);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNormalizeFunctionDeclarations() throws Exception {
+ testSame(""function f() {}"");
+ testSame(""var f = function () {}"");
+ test(""var f = function f() {}"",
+ ""var f = function f$$1() {}"");
+ testSame(""var f = function g() {}"");
+ test(""a:function g() {}"",
+ ""a:{ var g = function () {} }"");
+ test(""{function g() {}}"",
+ ""{var g = function () {}}"");
+ testSame(""if (function g() {}) {}"");
+ test(""if (true) {function g() {}}"",
+ ""if (true) {var g = function () {}}"");
+ test(""if (true) {} else {function g() {}}"",
+ ""if (true) {} else {var g = function () {}}"");
+ testSame(""switch (function g() {}) {}"");
+ test(""switch (1) { case 1: function g() {}}"",
+ ""switch (1) { case 1: var g = function () {}}"");
+
+
+ testSameInFunction(""function f() {}"");
+ testInFunction(""f(); a:function g() {}"",
+ ""f(); a:{ var g = function () {} }"");
+ testInFunction(""f(); {function g() {}}"",
+ ""f(); {var g = function () {}}"");
+ testInFunction(""f(); if (true) {function g() {}}"",
+ ""f(); if (true) {var g = function () {}}"");
+ testInFunction(""if (true) {} else {function g() {}}"",
+ ""if (true) {} else {var g = function () {}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static Node computeFollowNode(
+ Node fromNode, Node node, ControlFlowAnalysis cfa) {
+ /*
+ * This is the case where:
+ *
+ * 1. Parent is null implies that we are transferring control to the end of
+ * the script.
+ *
+ * 2. Parent is a function implies that we are transferring control back to
+ * the caller of the function.
+ *
+ * 3. If the node is a return statement, we should also transfer control
+ * back to the caller of the function.
+ *
+ * 4. If the node is root then we have reached the end of what we have been
+ * asked to traverse.
+ *
+ * In all cases we should transfer control to a ""symbolic return"" node.
+ * This will make life easier for DFAs.
+ */
+ Node parent = node.getParent();
+ if (parent == null || parent.isFunction() ||
+ (cfa != null && node == cfa.root)) {
+ return null;
+ }
+
+ // If we are just before a IF/WHILE/DO/FOR:
+ switch (parent.getType()) {
+ // The follow() of any of the path from IF would be what follows IF.
+ case Token.IF:
+ return computeFollowNode(fromNode, parent, cfa);
+ case Token.CASE:
+ case Token.DEFAULT_CASE:
+ // After the body of a CASE, the control goes to the body of the next
+ // case, without having to go to the case condition.
+ if (parent.getNext() != null) {
+ if (parent.getNext().isCase()) {
+ return parent.getNext().getFirstChild().getNext();
+ } else if (parent.getNext().isDefaultCase()) {
+ return parent.getNext().getFirstChild();
+ } else {
+ Preconditions.checkState(false, ""Not reachable"");
+ }
+ } else {
+ return computeFollowNode(fromNode, parent, cfa);
+ }
+ break;
+ case Token.FOR:
+ if (NodeUtil.isForIn(parent)) {
+ return parent;
+ } else {
+ return parent.getFirstChild().getNext().getNext();
+ }
+ case Token.WHILE:
+ case Token.DO:
+ return parent;
+ case Token.TRY:
+ // If we are coming out of the TRY block...
+ if (parent.getFirstChild() == node) {
+ if (NodeUtil.hasFinally(parent)) { // and have FINALLY block.
+ return computeFallThrough(parent.getLastChild());
+ } else { // and have no FINALLY.
+ return computeFollowNode(fromNode, parent, cfa);
+ }
+ // CATCH block.
+ } else if (NodeUtil.getCatchBlock(parent) == node){
+ if (NodeUtil.hasFinally(parent)) { // and have FINALLY block.
+ return computeFallThrough(node.getNext());
+ } else {
+ return computeFollowNode(fromNode, parent, cfa);
+ }
+ // If we are coming out of the FINALLY block...
+ } else if (parent.getLastChild() == node){
+ if (cfa != null) {
+ for (Node finallyNode : cfa.finallyMap.get(parent)) {
+ cfa.createEdge(fromNode, Branch.UNCOND, finallyNode);
+ }
+ }
+ return computeFollowNode(fromNode, parent, cfa);
+ }
+ }
+
+ // Now that we are done with the special cases follow should be its
+ // immediate sibling, unless its sibling is a function
+ Node nextSibling = node.getNext();
+
+ // Skip function declarations because control doesn't get pass into it.
+ while (nextSibling != null && nextSibling.isFunction()) {
+ nextSibling = nextSibling.getNext();
+ }
+
+ if (nextSibling != null) {
+ return computeFallThrough(nextSibling);
+ } else {
+ // If there are no more siblings, control is transferred up the AST.
+ return computeFollowNode(fromNode, parent, cfa);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue779() {
+ testNotMissing(
+ ""var a = f(); try { alert(); if (a > 0) return 1; }"" +
+ ""finally { a = 5; } return 2;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void init(JSSourceFile[] externs, JSModule[] modules,
+ CompilerOptions options) {
+ initOptions(options);
+
+ checkFirstModule(modules);
+
+ this.externs = makeCompilerInput(externs, true);
+ this.modules = modules;
+ // Generate the module graph, and report any errors in the module
+ // specification as errors.
+ try {
+ this.moduleGraph = new JSModuleGraph(modules);
+ } catch (JSModuleGraph.ModuleDependenceException e) {
+ // problems with the module format. Report as an error. The
+ // message gives all details.
+ report(JSError.make(MODULE_DEPENDENCY_ERROR,
+ e.getModule().getName(), e.getDependentModule().getName()));
+ return;
+ }
+ this.inputs = getAllInputsFromModules();
+ initBasedOnOptions();
+
+ initInputsByNameMap();
+ }
+
+// Test Case
+[/INST]
+ public void testEmptyModule() {
+ // When the dest module is empty, it might try to move the code to the
+ // one of the modules that the empty module depends on. In some cases
+ // this might ended up to be the same module as the definition of the code.
+ // When that happens, CrossMooduleCodeMotion might report a code change
+ // while nothing is moved. This should not be a problem if we know all
+ // modules are non-empty.
+ JSModule m1 = new JSModule(""m1"");
+ m1.add(JSSourceFile.fromCode(""m1"", ""function x() {}""));
+
+ JSModule empty = new JSModule(""empty"");
+ empty.addDependency(m1);
+
+ JSModule m2 = new JSModule(""m2"");
+ m2.add(JSSourceFile.fromCode(""m2"", ""x()""));
+ m2.addDependency(empty);
+
+ JSModule m3 = new JSModule(""m3"");
+ m3.add(JSSourceFile.fromCode(""m3"", ""x()""));
+ m3.addDependency(empty);
+
+ test(new JSModule[] {m1,empty,m2,m3},
+ new String[] {
+ """",
+ ""function x() {}"",
+ ""x()"",
+ ""x()""
+ });
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ Node getNodeForCodeInsertion(JSModule module) {
+ if (module == null) {
+ if (inputs.length == 0) {
+ throw new IllegalStateException(""No inputs"");
+ }
+
+ return inputs[0].getAstRoot(this);
+ }
+
+ List inputs = module.getInputs();
+ if (inputs.size() > 0) {
+ return inputs.get(0).getAstRoot(this);
+ }
+ for (JSModule m : getModuleGraph().getTransitiveDepsDeepestFirst(module)) {
+ inputs = m.getInputs();
+ if (inputs.size() > 0) {
+ return inputs.get(0).getAstRoot(this);
+ }
+ }
+ throw new IllegalStateException(""Root module has no inputs"");
+ }
+
+// Test Case
+[/INST]
+ public void testEmptyModule() {
+ // When the dest module is empty, it might try to move the code to the
+ // one of the modules that the empty module depends on. In some cases
+ // this might ended up to be the same module as the definition of the code.
+ // When that happens, CrossMooduleCodeMotion might report a code change
+ // while nothing is moved. This should not be a problem if we know all
+ // modules are non-empty.
+ JSModule m1 = new JSModule(""m1"");
+ m1.add(JSSourceFile.fromCode(""m1"", ""function x() {}""));
+
+ JSModule empty = new JSModule(""empty"");
+ empty.addDependency(m1);
+
+ JSModule m2 = new JSModule(""m2"");
+ m2.add(JSSourceFile.fromCode(""m2"", ""x()""));
+ m2.addDependency(empty);
+
+ JSModule m3 = new JSModule(""m3"");
+ m3.add(JSSourceFile.fromCode(""m3"", ""x()""));
+ m3.addDependency(empty);
+
+ test(new JSModule[] {m1,empty,m2,m3},
+ new String[] {
+ """",
+ ""function x() {}"",
+ ""x()"",
+ ""x()""
+ });
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static Collection getCallableDefinitions(
+ DefinitionProvider definitionProvider, Node name) {
+ List result = Lists.newArrayList();
+
+ if (!NodeUtil.isGetProp(name) && !NodeUtil.isName(name)) {
+ return null;
+ }
+ Collection decls =
+ definitionProvider.getDefinitionsReferencedAt(name);
+ if (decls == null) {
+ return null;
+ }
+
+ for (Definition current : decls) {
+ Node rValue = current.getRValue();
+ if ((rValue != null) && NodeUtil.isFunction(rValue)) {
+ result.add(current);
+ } else {
+ return null;
+ }
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testCanExposeExpression2() {
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""foo()"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo()"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""var x = foo()"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""if(foo()){}"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""switch(foo()){}"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""switch(foo()){}"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""function (){ return foo();}"", ""foo"");
+
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo() && 1"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo() || 1"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo() ? 0 : 1"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""(function(a){b = a})(foo())"", ""foo"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean canBeSideEffected(Node n, Set knownConstants) {
+ switch (n.getType()) {
+ case Token.CALL:
+ case Token.NEW:
+ // Function calls or constructor can reference changed values.
+ // TODO(johnlenz): Add some mechanism for determining that functions
+ // are unaffected by side effects.
+ return true;
+ case Token.NAME:
+ // Non-constant names values may have been changed.
+ return !NodeUtil.isConstantName(n)
+ && !knownConstants.contains(n.getString());
+
+ // Properties on constant NAMEs can still be side-effected.
+ case Token.GETPROP:
+ case Token.GETELEM:
+ return true;
+
+ // Anonymous functions definitions are not changed by side-effects,
+ // and named functions are not part of expressions.
+ }
+
+ for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
+ if (canBeSideEffected(c, knownConstants)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testCanExposeExpression2() {
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""foo()"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo()"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""var x = foo()"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""if(foo()){}"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""switch(foo()){}"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""switch(foo()){}"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""function (){ return foo();}"", ""foo"");
+
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo() && 1"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo() || 1"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""x = foo() ? 0 : 1"", ""foo"");
+ helperCanExposeExpression(
+ DecompositionType.MOVABLE, ""(function(a){b = a})(foo())"", ""foo"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void enterScope(NodeTraversal t) {
+ // TODO(user): We CAN do this in the global scope, just need to be
+ // careful when something is exported. Liveness uses bit-vector for live
+ // sets so I don't see compilation time will be a problem for running this
+ // pass in the global scope.
+ Scope scope = t.getScope();
+ if (scope.isGlobal()) {
+ return;
+ }
+ ControlFlowGraph cfg = t.getControlFlowGraph();
+
+ LiveVariablesAnalysis liveness =
+ new LiveVariablesAnalysis(cfg, scope, compiler);
+ // If the function has exactly 2 params, mark them as escaped. This is
+ // a work-around for an IE bug where it throws an exception if you
+ // write to the parameters of the callback in a sort(). See:
+ // http://code.google.com/p/closure-compiler/issues/detail?id=58
+ liveness.analyze();
+
+ UndiGraph interferenceGraph =
+ computeVariableNamesInterferenceGraph(
+ t, cfg, liveness.getEscapedLocals());
+
+ GraphColoring coloring =
+ new GreedyGraphColoring(interferenceGraph,
+ coloringTieBreaker);
+
+ coloring.color();
+ colorings.push(coloring);
+ }
+
+// Test Case
+[/INST]
+ public void testParameter4() {
+ // Make sure that we do not merge two-arg functions because of the
+ // IE sort bug (see comments in computeEscaped)
+ test(""function FUNC(x, y) {var a,b; y; a=0; a; x; b=0; b}"",
+ ""function FUNC(x, y) {var a; y; a=0; a; x; a=0; a}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""fallthrough"")
+ private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
+ WhitespaceOption option) {
+
+ if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
+ token == JsDocToken.EOF) {
+ return new ExtractionInfo("""", token);
+ }
+
+ stream.update();
+ int startLineno = stream.getLineno();
+ int startCharno = stream.getCharno() + 1;
+
+ // Read the content from the first line.
+ String line = stream.getRemainingJSDocLine();
+
+ if (option != WhitespaceOption.PRESERVE) {
+ line = line.trim();
+ }
+
+ StringBuilder builder = new StringBuilder();
+ builder.append(line);
+
+ state = State.SEARCHING_ANNOTATION;
+ token = next();
+
+ boolean ignoreStar = false;
+
+ do {
+ switch (token) {
+ case STAR:
+ if (!ignoreStar) {
+ if (builder.length() > 0) {
+ builder.append(' ');
+ }
+
+ builder.append('*');
+ }
+
+ token = next();
+ continue;
+
+ case EOL:
+ if (option != WhitespaceOption.SINGLE_LINE) {
+ builder.append(""\n"");
+ }
+
+ ignoreStar = true;
+ token = next();
+ continue;
+
+ case ANNOTATION:
+ case EOC:
+ case EOF:
+ // When we're capturing a license block, annotations
+ // in the block are ok.
+ String multilineText = builder.toString();
+
+ if (option != WhitespaceOption.PRESERVE) {
+ multilineText = multilineText.trim();
+ }
+
+ int endLineno = stream.getLineno();
+ int endCharno = stream.getCharno();
+
+ if (multilineText.length() > 0) {
+ jsdocBuilder.markText(multilineText, startLineno, startCharno,
+ endLineno, endCharno);
+ }
+
+ return new ExtractionInfo(multilineText, token);
+
+ // FALL THROUGH
+
+ default:
+ ignoreStar = false;
+ state = State.SEARCHING_ANNOTATION;
+
+ if (builder.length() > 0) {
+ builder.append(' ');
+ }
+
+ builder.append(toString(token));
+
+ line = stream.getRemainingJSDocLine();
+
+ if (option != WhitespaceOption.PRESERVE) {
+ line = trimEnd(line);
+ }
+
+ builder.append(line);
+ token = next();
+ }
+ } while (true);
+ }
+
+// Test Case
+[/INST]
+ public void testParameter4() {
+ // Make sure that we do not merge two-arg functions because of the
+ // IE sort bug (see comments in computeEscaped)
+ test(""function FUNC(x, y) {var a,b; y; a=0; a; x; b=0; b}"",
+ ""function FUNC(x, y) {var a; y; a=0; a; x; a=0; a}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void trySimplify(Node parent, Node node) {
+ if (node.getType() != Token.EXPR_RESULT) {
+ return;
+ }
+
+ Node exprBody = node.getFirstChild();
+ if (!NodeUtil.nodeTypeMayHaveSideEffects(exprBody)
+ ) {
+ changeProxy.replaceWith(parent, node, getSideEffectNodes(exprBody));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDefineFlag3() {
+ args.add(""--define=FOO=\""x'\"""");
+ test(""/** @define {string} */ var FOO = \""a\"";"",
+ ""var FOO = \""x'\"";"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @VisibleForTesting
+ static void createDefineReplacements(List definitions,
+ CompilerOptions options) {
+ // Parse the definitions
+ for (String override : definitions) {
+ String[] assignment = override.split(""="", 2);
+ String defName = assignment[0];
+
+ if (defName.length() > 0) {
+ if (assignment.length == 1) {
+ options.setDefineToBooleanLiteral(defName, true);
+ continue;
+ } else {
+ String defValue = assignment[1];
+
+ if (defValue.equals(""true"")) {
+ options.setDefineToBooleanLiteral(defName, true);
+ continue;
+ } else if (defValue.equals(""false"")) {
+ options.setDefineToBooleanLiteral(defName, false);
+ continue;
+ } else if (defValue.length() > 1
+ && ((defValue.charAt(0) == '\'' &&
+ defValue.charAt(defValue.length() - 1) == '\'')
+ )) {
+ // If the value starts and ends with a single quote,
+ // we assume that it's a string.
+ String maybeStringVal =
+ defValue.substring(1, defValue.length() - 1);
+ if (maybeStringVal.indexOf(defValue.charAt(0)) == -1) {
+ options.setDefineToStringLiteral(defName, maybeStringVal);
+ continue;
+ }
+ } else {
+ try {
+ options.setDefineToDoubleLiteral(defName,
+ Double.parseDouble(defValue));
+ continue;
+ } catch (NumberFormatException e) {
+ // do nothing, it will be caught at the end
+ }
+ }
+ }
+ }
+
+ throw new RuntimeException(
+ ""--define flag syntax invalid: "" + override);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDefineFlag3() {
+ args.add(""--define=FOO=\""x'\"""");
+ test(""/** @define {string} */ var FOO = \""a\"";"",
+ ""var FOO = \""x'\"";"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ FunctionTypeBuilder inferReturnType(@Nullable JSDocInfo info) {
+ returnType = info != null && info.hasReturnType() ?
+ info.getReturnType().evaluate(scope, typeRegistry) :
+ typeRegistry.getNativeType(UNKNOWN_TYPE);
+ if (templateTypeName != null &&
+ returnType.restrictByNotNullOrUndefined().isTemplateType()) {
+ reportError(TEMPLATE_TYPE_EXPECTED, fnName);
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeAnnotationsAssign() {
+ assertTypeAnnotations(""/** @constructor */ var Foo = function(){}"",
+ ""/**\n * @return {undefined}\n * @constructor\n */\n""
+ + ""var Foo = function() {\n}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ FunctionType buildAndRegister() {
+ if (returnType == null) {
+ returnType = typeRegistry.getNativeType(UNKNOWN_TYPE);
+ }
+
+ if (parametersNode == null) {
+ throw new IllegalStateException(
+ ""All Function types must have params and a return type"");
+ }
+
+ FunctionType fnType;
+ if (isConstructor) {
+ fnType = getOrCreateConstructor();
+ } else if (isInterface) {
+ fnType = typeRegistry.createInterfaceType(fnName, sourceNode);
+ if (scope.isGlobal() && !fnName.isEmpty()) {
+ typeRegistry.declareType(fnName, fnType.getInstanceType());
+ }
+ maybeSetBaseType(fnType);
+ } else {
+ fnType = new FunctionBuilder(typeRegistry)
+ .withName(fnName)
+ .withSourceNode(sourceNode)
+ .withParamsNode(parametersNode)
+ .withReturnType(returnType)
+ .withTypeOfThis(thisType)
+ .withTemplateName(templateTypeName)
+ .build();
+ maybeSetBaseType(fnType);
+ }
+
+ if (implementedInterfaces != null) {
+ fnType.setImplementedInterfaces(implementedInterfaces);
+ }
+
+ typeRegistry.clearTemplateTypeName();
+
+ return fnType;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeAnnotationsAssign() {
+ assertTypeAnnotations(""/** @constructor */ var Foo = function(){}"",
+ ""/**\n * @return {undefined}\n * @constructor\n */\n""
+ + ""var Foo = function() {\n}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ FunctionType cloneWithNewReturnType(JSType newReturnType, boolean inferred) {
+ return new FunctionType(
+ registry, null, null,
+ new ArrowType(
+ registry, call.parameters, newReturnType, inferred),
+ typeOfThis, null, false, false);
+ }
+
+// Test Case
+[/INST]
+ public void testTypeAnnotationsAssign() {
+ assertTypeAnnotations(""/** @constructor */ var Foo = function(){}"",
+ ""/**\n * @return {undefined}\n * @constructor\n */\n""
+ + ""var Foo = function() {\n}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FunctionType getFunctionType(String name,
+ Node rValue, JSDocInfo info, @Nullable Node lvalueNode) {
+ FunctionType functionType = null;
+
+ // Handle function aliases.
+ if (rValue != null && rValue.isQualifiedName()) {
+ Var var = scope.getVar(rValue.getQualifiedName());
+ if (var != null && var.getType() instanceof FunctionType) {
+ functionType = (FunctionType) var.getType();
+ if (functionType != null && functionType.isConstructor()) {
+ typeRegistry.declareType(name, functionType.getInstanceType());
+ }
+ }
+ return functionType;
+ }
+
+ Node owner = null;
+ if (lvalueNode != null) {
+ owner = getPrototypePropertyOwner(lvalueNode);
+ }
+
+ Node errorRoot = rValue == null ? lvalueNode : rValue;
+ boolean isFnLiteral =
+ rValue != null && rValue.getType() == Token.FUNCTION;
+ Node fnRoot = isFnLiteral ? rValue : null;
+ Node parametersNode = isFnLiteral ?
+ rValue.getFirstChild().getNext() : null;
+
+ if (functionType == null && info != null && info.hasType()) {
+ JSType type = info.getType().evaluate(scope, typeRegistry);
+
+ // Known to be not null since we have the FUNCTION token there.
+ type = type.restrictByNotNullOrUndefined();
+ if (type.isFunctionType()) {
+ functionType = (FunctionType) type;
+ functionType.setJSDocInfo(info);
+ }
+ }
+
+ if (functionType == null) {
+ if (info == null ||
+ !FunctionTypeBuilder.isFunctionTypeDeclaration(info)) {
+ // We don't really have any type information in the annotation.
+ // Before we give up on this function, look at the object we're
+ // assigning it to. For example, if the function looks like this:
+ // SubFoo.prototype.bar = function() { ... };
+ // We can use type information on Foo.prototype.bar and apply it
+ // to this function.
+ if (lvalueNode != null && lvalueNode.getType() == Token.GETPROP &&
+ lvalueNode.isQualifiedName()) {
+ Var var = scope.getVar(
+ lvalueNode.getFirstChild().getQualifiedName());
+ if (var != null) {
+ ObjectType ownerType = ObjectType.cast(var.getType());
+ FunctionType propType = null;
+ if (ownerType != null) {
+ String propName = lvalueNode.getLastChild().getString();
+ propType = findOverriddenFunction(ownerType, propName);
+ }
+
+ if (propType != null) {
+ functionType =
+ new FunctionTypeBuilder(
+ name, compiler, errorRoot, sourceName, scope)
+ .setSourceNode(fnRoot)
+ .inferFromOverriddenFunction(propType, parametersNode)
+ .inferThisType(info, owner)
+ .buildAndRegister();
+ }
+ }
+ }
+ }
+ } // end if (functionType == null)
+
+ if (functionType == null) {
+ functionType =
+ new FunctionTypeBuilder(name, compiler, errorRoot, sourceName,
+ scope)
+ .setSourceNode(fnRoot)
+ .inferTemplateTypeName(info)
+ .inferReturnType(info)
+ .inferInheritance(info)
+ .inferThisType(info, owner)
+ .inferParameterTypes(parametersNode, info)
+ .buildAndRegister();
+ }
+
+ // assigning the function type to the function node
+ if (rValue != null) {
+ setDeferredType(rValue, functionType);
+ }
+
+ // all done
+ return functionType;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeAnnotationsAssign() {
+ assertTypeAnnotations(""/** @constructor */ var Foo = function(){}"",
+ ""/**\n * @return {undefined}\n * @constructor\n */\n""
+ + ""var Foo = function() {\n}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testTypeAnnotationsAssign() {
+ assertTypeAnnotations(""/** @constructor */ var Foo = function(){}"",
+ ""/**\n * @return {undefined}\n * @constructor\n */\n""
+ + ""var Foo = function() {\n}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isOneExactlyFunctionOrDo(Node n) {
+ // For labels with block children, we need to ensure that a
+ // labeled FUNCTION or DO isn't generated when extraneous BLOCKs
+ // are skipped.
+ // Either a empty statement or an block with more than one child,
+ // way it isn't a FUNCTION or DO.
+ return (n.getType() == Token.FUNCTION || n.getType() == Token.DO);
+ }
+
+// Test Case
+[/INST]
+ public void testFunctionSafariCompatiblity() {
+ // Functions within IFs cause syntax errors on Safari.
+ assertPrint(""function(){if(e1){function goo(){return true}}else foo()}"",
+ ""function(){if(e1){function goo(){return true}}else foo()}"");
+
+ assertPrint(""function(){if(e1)function goo(){return true}else foo()}"",
+ ""function(){if(e1){function goo(){return true}}else foo()}"");
+
+ assertPrint(""if(e1){function goo(){return true}}"",
+ ""if(e1){function goo(){return true}}"");
+
+ assertPrint(""if(e1)function goo(){return true}"",
+ ""if(e1){function goo(){return true}}"");
+
+ assertPrint(""if(e1)A:function goo(){return true}"",
+ ""if(e1){A:function goo(){return true}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public TypePair getTypesUnderInequality(JSType that) {
+ // unions types
+ if (that instanceof UnionType) {
+ TypePair p = that.getTypesUnderInequality(this);
+ return new TypePair(p.typeB, p.typeA);
+ }
+
+ // other types
+ switch (this.testForEquality(that)) {
+ case TRUE:
+ return new TypePair(null, null);
+
+ case FALSE:
+ case UNKNOWN:
+ return new TypePair(this, that);
+ }
+
+ // switch case is exhaustive
+ throw new IllegalStateException();
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""unchecked"")
+ public void testEqCondition4() throws Exception {
+ FlowScope blind = newScope();
+ testBinop(blind,
+ Token.EQ,
+ createVar(blind, ""a"", VOID_TYPE),
+ createVar(blind, ""b"", VOID_TYPE),
+ Sets.newHashSet(
+ new TypedName(""a"", VOID_TYPE),
+ new TypedName(""b"", VOID_TYPE)),
+ Sets.newHashSet(
+ new TypedName(""a"", NO_TYPE),
+ new TypedName(""b"", NO_TYPE)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
+
+ if (n.getType() == Token.FUNCTION) {
+ // Don't traverse functions that are constructors or have the @this
+ // or @override annotation.
+ JSDocInfo jsDoc = getFunctionJsDocInfo(n);
+ if (jsDoc != null &&
+ (jsDoc.isConstructor() ||
+ jsDoc.isInterface() ||
+ jsDoc.hasThisType() ||
+ jsDoc.isOverride())) {
+ return false;
+ }
+
+ // Don't traverse functions unless they would normally
+ // be able to have a @this annotation associated with them. e.g.,
+ // var a = function() { }; // or
+ // function a() {} // or
+ // a.x = function() {}; // or
+ // var a = {x: function() {}};
+ int pType = parent.getType();
+ if (!(pType == Token.BLOCK ||
+ pType == Token.SCRIPT ||
+ pType == Token.NAME ||
+ pType == Token.ASSIGN)) {
+ return false;
+ }
+ }
+
+ if (parent != null && parent.getType() == Token.ASSIGN) {
+ Node lhs = parent.getFirstChild();
+ Node rhs = lhs.getNext();
+
+ if (n == lhs) {
+ // Always traverse the left side of the assignment. To handle
+ // nested assignments properly (e.g., (a = this).property = c;),
+ // assignLhsChild should not be overridden.
+ if (assignLhsChild == null) {
+ assignLhsChild = lhs;
+ }
+ } else {
+ // Only traverse the right side if it's not an assignment to a prototype
+ // property or subproperty.
+ if (NodeUtil.isGet(lhs)) {
+ if (lhs.getType() == Token.GETPROP &&
+ lhs.getLastChild().getString().equals(""prototype"")) {
+ return false;
+ }
+ Node llhs = lhs.getFirstChild();
+ if (llhs.getType() == Token.GETPROP &&
+ llhs.getLastChild().getString().equals(""prototype"")) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue182a() {
+ testFailure(""var NS = {read: function() { return this.foo; }};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitFunction(NodeTraversal t, Node n) {
+ FunctionType funType = (FunctionType) n.getJSType();
+ Node block = n.getLastChild();
+ Node paramName = NodeUtil.getFnParameters(n).getFirstChild();
+ Node insertionPoint = null;
+
+ // To satisfy normalization constraints, the type checking must be
+ // added after any inner function declarations.
+
+ for (Node paramType : funType.getParameters()) {
+ // Can this ever happen?
+ if (paramName == null) {
+ return;
+ }
+
+ Node checkNode = createCheckTypeCallNode(
+ paramType.getJSType(), paramName.cloneTree());
+
+ if (checkNode == null) {
+ // We don't know how to check this parameter type.
+ paramName = paramName.getNext();
+ continue;
+ }
+
+ checkNode = new Node(Token.EXPR_RESULT, checkNode);
+ if (insertionPoint == null) {
+ block.addChildToFront(checkNode);
+ } else {
+ block.addChildAfter(checkNode, insertionPoint);
+ }
+
+ compiler.reportCodeChange();
+ paramName = paramName.getNext();
+ insertionPoint = checkNode;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue182a() {
+ testFailure(""var NS = {read: function() { return this.foo; }};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void appendTo(Appendable out) throws IOException {
+ out.append(""["");
+
+ out.append(sourceFile);
+ // The source file rarely changes, so cache the escaped string.
+
+ out.append("","");
+
+
+ out.append(String.valueOf(originalPosition.getLineNumber()));
+
+ out.append("","");
+ out.append(String.valueOf(originalPosition.getCharacterIndex()));
+
+ if (originalName != null) {
+ out.append("","");
+ out.append(originalName);
+ }
+
+ out.append(""]"");
+ }
+
+// Test Case
+[/INST]
+ public void testFoldTypeof() {
+ fold(""x = typeof 1"", ""x = \""number\"""");
+ fold(""x = typeof 'foo'"", ""x = \""string\"""");
+ fold(""x = typeof true"", ""x = \""boolean\"""");
+ fold(""x = typeof false"", ""x = \""boolean\"""");
+ fold(""x = typeof null"", ""x = \""object\"""");
+ fold(""x = typeof undefined"", ""x = \""undefined\"""");
+ fold(""x = typeof void 0"", ""x = \""undefined\"""");
+ fold(""x = typeof []"", ""x = \""object\"""");
+ fold(""x = typeof [1]"", ""x = \""object\"""");
+ fold(""x = typeof [1,[]]"", ""x = \""object\"""");
+ fold(""x = typeof {}"", ""x = \""object\"""");
+
+ foldSame(""x = typeof[1,[foo()]]"");
+ foldSame(""x = typeof{bathwater:baby()}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void addMapping(Node node, Position startPosition, Position endPosition) {
+ String sourceFile = (String)node.getProp(Node.SOURCEFILE_PROP);
+
+ // If the node does not have an associated source file or
+ // its line number is -1, then the node does not have sufficient
+ // information for a mapping to be useful.
+ if (sourceFile == null || node.getLineno() < 0) {
+ return;
+ }
+
+ String escapedSourceFile;
+ if (lastSourceFile != sourceFile) { // yes, ""s1 != s2"" not ""!s1.equals(s2)""
+ lastSourceFile = sourceFile;
+ lastSourceFileEscaped = escapeString(sourceFile);
+ }
+ escapedSourceFile = lastSourceFileEscaped;
+ // Create the new mapping.
+ Mapping mapping = new Mapping();
+ mapping.id = mappings.size();
+ mapping.sourceFile = escapedSourceFile;
+ mapping.originalPosition = new Position(node.getLineno(), node.getCharno());
+
+ String originalName = (String)node.getProp(Node.ORIGINALNAME_PROP);
+ if (originalName != null) {
+ mapping.originalName = escapeString(originalName);
+ }
+
+ // If the mapping is found on the first line, we need to offset
+ // its character position by the number of characters found on
+ // the *last* line of the source file to which the code is
+ // being generated.
+ int offsetLine = offsetPosition.getLineNumber();
+ int startOffsetPosition = offsetPosition.getCharacterIndex();
+ int endOffsetPosition = offsetPosition.getCharacterIndex();
+
+ if (startPosition.getLineNumber() > 0) {
+ startOffsetPosition = 0;
+ }
+
+ if (endPosition.getLineNumber() > 0) {
+ endOffsetPosition = 0;
+ }
+
+ mapping.startPosition =
+ new Position(startPosition.getLineNumber() + offsetLine,
+ startPosition.getCharacterIndex() + startOffsetPosition);
+
+ mapping.endPosition =
+ new Position(endPosition.getLineNumber() + offsetLine,
+ endPosition.getCharacterIndex() + endOffsetPosition);
+
+ mappings.add(mapping);
+ }
+
+// Test Case
+[/INST]
+ public void testFoldTypeof() {
+ fold(""x = typeof 1"", ""x = \""number\"""");
+ fold(""x = typeof 'foo'"", ""x = \""string\"""");
+ fold(""x = typeof true"", ""x = \""boolean\"""");
+ fold(""x = typeof false"", ""x = \""boolean\"""");
+ fold(""x = typeof null"", ""x = \""object\"""");
+ fold(""x = typeof undefined"", ""x = \""undefined\"""");
+ fold(""x = typeof void 0"", ""x = \""undefined\"""");
+ fold(""x = typeof []"", ""x = \""object\"""");
+ fold(""x = typeof [1]"", ""x = \""object\"""");
+ fold(""x = typeof [1,[]]"", ""x = \""object\"""");
+ fold(""x = typeof {}"", ""x = \""object\"""");
+
+ foldSame(""x = typeof[1,[foo()]]"");
+ foldSame(""x = typeof{bathwater:baby()}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryFoldTypeof(Node originalTypeofNode) {
+ Preconditions.checkArgument(originalTypeofNode.getType() == Token.TYPEOF);
+
+ Node argumentNode = originalTypeofNode.getFirstChild();
+ if (argumentNode == null || !NodeUtil.isLiteralValue(argumentNode)) {
+ return originalTypeofNode;
+ }
+
+ String typeNameString = null;
+
+ switch (argumentNode.getType()) {
+ case Token.STRING:
+ typeNameString = ""string"";
+ break;
+ case Token.NUMBER:
+ typeNameString = ""number"";
+ break;
+ case Token.TRUE:
+ case Token.FALSE:
+ typeNameString = ""boolean"";
+ break;
+ case Token.NULL:
+ case Token.OBJECTLIT:
+ case Token.ARRAYLIT:
+ typeNameString = ""object"";
+ break;
+ case Token.NAME:
+ // We assume here that programs don't change the value of the
+ // keyword undefined to something other than the value undefined.
+ if (""undefined"".equals(argumentNode.getString())) {
+ typeNameString = ""undefined"";
+ }
+ break;
+ }
+
+ if (typeNameString != null) {
+ Node newNode = Node.newString(typeNameString);
+ originalTypeofNode.getParent().replaceChild(originalTypeofNode, newNode);
+ reportCodeChange();
+
+ return newNode;
+ }
+
+ return originalTypeofNode;
+ }
+
+// Test Case
+[/INST]
+ public void testFoldTypeof() {
+ fold(""x = typeof 1"", ""x = \""number\"""");
+ fold(""x = typeof 'foo'"", ""x = \""string\"""");
+ fold(""x = typeof true"", ""x = \""boolean\"""");
+ fold(""x = typeof false"", ""x = \""boolean\"""");
+ fold(""x = typeof null"", ""x = \""object\"""");
+ fold(""x = typeof undefined"", ""x = \""undefined\"""");
+ fold(""x = typeof void 0"", ""x = \""undefined\"""");
+ fold(""x = typeof []"", ""x = \""object\"""");
+ fold(""x = typeof [1]"", ""x = \""object\"""");
+ fold(""x = typeof [1,[]]"", ""x = \""object\"""");
+ fold(""x = typeof {}"", ""x = \""object\"""");
+
+ foldSame(""x = typeof[1,[foo()]]"");
+ foldSame(""x = typeof{bathwater:baby()}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void appendTo(Appendable out, String name) throws IOException {
+ // Write the mappings out to the file. The format of the generated
+ // source map is three sections, each deliminated by a magic comment.
+ //
+ // The first section contains an array for each line of the generated
+ // code, where each element in the array is the ID of the mapping which
+ // best represents the index-th character found on that line of the
+ // generated source code.
+ //
+ // The second section contains an array per generated line. Unused.
+ //
+ // The third and final section contains an array per line, each of which
+ // represents a mapping with a unique ID. The mappings are added in order.
+ // The array itself contains a tuple representing
+ // ['source file', line, col (, 'original name')]
+ //
+ // Example for 2 lines of generated code (with line numbers added for
+ // readability):
+ //
+ // 1) /** Begin line maps. **/{ ""count"": 2 }
+ // 2) [0,0,0,0,0,0,1,1,1,1,2]
+ // 3) [2,2,2,2,2,2,3,4,4,4,4,4]
+ // 4) /** Begin file information. **/
+ // 5) []
+ // 6) []
+ // 7) /** Begin mapping definitions. **/
+ // 8) [""a.js"", 1, 34]
+ // 9) [""a.js"", 5, 2]
+ // 10) [""b.js"", 1, 3, ""event""]
+ // 11) [""c.js"", 1, 4]
+ // 12) [""d.js"", 3, 78, ""foo""]
+
+ int maxLine = findLastLine();
+
+ // Add the line character maps.
+ out.append(""/** Begin line maps. **/{ \""file\"" : "");
+ out.append(escapeString(name));
+ out.append("", \""count\"": "");
+ out.append(String.valueOf(maxLine + 1));
+ out.append("" }\n"");
+ (new LineMapper(out)).appendLineMappings();
+
+ // Add the source file maps.
+ out.append(""/** Begin file information. **/\n"");
+
+ // This section is unused but we need one entry per line to
+ // prevent changing the format.
+ for (int i = 0; i <= maxLine; ++i) {
+ out.append(""[]\n"");
+ }
+
+ // Add the mappings themselves.
+ out.append(""/** Begin mapping definitions. **/\n"");
+
+ for (Mapping mapping : mappings) {
+ mapping.appendTo(out);
+ out.append(""\n"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testFoldTypeof() {
+ fold(""x = typeof 1"", ""x = \""number\"""");
+ fold(""x = typeof 'foo'"", ""x = \""string\"""");
+ fold(""x = typeof true"", ""x = \""boolean\"""");
+ fold(""x = typeof false"", ""x = \""boolean\"""");
+ fold(""x = typeof null"", ""x = \""object\"""");
+ fold(""x = typeof undefined"", ""x = \""undefined\"""");
+ fold(""x = typeof void 0"", ""x = \""undefined\"""");
+ fold(""x = typeof []"", ""x = \""object\"""");
+ fold(""x = typeof [1]"", ""x = \""object\"""");
+ fold(""x = typeof [1,[]]"", ""x = \""object\"""");
+ fold(""x = typeof {}"", ""x = \""object\"""");
+
+ foldSame(""x = typeof[1,[foo()]]"");
+ foldSame(""x = typeof{bathwater:baby()}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ final protected void setRunOptions(CompilerOptions options)
+ throws FlagUsageException, IOException {
+ DiagnosticGroups diagnosticGroups = getDiagnosticGroups();
+
+ diagnosticGroups.setWarningLevels(
+ options, config.jscompError, CheckLevel.ERROR);
+ diagnosticGroups.setWarningLevels(
+ options, config.jscompWarning, CheckLevel.WARNING);
+ diagnosticGroups.setWarningLevels(
+ options, config.jscompOff, CheckLevel.OFF);
+
+ createDefineReplacements(config.define, options);
+
+ options.manageClosureDependencies = config.manageClosureDependencies;
+ options.devMode = config.jscompDevMode;
+ options.setCodingConvention(config.codingConvention);
+ options.setSummaryDetailLevel(config.summaryDetailLevel);
+
+ inputCharset = getInputCharset();
+
+ if (config.jsOutputFile.length() > 0) {
+ options.jsOutputFile = config.jsOutputFile;
+ }
+
+ if (config.createSourceMap.length() > 0) {
+ options.sourceMapOutputPath = config.createSourceMap;
+ }
+ options.sourceMapDetailLevel = config.sourceMapDetailLevel;
+
+ if (!config.variableMapInputFile.equals("""")) {
+ options.inputVariableMapSerialized =
+ VariableMap.load(config.variableMapInputFile).toBytes();
+ }
+
+ if (!config.propertyMapInputFile.equals("""")) {
+ options.inputPropertyMapSerialized =
+ VariableMap.load(config.propertyMapInputFile).toBytes();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testCharSetExpansion() {
+ testSame("""");
+ assertEquals(""US-ASCII"", lastCompiler.getOptions().outputCharset);
+ args.add(""--charset=UTF-8"");
+ testSame("""");
+ assertEquals(""UTF-8"", lastCompiler.getOptions().outputCharset);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ 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;
+ }
+
+// Test Case
+[/INST]
+ public void testCharSetExpansion() {
+ testSame("""");
+ assertEquals(""US-ASCII"", lastCompiler.getOptions().outputCharset);
+ args.add(""--charset=UTF-8"");
+ testSame("""");
+ assertEquals(""UTF-8"", lastCompiler.getOptions().outputCharset);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected int doRun() throws FlagUsageException, IOException {
+ Compiler.setLoggingLevel(Level.parse(config.loggingLevel));
+
+ List externsList = createExterns();
+ JSSourceFile[] externs = new JSSourceFile[externsList.size()];
+ externsList.toArray(externs);
+
+ compiler = createCompiler();
+ B options = createOptions();
+
+ JSModule[] modules = null;
+ Result result;
+
+ setRunOptions(options);
+ if (inputCharset == Charsets.UTF_8) {
+ options.outputCharset = Charsets.US_ASCII;
+ } else {
+ options.outputCharset = inputCharset;
+ }
+
+ boolean writeOutputToFile = !options.jsOutputFile.isEmpty();
+ if (writeOutputToFile) {
+ out = toWriter(options.jsOutputFile, inputCharset.name());
+ }
+
+ List jsFiles = config.js;
+ List moduleSpecs = config.module;
+ if (!moduleSpecs.isEmpty()) {
+ modules = createJsModules(moduleSpecs, jsFiles);
+ result = compiler.compile(externs, modules, options);
+ } else {
+ List inputList = createSourceInputs(jsFiles);
+ JSSourceFile[] inputs = new JSSourceFile[inputList.size()];
+ inputList.toArray(inputs);
+ result = compiler.compile(externs, inputs, options);
+ }
+
+ int errCode = processResults(result, modules, options);
+ // Close the output if we are writing to a file.
+ if (writeOutputToFile) {
+ ((Writer)out).close();
+ }
+ return errCode;
+ }
+
+// Test Case
+[/INST]
+ public void testCharSetExpansion() {
+ testSame("""");
+ assertEquals(""US-ASCII"", lastCompiler.getOptions().outputCharset);
+ args.add(""--charset=UTF-8"");
+ testSame("""");
+ assertEquals(""UTF-8"", lastCompiler.getOptions().outputCharset);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private String toSource(Node n, SourceMap sourceMap) {
+ CodePrinter.Builder builder = new CodePrinter.Builder(n);
+ builder.setPrettyPrint(options.prettyPrint);
+ builder.setLineBreak(options.lineBreak);
+ builder.setSourceMap(sourceMap);
+ builder.setSourceMapDetailLevel(options.sourceMapDetailLevel);
+
+ Charset charset = options.outputCharset;
+ builder.setOutputCharset(charset);
+
+ return builder.build();
+ }
+
+// Test Case
+[/INST]
+ public void testCharSetExpansion() {
+ testSame("""");
+ assertEquals(""US-ASCII"", lastCompiler.getOptions().outputCharset);
+ args.add(""--charset=UTF-8"");
+ testSame("""");
+ assertEquals(""UTF-8"", lastCompiler.getOptions().outputCharset);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testCharSetExpansion() {
+ testSame("""");
+ assertEquals(""US-ASCII"", lastCompiler.getOptions().outputCharset);
+ args.add(""--charset=UTF-8"");
+ testSame("""");
+ assertEquals(""UTF-8"", lastCompiler.getOptions().outputCharset);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean apply(Node n) {
+ // When the node is null it means, we reached the implicit return
+ // where the function returns (possibly without an return statement)
+ if (n == null) {
+ return false;
+ }
+
+ // TODO(user): We only care about calls to functions that
+ // passes one of the dependent variable to a non-side-effect free
+ // function.
+ if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {
+ return true;
+ }
+
+ if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {
+ return true;
+ }
+
+
+ for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
+ if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleForIn() {
+ inline(""var a,b,x = a in b; x"",
+ ""var a,b,x; a in b"");
+ noInline(""var a, b; var x = a in b; print(1); x"");
+ noInline(""var a,b,x = a in b; delete a[b]; x"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override public void visit(NodeTraversal t, Node n, Node parent) {
+ if (n == scope.getRootNode()) return;
+
+ if (n.getType() == Token.LP && parent == scope.getRootNode()) {
+ handleFunctionInputs(parent);
+ return;
+ }
+
+ attachLiteralTypes(n);
+ switch (n.getType()) {
+ case Token.FUNCTION:
+ if (parent.getType() == Token.NAME) {
+ return;
+ }
+ defineDeclaredFunction(n, parent);
+ break;
+ case Token.CATCH:
+ defineCatch(n, parent);
+ break;
+ case Token.VAR:
+ defineVar(n, parent);
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNamespacedFunctionStubLocal() {
+ testSame(
+ ""(function() {"" +
+ ""var goog = {};"" +
+ ""/** @param {number} x */ goog.foo;"" +
+ ""});"");
+
+ ObjectType goog = (ObjectType) findNameType(""goog"", lastLocalScope);
+ assertTrue(goog.hasProperty(""foo""));
+ assertEquals(""function (number): ?"",
+ goog.getPropertyType(""foo"").toString());
+ assertTrue(goog.isPropertyTypeDeclared(""foo""));
+
+ assertEquals(lastLocalScope.getVar(""goog.foo"").getType(),
+ goog.getPropertyType(""foo""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void initConfigFromFlags(String[] args, PrintStream err) {
+ // Args4j has a different format that the old command-line parser.
+ // So we use some voodoo to get the args into the format that args4j
+ // expects.
+ Pattern argPattern = Pattern.compile(""(--[a-zA-Z_]+)=(.*)"");
+ Pattern quotesPattern = Pattern.compile(""^['\""](.*)['\""]$"");
+ List processedArgs = Lists.newArrayList();
+ for (String arg : args) {
+ Matcher matcher = argPattern.matcher(arg);
+ if (matcher.matches()) {
+ processedArgs.add(matcher.group(1));
+
+ String value = matcher.group(2);
+ Matcher quotesMatcher = quotesPattern.matcher(value);
+ if (quotesMatcher.matches()) {
+ processedArgs.add(quotesMatcher.group(1));
+ } else {
+ processedArgs.add(value);
+ }
+ } else {
+ processedArgs.add(arg);
+ }
+ }
+
+ CmdLineParser parser = new CmdLineParser(flags);
+ isConfigValid = true;
+ try {
+ parser.parseArgument(processedArgs.toArray(new String[] {}));
+ } catch (CmdLineException e) {
+ err.println(e.getMessage());
+ isConfigValid = false;
+ }
+
+
+ if (!isConfigValid || flags.display_help) {
+ isConfigValid = false;
+ parser.printUsage(err);
+ } else {
+ getCommandLineConfig()
+ .setPrintTree(flags.print_tree)
+ .setComputePhaseOrdering(flags.compute_phase_ordering)
+ .setPrintAst(flags.print_ast)
+ .setPrintPassGraph(flags.print_pass_graph)
+ .setJscompDevMode(flags.jscomp_dev_mode)
+ .setLoggingLevel(flags.logging_level)
+ .setExterns(flags.externs)
+ .setJs(flags.js)
+ .setJsOutputFile(flags.js_output_file)
+ .setModule(flags.module)
+ .setVariableMapInputFile(flags.variable_map_input_file)
+ .setPropertyMapInputFile(flags.property_map_input_file)
+ .setVariableMapOutputFile(flags.variable_map_output_file)
+ .setCreateNameMapFiles(flags.create_name_map_files)
+ .setPropertyMapOutputFile(flags.property_map_output_file)
+ .setCodingConvention(flags.third_party ?
+ new DefaultCodingConvention() :
+ new ClosureCodingConvention())
+ .setSummaryDetailLevel(flags.summary_detail_level)
+ .setOutputWrapper(flags.output_wrapper)
+ .setOutputWrapperMarker(flags.output_wrapper_marker)
+ .setModuleWrapper(flags.module_wrapper)
+ .setModuleOutputPathPrefix(flags.module_output_path_prefix)
+ .setCreateSourceMap(flags.create_source_map)
+ .setJscompError(flags.jscomp_error)
+ .setJscompWarning(flags.jscomp_warning)
+ .setJscompOff(flags.jscomp_off)
+ .setDefine(flags.define)
+ .setCharset(flags.charset)
+ .setManageClosureDependencies(flags.manage_closure_dependencies)
+ .setOutputManifest(flags.output_manifest);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testVersionFlag() {
+ args.add(""--version"");
+ testSame("""");
+ assertEquals(
+ 0,
+ new String(errReader.toByteArray()).indexOf(
+ ""Closure Compiler (http://code.google.com/p/closure/compiler)\n"" +
+ ""Version: HEAD\n"" +
+ ""Built on:""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ JSType resolveInternal(ErrorReporter t, StaticScope scope) {
+ setResolvedTypeInternal(this);
+
+ call = (ArrowType) safeResolve(call, t, scope);
+ prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope);
+
+ // Warning about typeOfThis if it doesn't resolve to an ObjectType
+ // is handled further upstream.
+ // TODO(nicksantos): Handle this correctly if we have a UnionType.
+ typeOfThis = (ObjectType) safeResolve(typeOfThis, t, scope);
+
+ boolean changed = false;
+ ImmutableList.Builder resolvedInterfaces =
+ ImmutableList.builder();
+ for (ObjectType iface : implementedInterfaces) {
+ ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope);
+ resolvedInterfaces.add(resolvedIface);
+ changed |= (resolvedIface != iface);
+ }
+ if (changed) {
+ implementedInterfaces = resolvedInterfaces.build();
+ }
+
+ if (subTypes != null) {
+ for (int i = 0; i < subTypes.size(); i++) {
+ subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope));
+ }
+ }
+
+ return super.resolveInternal(t, scope);
+ }
+
+// Test Case
+[/INST]
+ public void testBackwardsTypedefUse1() throws Exception {
+ testTypes(
+ ""/** @this {MyTypedef} */ function f() {}"" +
+ ""/** @typedef {string} */ var MyTypedef;"",
+ ""@this type of a function must be an object\n"" +
+ ""Actual type: string"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void scanRoot(Node n, Scope parent) {
+ if (n.getType() == Token.FUNCTION) {
+ sourceName = (String) n.getProp(Node.SOURCENAME_PROP);
+
+ final Node fnNameNode = n.getFirstChild();
+ final Node args = fnNameNode.getNext();
+ final Node body = args.getNext();
+
+ // Bleed the function name into the scope, if it hasn't
+ // been declared in the outer scope.
+ String fnName = fnNameNode.getString();
+ if (!fnName.isEmpty() && NodeUtil.isFunctionExpression(n)) {
+ declareVar(fnName, fnNameNode, n, null, null, n);
+ }
+
+ // Args: Declare function variables
+ Preconditions.checkState(args.getType() == Token.LP);
+ for (Node a = args.getFirstChild(); a != null;
+ a = a.getNext()) {
+ Preconditions.checkState(a.getType() == Token.NAME);
+ declareVar(a.getString(), a, args, n, null, n);
+ }
+
+ // Body
+ scanVars(body, n);
+ } else {
+ // It's the global block
+ Preconditions.checkState(scope.getParent() == null);
+ scanVars(n, null);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDuplicateVarInExterns() {
+ test(""var extern;"",
+ ""/** @suppress {duplicate} */ var extern = 3;"", ""var extern = 3;"",
+ null, null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void scanVars(Node n, Node parent) {
+ switch (n.getType()) {
+ case Token.VAR:
+ // Declare all variables. e.g. var x = 1, y, z;
+ for (Node child = n.getFirstChild();
+ child != null;) {
+ Node next = child.getNext();
+ Preconditions.checkState(child.getType() == Token.NAME);
+ String name = child.getString();
+ declareVar(name, child, n, parent, null, n);
+ child = next;
+ }
+ return;
+
+ case Token.FUNCTION:
+ if (NodeUtil.isFunctionExpression(n)) {
+ return;
+ }
+
+ String fnName = n.getFirstChild().getString();
+ if (fnName.isEmpty()) {
+ // This is invalid, but allow it so the checks can catch it.
+ return;
+ }
+ declareVar(fnName, n.getFirstChild(), n, parent, null, n);
+ return; // should not examine function's children
+
+ case Token.CATCH:
+ Preconditions.checkState(n.getChildCount() == 2);
+ Preconditions.checkState(n.getFirstChild().getType() == Token.NAME);
+ // the first child is the catch var and the third child
+ // is the code block
+
+ final Node var = n.getFirstChild();
+ final Node block = var.getNext();
+
+ declareVar(var.getString(), var, n, parent, null, n);
+ scanVars(block, n);
+ return; // only one child to scan
+
+ case Token.SCRIPT:
+ sourceName = (String) n.getProp(Node.SOURCENAME_PROP);
+ break;
+ }
+
+ // Variables can only occur in statement-level nodes, so
+ // we only need to traverse children in a couple special cases.
+ if (NodeUtil.isControlStructure(n) || NodeUtil.isStatementBlock(n)) {
+ for (Node child = n.getFirstChild();
+ child != null;) {
+ Node next = child.getNext();
+ scanVars(child, n);
+ child = next;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDuplicateVarInExterns() {
+ test(""var extern;"",
+ ""/** @suppress {duplicate} */ var extern = 3;"", ""var extern = 3;"",
+ null, null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void onRedeclaration(
+ Scope s, String name,
+ Node n, Node parent, Node gramps, Node nodeWithLineNumber);
+
+// Test Case
+[/INST]
+ public void testDuplicateVarInExterns() {
+ test(""var extern;"",
+ ""/** @suppress {duplicate} */ var extern = 3;"", ""var extern = 3;"",
+ null, null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void onRedeclaration(
+ Scope s, String name,
+ Node n, Node parent, Node gramps, Node nodeWithLineNumber) {
+
+ // Don't allow multiple variables to be declared at the top level scope
+ if (scope.isGlobal()) {
+ Scope.Var origVar = scope.getVar(name);
+ Node origParent = origVar.getParentNode();
+ if (origParent.getType() == Token.CATCH &&
+ parent.getType() == Token.CATCH) {
+ // Okay, both are 'catch(x)' variables.
+ return;
+ }
+
+ boolean allowDupe = false;
+ JSDocInfo info = n.getJSDocInfo();
+ if (info == null) {
+ info = parent.getJSDocInfo();
+ }
+ allowDupe =
+ info != null && info.getSuppressions().contains(""duplicate"");
+
+ if (!allowDupe) {
+ compiler.report(
+ JSError.make(sourceName, n,
+ VAR_MULTIPLY_DECLARED_ERROR,
+ name,
+ (origVar.input != null
+ ? origVar.input.getName()
+ : ""??"")));
+ }
+ } else if (name.equals(ARGUMENTS) && !NodeUtil.isVarDeclaration(n)) {
+ // Disallow shadowing ""arguments"" as we can't handle with our current
+ // scope modeling.
+ compiler.report(
+ JSError.make(sourceName, n,
+ VAR_ARGUMENTS_SHADOWED_ERROR));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDuplicateVarInExterns() {
+ test(""var extern;"",
+ ""/** @suppress {duplicate} */ var extern = 3;"", ""var extern = 3;"",
+ null, null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void declareVar(String name, Node n, Node parent,
+ Node gramps, JSType declaredType,
+ Node nodeWithLineNumber) {
+
+ if (scope.isDeclared(name, false)
+ || (scope.isLocal() && name.equals(ARGUMENTS))) {
+ redeclarationHandler.onRedeclaration(
+ scope, name, n, parent, gramps, nodeWithLineNumber);
+ } else {
+ scope.declare(name, n, declaredType, compiler.getInput(sourceName));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDuplicateVarInExterns() {
+ test(""var extern;"",
+ ""/** @suppress {duplicate} */ var extern = 3;"", ""var extern = 3;"",
+ null, null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void onRedeclaration(
+ Scope s, String name, Node n, Node parent, Node gramps,
+ Node nodeWithLineNumber) {
+ Preconditions.checkState(n.getType() == Token.NAME);
+ Var v = s.getVar(name);
+
+ // We allow variables to be duplicate declared if one
+ // declaration appears in source and the other in externs.
+ // This deals with issues where a browser built-in is declared
+ // in one browser but not in another.
+
+ // If name is ""arguments"", Var maybe null.
+ if (v != null && v.getParentNode().getType() == Token.CATCH) {
+ // Redeclaration of a catch expression variable is hard to model
+ // without support for ""with"" expressions.
+ // The EcmaScript spec (section 12.14), declares that a catch
+ // ""catch (e) {}"" is handled like ""with ({'e': e}) {}"" so that
+ // ""var e"" would refer to the scope variable, but any following
+ // reference would still refer to ""e"" of the catch expression.
+ // Until we have support for this disallow it.
+ // Currently the Scope object adds the catch expression to the
+ // function scope, which is technically not true but a good
+ // approximation for most uses.
+
+ // TODO(johnlenz): Consider improving how scope handles catch
+ // expression.
+
+ // Use the name of the var before it was made unique.
+ name = MakeDeclaredNamesUnique.ContextualRenameInverter.getOrginalName(
+ name);
+ compiler.report(
+ JSError.make(
+ NodeUtil.getSourceName(nodeWithLineNumber), nodeWithLineNumber,
+ CATCH_BLOCK_VAR_ERROR, name));
+ } else if (v != null && parent.getType() == Token.FUNCTION) {
+ if (v.getParentNode().getType() == Token.VAR) {
+ s.undeclare(v);
+ s.declare(name, n, n.getJSType(), v.input);
+ replaceVarWithAssignment(v.getNameNode(), v.getParentNode(),
+ v.getParentNode().getParent());
+ }
+ } else if (parent.getType() == Token.VAR) {
+ Preconditions.checkState(parent.hasOneChild());
+
+ replaceVarWithAssignment(n, parent, gramps);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDuplicateVarInExterns() {
+ test(""var extern;"",
+ ""/** @suppress {duplicate} */ var extern = 3;"", ""var extern = 3;"",
+ null, null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void expectInterfaceProperty(NodeTraversal t, Node n,
+ ObjectType instance, ObjectType implementedInterface, String prop) {
+ if (!instance.hasProperty(prop)) {
+ // Not implemented
+ String sourceName = (String) n.getProp(Node.SOURCENAME_PROP);
+ sourceName = sourceName == null ? """" : sourceName;
+ if (shouldReport) {
+ compiler.report(JSError.make(sourceName, n,
+ INTERFACE_METHOD_NOT_IMPLEMENTED,
+ prop, implementedInterface.toString(), instance.toString()));
+ }
+ registerMismatch(instance, implementedInterface);
+ // Implemented, but not correctly typed
+ }
+ }
+
+
+// Test Case
+[/INST]
+ public void testInterfaceInheritanceCheck12() throws Exception {
+ testTypes(
+ ""/** @interface */ function I() {};\n"" +
+ ""/** @type {string} */ I.prototype.foobar;\n"" +
+ ""/** \n * @constructor \n * @implements {I} */\n"" +
+ ""function C() {\n"" +
+ ""/** \n * @type {number} */ this.foobar = 2;};\n"" +
+ ""/** @type {I} */ \n var test = new C(); alert(test.foobar);"",
+ ""mismatch of the foobar property type and the type of the property"" +
+ "" it overrides from interface I\n"" +
+ ""original: string\n"" +
+ ""override: number"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void checkDeclaredPropertyInheritance(
+ NodeTraversal t, Node n, FunctionType ctorType, String propertyName,
+ JSDocInfo info, JSType propertyType) {
+ // If the supertype doesn't resolve correctly, we've warned about this
+ // already.
+ if (hasUnknownOrEmptySupertype(ctorType)) {
+ return;
+ }
+
+ FunctionType superClass = ctorType.getSuperClassConstructor();
+ boolean superClassHasProperty = superClass != null &&
+ superClass.getPrototype().hasProperty(propertyName);
+ boolean declaredOverride = info != null && info.isOverride();
+
+ boolean foundInterfaceProperty = false;
+ if (ctorType.isConstructor()) {
+ for (JSType implementedInterface : ctorType.getImplementedInterfaces()) {
+ if (implementedInterface.isUnknownType() ||
+ implementedInterface.isEmptyType()) {
+ continue;
+ }
+ FunctionType interfaceType =
+ implementedInterface.toObjectType().getConstructor();
+ Preconditions.checkNotNull(interfaceType);
+ boolean interfaceHasProperty =
+ interfaceType.getPrototype().hasProperty(propertyName);
+ foundInterfaceProperty = foundInterfaceProperty || interfaceHasProperty;
+ if (reportMissingOverride.isOn() && !declaredOverride &&
+ interfaceHasProperty) {
+ // @override not present, but the property does override an interface
+ // property
+ compiler.report(t.makeError(n, reportMissingOverride,
+ HIDDEN_INTERFACE_PROPERTY, propertyName,
+ interfaceType.getTopMostDefiningType(propertyName).toString()));
+ }
+ if (interfaceHasProperty) {
+ JSType interfacePropType =
+ interfaceType.getPrototype().getPropertyType(propertyName);
+ if (!propertyType.canAssignTo(interfacePropType)) {
+ compiler.report(t.makeError(n,
+ HIDDEN_INTERFACE_PROPERTY_MISMATCH, propertyName,
+ interfaceType.getTopMostDefiningType(propertyName).toString(),
+ interfacePropType.toString(), propertyType.toString()));
+ }
+ }
+ }
+ }
+
+ if (!declaredOverride && !superClassHasProperty) {
+ // nothing to do here, it's just a plain new property
+ return;
+ }
+
+ JSType topInstanceType = superClassHasProperty ?
+ superClass.getTopMostDefiningType(propertyName) : null;
+ if (reportMissingOverride.isOn() && ctorType.isConstructor() &&
+ !declaredOverride && superClassHasProperty) {
+ // @override not present, but the property does override a superclass
+ // property
+ compiler.report(t.makeError(n, reportMissingOverride,
+ HIDDEN_SUPERCLASS_PROPERTY, propertyName,
+ topInstanceType.toString()));
+ }
+ if (!declaredOverride) {
+ // there's no @override to check
+ return;
+ }
+ // @override is present and we have to check that it is ok
+ if (superClassHasProperty) {
+ // there is a superclass implementation
+ JSType superClassPropType =
+ superClass.getPrototype().getPropertyType(propertyName);
+ if (!propertyType.canAssignTo(superClassPropType)) {
+ compiler.report(
+ t.makeError(n, HIDDEN_SUPERCLASS_PROPERTY_MISMATCH,
+ propertyName, topInstanceType.toString(),
+ superClassPropType.toString(), propertyType.toString()));
+ }
+ } else if (!foundInterfaceProperty) {
+ // there is no superclass nor interface implementation
+ compiler.report(
+ t.makeError(n, UNKNOWN_OVERRIDE,
+ propertyName, ctorType.getInstanceType().toString()));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testInterfaceInheritanceCheck12() throws Exception {
+ testTypes(
+ ""/** @interface */ function I() {};\n"" +
+ ""/** @type {string} */ I.prototype.foobar;\n"" +
+ ""/** \n * @constructor \n * @implements {I} */\n"" +
+ ""function C() {\n"" +
+ ""/** \n * @type {number} */ this.foobar = 2;};\n"" +
+ ""/** @type {I} */ \n var test = new C(); alert(test.foobar);"",
+ ""mismatch of the foobar property type and the type of the property"" +
+ "" it overrides from interface I\n"" +
+ ""original: string\n"" +
+ ""override: number"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (n.getType() == Token.NAME) {
+ Var v = t.getScope().getVar(n.getString());
+ if (v != null && varFilter.apply(v)) {
+ addReference(t, v,
+ new Reference(n, parent, t, blockStack.peek()));
+ }
+ }
+
+ if (isBlockBoundary(n, parent)) {
+ blockStack.pop();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testArgumentsModifiedInInnerFunction() {
+ test(
+ ""function g(callback) {\n"" +
+ "" var f = callback;\n"" +
+ "" f.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"",
+ ""function g(callback) {\n"" +
+ "" callback.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void doInlinesForScope(NodeTraversal t,
+ Map referenceMap) {
+
+ for (Iterator it = t.getScope().getVars(); it.hasNext();) {
+ Var v = it.next();
+
+ ReferenceCollection referenceInfo = referenceMap.get(v);
+
+ // referenceInfo will be null if we're in constants-only mode
+ // and the variable is not a constant.
+ if (referenceInfo == null || isVarInlineForbidden(v)) {
+ // Never try to inline exported variables or variables that
+ // were not collected or variables that have already been inlined.
+ continue;
+ } else if (isInlineableDeclaredConstant(v, referenceInfo)) {
+ Reference init = referenceInfo.getInitializingReferenceForConstants();
+ Node value = init.getAssignedValue();
+ inlineDeclaredConstant(v, value, referenceInfo.references);
+ staleVars.add(v);
+ } else if (mode == Mode.CONSTANTS_ONLY) {
+ // If we're in constants-only mode, don't run more aggressive
+ // inlining heuristics. See InlineConstantsTest.
+ continue;
+ } else {
+ inlineNonConstants(v, referenceInfo);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testArgumentsModifiedInInnerFunction() {
+ test(
+ ""function g(callback) {\n"" +
+ "" var f = callback;\n"" +
+ "" f.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"",
+ ""function g(callback) {\n"" +
+ "" callback.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void inlineNonConstants(
+ Var v, ReferenceCollection referenceInfo) {
+ 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.getNameNode();
+ 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 (
+ !staleVars.contains(v) && referenceInfo.isWellDefined() &&
+ referenceInfo.isAssignedOnceInLifetime()) {
+ List refs = referenceInfo.references;
+ for (int i = 1 /* start from a read */; i < refs.size(); i++) {
+ Node nameNode = refs.get(i).getNameNode();
+ 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);
+ }
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testArgumentsModifiedInInnerFunction() {
+ test(
+ ""function g(callback) {\n"" +
+ "" var f = callback;\n"" +
+ "" f.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"",
+ ""function g(callback) {\n"" +
+ "" callback.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testArgumentsModifiedInInnerFunction() {
+ test(
+ ""function g(callback) {\n"" +
+ "" var f = callback;\n"" +
+ "" f.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"",
+ ""function g(callback) {\n"" +
+ "" callback.apply(this, arguments);\n"" +
+ "" function inner(callback) {"" +
+ "" var x = callback;\n"" +
+ "" arguments[0] = this;\n"" +
+ "" x.apply(this);\n"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void collapseDeclarationOfNameAndDescendants(Name n, String alias) {
+ boolean canCollapseChildNames = n.canCollapseUnannotatedChildNames();
+
+ // Handle this name first so that nested object literals get unrolled.
+ if (n.canCollapse() && canCollapseChildNames) {
+ updateObjLitOrFunctionDeclaration(n, alias);
+ }
+
+ if (n.props != null) {
+ for (Name p : n.props) {
+ // Recurse first so that saved node ancestries are intact when needed.
+ collapseDeclarationOfNameAndDescendants(
+ p, appendPropForAlias(alias, p.name));
+
+ if (!p.inExterns && canCollapseChildNames && p.declaration != null &&
+ p.declaration.node != null &&
+ p.declaration.node.getParent() != null &&
+ p.declaration.node.getParent().getType() == Token.ASSIGN) {
+ updateSimpleDeclaration(
+ appendPropForAlias(alias, p.name), p, p.declaration);
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testAliasedTopLevelEnum() {
+ test(
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @enum {number} */"" +
+ ""dojo.gfx.Shape = {SQUARE: 2};"" +
+ ""dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo.gfx.Shape.SQUARE);"",
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @constructor */"" +
+ ""var dojo$gfx$Shape = {SQUARE: 2};"" +
+ ""dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo$gfx$Shape.SQUARE);"",
+ null,
+ CollapseProperties.UNSAFE_NAMESPACE_WARNING);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateObjLitOrFunctionDeclaration(Name n, String alias) {
+ if (n.declaration == null) {
+ // Some names do not have declarations, because they
+ // are only defined in local scopes.
+ return;
+ }
+
+ if (n.declaration.getTwin() != null) {
+ // Twin declarations will get handled when normal references
+ // are handled.
+ return;
+ }
+
+ switch (n.declaration.node.getParent().getType()) {
+ case Token.ASSIGN:
+ updateObjLitOrFunctionDeclarationAtAssignNode(n, alias);
+ break;
+ case Token.VAR:
+ updateObjLitOrFunctionDeclarationAtVarNode(n);
+ break;
+ case Token.FUNCTION:
+ updateFunctionDeclarationAtFunctionNode(n);
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testAliasedTopLevelEnum() {
+ test(
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @enum {number} */"" +
+ ""dojo.gfx.Shape = {SQUARE: 2};"" +
+ ""dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo.gfx.Shape.SQUARE);"",
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @constructor */"" +
+ ""var dojo$gfx$Shape = {SQUARE: 2};"" +
+ ""dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo$gfx$Shape.SQUARE);"",
+ null,
+ CollapseProperties.UNSAFE_NAMESPACE_WARNING);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateObjLitOrFunctionDeclarationAtAssignNode(
+ Name n, String alias) {
+ // NOTE: It's important that we don't add additional nodes
+ // (e.g. a var node before the exprstmt) because the exprstmt might be
+ // the child of an if statement that's not inside a block).
+
+ Ref ref = n.declaration;
+ Node rvalue = ref.node.getNext();
+ Node varNode = new Node(Token.VAR);
+ Node varParent = ref.node.getAncestor(3);
+ Node gramps = ref.node.getAncestor(2);
+ boolean isObjLit = rvalue.getType() == Token.OBJECTLIT;
+ boolean insertedVarNode = false;
+
+ if (isObjLit && n.canEliminate()) {
+ // Eliminate the object literal altogether.
+ varParent.replaceChild(gramps, varNode);
+ ref.node = null;
+ insertedVarNode = true;
+
+ } else if (!n.isSimpleName()) {
+ // Create a VAR node to declare the name.
+ if (rvalue.getType() == Token.FUNCTION) {
+ checkForHosedThisReferences(rvalue, n.docInfo, n);
+ }
+
+ ref.node.getParent().removeChild(rvalue);
+
+ Node nameNode = NodeUtil.newName(
+ compiler.getCodingConvention(),
+ alias, ref.node.getAncestor(2), n.fullName());
+
+ if (ref.node.getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME)) {
+ nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
+ }
+
+ varNode.addChildToBack(nameNode);
+ nameNode.addChildToFront(rvalue);
+ varParent.replaceChild(gramps, varNode);
+
+ // Update the node ancestry stored in the reference.
+ ref.node = nameNode;
+ insertedVarNode = true;
+ }
+
+ if (isObjLit) {
+ declareVarsForObjLitValues(
+ n, alias, rvalue,
+ varNode, varParent.getChildBefore(varNode), varParent);
+
+ }
+ addStubsForUndeclaredProperties(n, alias, varParent, varNode);
+
+ if (insertedVarNode) {
+ if (!varNode.hasChildren()) {
+ varParent.removeChild(varNode);
+ }
+ compiler.reportCodeChange();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testAliasedTopLevelEnum() {
+ test(
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @enum {number} */"" +
+ ""dojo.gfx.Shape = {SQUARE: 2};"" +
+ ""dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo.gfx.Shape.SQUARE);"",
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @constructor */"" +
+ ""var dojo$gfx$Shape = {SQUARE: 2};"" +
+ ""dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo$gfx$Shape.SQUARE);"",
+ null,
+ CollapseProperties.UNSAFE_NAMESPACE_WARNING);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateObjLitOrFunctionDeclarationAtVarNode(Name n) {
+
+ Ref ref = n.declaration;
+ String name = ref.node.getString();
+ Node rvalue = ref.node.getFirstChild();
+ Node varNode = ref.node.getParent();
+ Node gramps = varNode.getParent();
+
+ boolean isObjLit = rvalue.getType() == Token.OBJECTLIT;
+ int numChanges = 0;
+
+ if (isObjLit) {
+ numChanges += declareVarsForObjLitValues(
+ n, name, rvalue, varNode, gramps.getChildBefore(varNode),
+ gramps);
+ }
+
+ numChanges += addStubsForUndeclaredProperties(n, name, gramps, varNode);
+
+ if (isObjLit && n.canEliminate()) {
+ varNode.removeChild(ref.node);
+ if (!varNode.hasChildren()) {
+ gramps.removeChild(varNode);
+ }
+ numChanges++;
+
+ // Clear out the object reference, since we've eliminated it from the
+ // parse tree.
+ ref.node = null;
+ }
+
+ if (numChanges > 0) {
+ compiler.reportCodeChange();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testAliasedTopLevelEnum() {
+ test(
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @enum {number} */"" +
+ ""dojo.gfx.Shape = {SQUARE: 2};"" +
+ ""dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo.gfx.Shape.SQUARE);"",
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @constructor */"" +
+ ""var dojo$gfx$Shape = {SQUARE: 2};"" +
+ ""dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo$gfx$Shape.SQUARE);"",
+ null,
+ CollapseProperties.UNSAFE_NAMESPACE_WARNING);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateFunctionDeclarationAtFunctionNode(Name n) {
+
+ Ref ref = n.declaration;
+ String fnName = ref.node.getString();
+ addStubsForUndeclaredProperties(
+ n, fnName, ref.node.getAncestor(2), ref.node.getParent());
+ }
+
+// Test Case
+[/INST]
+ public void testAliasedTopLevelEnum() {
+ test(
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @enum {number} */"" +
+ ""dojo.gfx.Shape = {SQUARE: 2};"" +
+ ""dojo.gfx.Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo.gfx.Shape.SQUARE);"",
+ ""function alias() {}"" +
+ ""var dojo = {};"" +
+ ""dojo.gfx = {};"" +
+ ""dojo.declare = function() {};"" +
+ ""/** @constructor */"" +
+ ""var dojo$gfx$Shape = {SQUARE: 2};"" +
+ ""dojo$gfx$Shape = dojo.declare('dojo.gfx.Shape');"" +
+ ""alias(dojo);"" +
+ ""alias(dojo$gfx$Shape.SQUARE);"",
+ null,
+ CollapseProperties.UNSAFE_NAMESPACE_WARNING);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void add(Node n, Context context) {
+ if (!cc.continueProcessing()) {
+ return;
+ }
+
+ int type = n.getType();
+ String opstr = NodeUtil.opToStr(type);
+ int childCount = n.getChildCount();
+ Node first = n.getFirstChild();
+ Node last = n.getLastChild();
+
+ // Handle all binary operators
+ if (opstr != null && first != last) {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad binary operator \""%s\"": expected 2 arguments but got %s"",
+ opstr, childCount);
+ int p = NodeUtil.precedence(type);
+ addLeftExpr(first, p, context);
+ cc.addOp(opstr, true);
+
+ // For right-hand-side of operations, only pass context if it's
+ // the IN_FOR_INIT_CLAUSE one.
+ Context rhsContext = getContextForNoInOperator(context);
+
+ // Handle associativity.
+ // e.g. if the parse tree is a * (b * c),
+ // we can simply generate a * b * c.
+ if (last.getType() == type &&
+ NodeUtil.isAssociative(type)) {
+ addExpr(last, p, rhsContext);
+ } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {
+ // Assignments are the only right-associative binary operators
+ addExpr(last, p, rhsContext);
+ } else {
+ addExpr(last, p + 1, rhsContext);
+ }
+ return;
+ }
+
+ cc.startSourceMapping(n);
+
+ switch (type) {
+ case Token.TRY: {
+ Preconditions.checkState(first.getNext().getType() == Token.BLOCK &&
+ !first.getNext().hasMoreThanOneChild());
+ Preconditions.checkState(childCount >= 2 && childCount <= 3);
+
+ add(""try"");
+ add(first, Context.PRESERVE_BLOCK);
+
+ // second child contains the catch block, or nothing if there
+ // isn't a catch block
+ Node catchblock = first.getNext().getFirstChild();
+ if (catchblock != null) {
+ add(catchblock);
+ }
+
+ if (childCount == 3) {
+ add(""finally"");
+ add(last, Context.PRESERVE_BLOCK);
+ }
+ break;
+ }
+
+ case Token.CATCH:
+ Preconditions.checkState(childCount == 2);
+ add(""catch("");
+ add(first);
+ add("")"");
+ add(last, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.THROW:
+ Preconditions.checkState(childCount == 1);
+ add(""throw"");
+ add(first);
+
+ // Must have a ';' after a throw statement, otherwise safari can't
+ // parse this.
+ cc.endStatement(true);
+ break;
+
+ case Token.RETURN:
+ add(""return"");
+ if (childCount == 1) {
+ add(first);
+ } else {
+ Preconditions.checkState(childCount == 0);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.VAR:
+ if (first != null) {
+ add(""var "");
+ addList(first, false, getContextForNoInOperator(context));
+ }
+ break;
+
+ case Token.LABEL_NAME:
+ Preconditions.checkState(!n.getString().isEmpty());
+ addIdentifier(n.getString());
+ break;
+
+ case Token.NAME:
+ if (first == null || first.getType() == Token.EMPTY) {
+ addIdentifier(n.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ addIdentifier(n.getString());
+ cc.addOp(""="", true);
+ if (first.getType() == Token.COMMA) {
+ addExpr(first, NodeUtil.precedence(Token.ASSIGN));
+ } else {
+ // Add expression, consider nearby code at lowest level of
+ // precedence.
+ addExpr(first, 0, getContextForNoInOperator(context));
+ }
+ }
+ break;
+
+ case Token.ARRAYLIT:
+ add(""["");
+ addArrayList(first);
+ add(""]"");
+ break;
+
+ case Token.LP:
+ add(""("");
+ addList(first);
+ add("")"");
+ break;
+
+ case Token.COMMA:
+ Preconditions.checkState(childCount == 2);
+ addList(first, false, context);
+ break;
+
+ case Token.NUMBER:
+ Preconditions.checkState(
+ childCount ==
+ ((n.getParent() != null &&
+ n.getParent().getType() == Token.OBJECTLIT) ? 1 : 0));
+ cc.addNumber(n.getDouble());
+ break;
+
+ case Token.TYPEOF:
+ case Token.VOID:
+ case Token.NOT:
+ case Token.BITNOT:
+ case Token.POS: {
+ // All of these unary operators are right-associative
+ Preconditions.checkState(childCount == 1);
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type));
+ break;
+ }
+
+ case Token.NEG: {
+ Preconditions.checkState(childCount == 1);
+
+ // It's important to our sanity checker that the code
+ // we print produces the same AST as the code we parse back.
+ // NEG is a weird case because Rhino parses ""- -2"" as ""2"".
+ if (n.getFirstChild().getType() == Token.NUMBER) {
+ cc.addNumber(-n.getFirstChild().getDouble());
+ } else {
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type));
+ }
+
+ break;
+ }
+
+ case Token.HOOK: {
+ Preconditions.checkState(childCount == 3);
+ int p = NodeUtil.precedence(type);
+ addLeftExpr(first, p + 1, context);
+ cc.addOp(""?"", true);
+ addExpr(first.getNext(), 1);
+ cc.addOp("":"", true);
+ addExpr(last, 1);
+ break;
+ }
+
+ case Token.REGEXP:
+ if (first.getType() != Token.STRING ||
+ last.getType() != Token.STRING) {
+ throw new Error(""Expected children to be strings"");
+ }
+
+ String regexp = regexpEscape(first.getString(), outputCharsetEncoder);
+
+ // I only use one .add because whitespace matters
+ if (childCount == 2) {
+ add(regexp + last.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ add(regexp);
+ }
+ break;
+
+ case Token.GET_REF:
+ add(first);
+ break;
+
+ case Token.REF_SPECIAL:
+ Preconditions.checkState(childCount == 1);
+ add(first);
+ add(""."");
+ add((String) n.getProp(Node.NAME_PROP));
+ break;
+
+ case Token.FUNCTION:
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ Preconditions.checkState(childCount == 3);
+ boolean funcNeedsParens = (context == Context.START_OF_EXPR);
+ if (funcNeedsParens) {
+ add(""("");
+ }
+
+ add(""function"");
+ add(first);
+
+ add(first.getNext());
+ add(last, Context.PRESERVE_BLOCK);
+ cc.endFunction(context == Context.STATEMENT);
+
+ if (funcNeedsParens) {
+ add("")"");
+ }
+ break;
+
+ case Token.GET:
+ case Token.SET:
+ Preconditions.checkState(n.getParent().getType() == Token.OBJECTLIT);
+ Preconditions.checkState(childCount == 1);
+ Preconditions.checkState(first.getType() == Token.FUNCTION);
+
+ // Get methods are unnamed
+ Preconditions.checkState(first.getFirstChild().getString().isEmpty());
+ if (type == Token.GET) {
+ // Get methods have no parameters.
+ Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());
+ add(""get "");
+ } else {
+ // Set methods have one parameter.
+ Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());
+ add(""set "");
+ }
+
+ // The name is on the GET or SET node.
+ String name = n.getString();
+ Node fn = first;
+ Node parameters = fn.getChildAtIndex(1);
+ Node body = fn.getLastChild();
+
+ // Add the property name.
+ if (TokenStream.isJSIdentifier(name) &&
+ // do not encode literally any non-literal characters that were
+ // unicode escaped.
+ NodeUtil.isLatin(name)) {
+ add(name);
+ } else {
+ // Determine if the string is a simple number.
+ add(jsString(n.getString(), outputCharsetEncoder));
+ }
+
+ add(parameters);
+ add(body, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.SCRIPT:
+ case Token.BLOCK: {
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ boolean preserveBlock = context == Context.PRESERVE_BLOCK;
+ if (preserveBlock) {
+ cc.beginBlock();
+ }
+
+ boolean preferLineBreaks =
+ type == Token.SCRIPT ||
+ (type == Token.BLOCK &&
+ !preserveBlock &&
+ n.getParent() != null &&
+ n.getParent().getType() == Token.SCRIPT);
+ for (Node c = first; c != null; c = c.getNext()) {
+ add(c, Context.STATEMENT);
+
+ // VAR doesn't include ';' since it gets used in expressions
+ if (c.getType() == Token.VAR) {
+ cc.endStatement();
+ }
+
+ if (c.getType() == Token.FUNCTION) {
+ cc.maybeLineBreak();
+ }
+
+ // Prefer to break lines in between top-level statements
+ // because top level statements are more homogeneous.
+ if (preferLineBreaks) {
+ cc.notePreferredLineBreak();
+ }
+ }
+ if (preserveBlock) {
+ cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
+ }
+ break;
+ }
+
+ case Token.FOR:
+ if (childCount == 4) {
+ add(""for("");
+ if (first.getType() == Token.VAR) {
+ add(first, Context.IN_FOR_INIT_CLAUSE);
+ } else {
+ addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);
+ }
+ add("";"");
+ add(first.getNext());
+ add("";"");
+ add(first.getNext().getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ Preconditions.checkState(childCount == 3);
+ add(""for("");
+ add(first);
+ add(""in"");
+ add(first.getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ }
+ break;
+
+ case Token.DO:
+ Preconditions.checkState(childCount == 2);
+ add(""do"");
+ addNonEmptyStatement(first, Context.OTHER, false);
+ add(""while("");
+ add(last);
+ add("")"");
+ cc.endStatement();
+ break;
+
+ case Token.WHILE:
+ Preconditions.checkState(childCount == 2);
+ add(""while("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.EMPTY:
+ Preconditions.checkState(childCount == 0);
+ break;
+
+ case Token.GETPROP: {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETPROP: expected 2 children, but got %s"", childCount);
+ Preconditions.checkState(
+ last.getType() == Token.STRING,
+ ""Bad GETPROP: RHS should be STRING"");
+ boolean needsParens = (first.getType() == Token.NUMBER);
+ if (needsParens) {
+ add(""("");
+ }
+ addLeftExpr(first, NodeUtil.precedence(type), context);
+ if (needsParens) {
+ add("")"");
+ }
+ add(""."");
+ addIdentifier(last.getString());
+ break;
+ }
+
+ case Token.GETELEM:
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETELEM: expected 2 children but got %s"", childCount);
+ addLeftExpr(first, NodeUtil.precedence(type), context);
+ add(""["");
+ add(first.getNext());
+ add(""]"");
+ break;
+
+ case Token.WITH:
+ Preconditions.checkState(childCount == 2);
+ add(""with("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.INC:
+ case Token.DEC: {
+ Preconditions.checkState(childCount == 1);
+ String o = type == Token.INC ? ""++"" : ""--"";
+ int postProp = n.getIntProp(Node.INCRDECR_PROP);
+ // A non-zero post-prop value indicates a post inc/dec, default of zero
+ // is a pre-inc/dec.
+ if (postProp != 0) {
+ addLeftExpr(first, NodeUtil.precedence(type), context);
+ cc.addOp(o, false);
+ } else {
+ cc.addOp(o, false);
+ add(first);
+ }
+ break;
+ }
+
+ case Token.CALL:
+ // We have two special cases here:
+ // 1) If the left hand side of the call is a direct reference to eval,
+ // then it must have a DIRECT_EVAL annotation. If it does not, then
+ // that means it was originally an indirect call to eval, and that
+ // indirectness must be preserved.
+ // 2) If the left hand side of the call is a property reference,
+ // then the call must not a FREE_CALL annotation. If it does, then
+ // that means it was originally an call without an explicit this and
+ // that must be preserved.
+ if (isIndirectEval(first)
+ || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {
+ add(""(0,"");
+ addExpr(first, NodeUtil.precedence(Token.COMMA));
+ add("")"");
+ } else {
+ addLeftExpr(first, NodeUtil.precedence(type), context);
+ }
+ add(""("");
+ addList(first.getNext());
+ add("")"");
+ break;
+
+ case Token.IF:
+ boolean hasElse = childCount == 3;
+ boolean ambiguousElseClause =
+ context == Context.BEFORE_DANGLING_ELSE && !hasElse;
+ if (ambiguousElseClause) {
+ cc.beginBlock();
+ }
+
+ add(""if("");
+ add(first);
+ add("")"");
+
+ if (hasElse) {
+ addNonEmptyStatement(
+ first.getNext(), Context.BEFORE_DANGLING_ELSE, false);
+ add(""else"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ addNonEmptyStatement(first.getNext(), Context.OTHER, false);
+ Preconditions.checkState(childCount == 2);
+ }
+
+ if (ambiguousElseClause) {
+ cc.endBlock();
+ }
+ break;
+
+ case Token.NULL:
+ case Token.THIS:
+ case Token.FALSE:
+ case Token.TRUE:
+ Preconditions.checkState(childCount == 0);
+ add(Node.tokenToName(type));
+ break;
+
+ case Token.CONTINUE:
+ Preconditions.checkState(childCount <= 1);
+ add(""continue"");
+ if (childCount == 1) {
+ if (first.getType() != Token.LABEL_NAME) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.DEBUGGER:
+ Preconditions.checkState(childCount == 0);
+ add(""debugger"");
+ cc.endStatement();
+ break;
+
+ case Token.BREAK:
+ Preconditions.checkState(childCount <= 1);
+ add(""break"");
+ if (childCount == 1) {
+ if (first.getType() != Token.LABEL_NAME) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.EXPR_VOID:
+ throw new Error(""Unexpected EXPR_VOID. Should be EXPR_RESULT."");
+
+ case Token.EXPR_RESULT:
+ Preconditions.checkState(childCount == 1);
+ add(first, Context.START_OF_EXPR);
+ cc.endStatement();
+ break;
+
+ case Token.NEW:
+ add(""new "");
+ int precedence = NodeUtil.precedence(type);
+
+ // If the first child contains a CALL, then claim higher precedence
+ // to force parentheses. Otherwise, when parsed, NEW will bind to the
+ // first viable parentheses (don't traverse into functions).
+ if (NodeUtil.containsType(first, Token.CALL, new MatchNotFunction())) {
+ precedence = NodeUtil.precedence(first.getType()) + 1;
+ }
+ addExpr(first, precedence);
+
+ // '()' is optional when no arguments are present
+ Node next = first.getNext();
+ if (next != null) {
+ add(""("");
+ addList(next);
+ add("")"");
+ }
+ break;
+
+ case Token.STRING:
+ if (childCount !=
+ ((n.getParent() != null &&
+ n.getParent().getType() == Token.OBJECTLIT) ? 1 : 0)) {
+ throw new IllegalStateException(
+ ""Unexpected String children: "" + n.getParent().toStringTree());
+ }
+ add(jsString(n.getString(), outputCharsetEncoder));
+ break;
+
+ case Token.DELPROP:
+ Preconditions.checkState(childCount == 1);
+ add(""delete "");
+ add(first);
+ break;
+
+ case Token.OBJECTLIT: {
+ boolean needsParens = (context == Context.START_OF_EXPR);
+ if (needsParens) {
+ add(""("");
+ }
+ add(""{"");
+ for (Node c = first; c != null; c = c.getNext()) {
+ if (c != first) {
+ cc.listSeparator();
+ }
+
+ if (c.getType() == Token.GET || c.getType() == Token.SET) {
+ add(c);
+ } else {
+ // Object literal property names don't have to be quoted if they
+ // are not JavaScript keywords
+ if (c.getType() == Token.STRING &&
+ !c.isQuotedString() &&
+ !TokenStream.isKeyword(c.getString()) &&
+ TokenStream.isJSIdentifier(c.getString()) &&
+ // do not encode literally any non-literal characters that
+ // were unicode escaped.
+ NodeUtil.isLatin(c.getString())) {
+ add(c.getString());
+ } else {
+ // Determine if the string is a simple number.
+ addExpr(c, 1);
+ }
+ add("":"");
+ addExpr(c.getFirstChild(), 1);
+ }
+ }
+ add(""}"");
+ if (needsParens) {
+ add("")"");
+ }
+ break;
+ }
+
+ case Token.SWITCH:
+ add(""switch("");
+ add(first);
+ add("")"");
+ cc.beginBlock();
+ addAllSiblings(first.getNext());
+ cc.endBlock(context == Context.STATEMENT);
+ break;
+
+ case Token.CASE:
+ Preconditions.checkState(childCount == 2);
+ add(""case "");
+ add(first);
+ addCaseBody(last);
+ break;
+
+ case Token.DEFAULT:
+ Preconditions.checkState(childCount == 1);
+ add(""default"");
+ addCaseBody(first);
+ break;
+
+ case Token.LABEL:
+ Preconditions.checkState(childCount == 2);
+ if (first.getType() != Token.LABEL_NAME) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add(first);
+ add("":"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), true);
+ break;
+
+ // This node is auto generated in anonymous functions and should just get
+ // ignored for our purposes.
+ case Token.SETNAME:
+ break;
+
+ default:
+ throw new Error(""Unknown type "" + type + ""\n"" + n.toStringTree());
+ }
+
+ cc.endSourceMapping(n);
+ }
+
+// Test Case
+[/INST]
+ public void testObjectLit2() {
+ assertPrint(""var x={1:1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1':1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1.0':1}"", ""var x={\""1.0\"":1}"");
+ assertPrint(""var x={1.5:1}"", ""var x={\""1.5\"":1}"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ switch (n.getType()) {
+ case Token.GETPROP:
+ case Token.GETELEM:
+ Node dest = n.getFirstChild().getNext();
+ if (dest.getType() == Token.STRING) {
+ String s = dest.getString();
+ if (s.equals(""prototype"")) {
+ processPrototypeParent(parent, t.getInput());
+ } else {
+ markPropertyAccessCandidate(dest, t.getInput());
+ }
+ }
+ break;
+ case Token.OBJECTLIT:
+ if (!prototypeObjLits.contains(n)) {
+ // Object literals have their property name/value pairs as a flat
+ // list as their children. We want every other node in order to get
+ // only the property names.
+ for (Node child = n.getFirstChild();
+ child != null;
+ child = child.getNext()) {
+
+ if (child.getType() != Token.NUMBER) {
+ markObjLitPropertyCandidate(child, t.getInput());
+ }
+ }
+ }
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testObjectLit2() {
+ assertPrint(""var x={1:1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1':1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1.0':1}"", ""var x={\""1.0\"":1}"");
+ assertPrint(""var x={1.5:1}"", ""var x={\""1.5\"":1}"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node transformAsString(AstNode n) {
+ Node ret;
+ if (n instanceof Name) {
+ ret = transformNameAsString((Name)n);
+ } else {
+ ret = transform(n);
+ Preconditions.checkState(ret.getType() == Token.NUMBER
+ || ret.getType() == Token.STRING);
+ if (ret.getType() == Token.STRING) {
+ ret.putBooleanProp(Node.QUOTED_PROP, true);
+ }
+ }
+ return ret;
+ }
+
+// Test Case
+[/INST]
+ public void testObjectLit2() {
+ assertPrint(""var x={1:1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1':1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1.0':1}"", ""var x={\""1.0\"":1}"");
+ assertPrint(""var x={1.5:1}"", ""var x={\""1.5\"":1}"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processPrototypeParent(Node n, CompilerInput input) {
+ switch (n.getType()) {
+ // Foo.prototype.getBar = function() { ... }
+ case Token.GETPROP:
+ case Token.GETELEM:
+ Node dest = n.getFirstChild().getNext();
+ if (dest.getType() == Token.STRING) {
+ markPrototypePropertyCandidate(dest, input);
+ }
+ break;
+
+ // Foo.prototype = { ""getBar"" : function() { ... } }
+ case Token.ASSIGN:
+ case Token.CALL:
+ Node map;
+ if (n.getType() == Token.ASSIGN) {
+ map = n.getFirstChild().getNext();
+ } else {
+ map = n.getLastChild();
+ }
+ if (map.getType() == Token.OBJECTLIT) {
+ // Remember this node so that we can avoid processing it again when
+ // the traversal reaches it.
+ prototypeObjLits.add(map);
+
+ for (Node key = map.getFirstChild();
+ key != null; key = key.getNext()) {
+ if (key.getType() != Token.NUMBER) {
+ // May be STRING, GET, or SET
+ markPrototypePropertyCandidate(key, input);
+ }
+ }
+ }
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testObjectLit2() {
+ assertPrint(""var x={1:1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1':1}"", ""var x={1:1}"");
+ assertPrint(""var x={'1.0':1}"", ""var x={\""1.0\"":1}"");
+ assertPrint(""var x={1.5:1}"", ""var x={\""1.5\"":1}"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void setWarningLevels(CompilerOptions options,
+ List diagnosticGroups, CheckLevel level) {
+ for (String name : diagnosticGroups) {
+ DiagnosticGroup group = forName(name);
+ Preconditions.checkNotNull(group, ""No warning class for name: "" + name);
+ options.setWarningLevel(group, level);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ final protected void setRunOptions(CompilerOptions options)
+ throws FlagUsageException, IOException {
+ DiagnosticGroups diagnosticGroups = getDiagnosticGroups();
+
+ diagnosticGroups.setWarningLevels(
+ options, config.jscompError, CheckLevel.ERROR);
+ diagnosticGroups.setWarningLevels(
+ options, config.jscompWarning, CheckLevel.WARNING);
+ diagnosticGroups.setWarningLevels(
+ options, config.jscompOff, CheckLevel.OFF);
+
+ createDefineOrTweakReplacements(config.define, options, false);
+
+ options.setTweakProcessing(config.tweakProcessing);
+ createDefineOrTweakReplacements(config.tweak, options, true);
+
+ options.manageClosureDependencies = config.manageClosureDependencies;
+ if (config.closureEntryPoints.size() > 0) {
+ options.setManageClosureDependencies(config.closureEntryPoints);
+ }
+ options.devMode = config.jscompDevMode;
+ options.setCodingConvention(config.codingConvention);
+ options.setSummaryDetailLevel(config.summaryDetailLevel);
+
+ outputCharset = options.outputCharset = getOutputCharset();
+ inputCharset = getInputCharset();
+
+ if (config.jsOutputFile.length() > 0) {
+ options.jsOutputFile = config.jsOutputFile;
+ }
+
+ if (config.createSourceMap.length() > 0) {
+ options.sourceMapOutputPath = config.createSourceMap;
+ }
+ options.sourceMapDetailLevel = config.sourceMapDetailLevel;
+ options.sourceMapFormat = config.sourceMapFormat;
+
+ if (!config.variableMapInputFile.equals("""")) {
+ options.inputVariableMapSerialized =
+ VariableMap.load(config.variableMapInputFile).toBytes();
+ }
+
+ if (!config.propertyMapInputFile.equals("""")) {
+ options.inputPropertyMapSerialized =
+ VariableMap.load(config.propertyMapInputFile).toBytes();
+ }
+
+ if (config.languageIn.length() > 0) {
+ if (config.languageIn.equals(""ECMASCRIPT5_STRICT"") ||
+ config.languageIn.equals(""ES5_STRICT"")) {
+ options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT5);
+ } else if (config.languageIn.equals(""ECMASCRIPT5"") ||
+ config.languageIn.equals(""ES5"")) {
+ options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT5);
+ } else if (config.languageIn.equals(""ECMASCRIPT3"") ||
+ config.languageIn.equals(""ES3"")) {
+ options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT3);
+ } else {
+ throw new FlagUsageException(""Unknown language `"" + config.languageIn +
+ ""' specified."");
+ }
+ }
+
+ options.acceptConstKeyword = config.acceptConstKeyword;
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processFlagFile(PrintStream err)
+ throws CmdLineException, IOException {
+ List argsInFile = Lists.newArrayList();
+ File flagFileInput = new File(flags.flag_file);
+ StringTokenizer tokenizer = new StringTokenizer(
+ Files.toString(flagFileInput, Charset.defaultCharset()));
+
+ while (tokenizer.hasMoreTokens()) {
+ argsInFile.add(tokenizer.nextToken());
+ }
+
+ flags.flag_file = """";
+ List processedFileArgs
+ = processArgs(argsInFile.toArray(new String[] {}));
+ CmdLineParser parserFileArgs = new CmdLineParser(flags);
+ parserFileArgs.parseArgument(processedFileArgs.toArray(new String[] {}));
+
+ // Currently we are not supporting this (prevent direct/indirect loops)
+ if (!flags.flag_file.equals("""")) {
+ err.println(""ERROR - Arguments in the file cannot contain ""
+ + ""--flagfile option."");
+ isConfigValid = false;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void initConfigFromFlags(String[] args, PrintStream err) {
+
+ List processedArgs = processArgs(args);
+
+ CmdLineParser parser = new CmdLineParser(flags);
+ isConfigValid = true;
+ try {
+ parser.parseArgument(processedArgs.toArray(new String[] {}));
+ // For contains --flagfile flag
+ if (!flags.flag_file.equals("""")) {
+ processFlagFile(err);
+ }
+ } catch (CmdLineException e) {
+ err.println(e.getMessage());
+ isConfigValid = false;
+ } catch (IOException ioErr) {
+ err.println(""ERROR - "" + flags.flag_file + "" read error."");
+ isConfigValid = false;
+ }
+
+ if (flags.version) {
+ ResourceBundle config = ResourceBundle.getBundle(configResource);
+ err.println(
+ ""Closure Compiler (http://code.google.com/closure/compiler)\n"" +
+ ""Version: "" + config.getString(""compiler.version"") + ""\n"" +
+ ""Built on: "" + config.getString(""compiler.date""));
+ err.flush();
+ }
+
+ if (!isConfigValid || flags.display_help) {
+ isConfigValid = false;
+ parser.printUsage(err);
+ } else {
+ getCommandLineConfig()
+ .setPrintTree(flags.print_tree)
+ .setComputePhaseOrdering(flags.compute_phase_ordering)
+ .setPrintAst(flags.print_ast)
+ .setPrintPassGraph(flags.print_pass_graph)
+ .setJscompDevMode(flags.jscomp_dev_mode)
+ .setLoggingLevel(flags.logging_level)
+ .setExterns(flags.externs)
+ .setJs(flags.js)
+ .setJsOutputFile(flags.js_output_file)
+ .setModule(flags.module)
+ .setVariableMapInputFile(flags.variable_map_input_file)
+ .setPropertyMapInputFile(flags.property_map_input_file)
+ .setVariableMapOutputFile(flags.variable_map_output_file)
+ .setCreateNameMapFiles(flags.create_name_map_files)
+ .setPropertyMapOutputFile(flags.property_map_output_file)
+ .setCodingConvention(flags.third_party ?
+ new DefaultCodingConvention() :
+ new ClosureCodingConvention())
+ .setSummaryDetailLevel(flags.summary_detail_level)
+ .setOutputWrapper(flags.output_wrapper)
+ .setModuleWrapper(flags.module_wrapper)
+ .setModuleOutputPathPrefix(flags.module_output_path_prefix)
+ .setCreateSourceMap(flags.create_source_map)
+ .setJscompError(flags.jscomp_error)
+ .setJscompWarning(flags.jscomp_warning)
+ .setJscompOff(flags.jscomp_off)
+ .setDefine(flags.define)
+ .setCharset(flags.charset)
+ .setManageClosureDependencies(flags.manage_closure_dependencies)
+ .setClosureEntryPoints(flags.closure_entry_point)
+ .setOutputManifest(flags.output_manifest)
+ .setAcceptConstKeyword(flags.accept_const_keyword)
+ .setLanguageIn(flags.language_in);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ CommandLineConfig setJscompError(List jscompError) {
+ this.jscompError.clear();
+ this.jscompError.addAll(jscompError);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ CommandLineConfig setJscompWarning(List jscompWarning) {
+ this.jscompWarning.clear();
+ this.jscompWarning.addAll(jscompWarning);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ CommandLineConfig setJscompOff(List jscompOff) {
+ this.jscompOff.clear();
+ this.jscompOff.addAll(jscompOff);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testWarningGuardOrdering2() {
+ args.add(""--jscomp_off=globalThis"");
+ args.add(""--jscomp_error=globalThis"");
+ test(""function f() { this.a = 3; }"", CheckGlobalThis.GLOBAL_THIS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void findCalledFunctions(
+ Node node, Set changed) {
+ Preconditions.checkArgument(changed != null);
+ // For each referenced function, add a new reference
+ if (node.getType() == Token.CALL) {
+ Node child = node.getFirstChild();
+ if (child.getType() == Token.NAME) {
+ changed.add(child.getString());
+ }
+ }
+
+ for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
+ findCalledFunctions(c, changed);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue423() {
+ test(
+ ""(function($) {\n"" +
+ "" $.fn.multicheck = function(options) {\n"" +
+ "" initialize.call(this, options);\n"" +
+ "" };\n"" +
+ ""\n"" +
+ "" function initialize(options) {\n"" +
+ "" options.checkboxes = $(this).siblings(':checkbox');\n"" +
+ "" preload_check_all.call(this);\n"" +
+ "" }\n"" +
+ ""\n"" +
+ "" function preload_check_all() {\n"" +
+ "" $(this).data('checkboxes');\n"" +
+ "" }\n"" +
+ ""})(jQuery)"",
+ ""(function($){"" +
+ "" $.fn.multicheck=function(options$$1){"" +
+ "" {"" +
+ "" options$$1.checkboxes=$(this).siblings(\"":checkbox\"");"" +
+ "" {"" +
+ "" $(this).data(\""checkboxes\"")"" +
+ "" }"" +
+ "" }"" +
+ "" }"" +
+ ""})(jQuery)"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ AliasedTypeNode(Node typeReference,
+ String aliasName) {
+ this.typeReference = typeReference;
+ this.aliasName = aliasName;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue772() throws Exception {
+ CompilerOptions options = createCompilerOptions();
+ options.closurePass = true;
+ options.checkTypes = true;
+ test(
+ options,
+ ""/** @const */ var a = {};"" +
+ ""/** @const */ a.b = {};"" +
+ ""/** @const */ a.b.c = {};"" +
+ ""goog.scope(function() {"" +
+ "" var b = a.b;"" +
+ "" var c = b.c;"" +
+ "" /** @typedef {string} */"" +
+ "" c.MyType;"" +
+ "" /** @param {c.MyType} x The variable. */"" +
+ "" c.myFunc = function(x) {};"" +
+ ""});"",
+ ""/** @const */ var a = {};"" +
+ ""/** @const */ a.b = {};"" +
+ ""/** @const */ a.b.c = {};"" +
+ ""a.b.c.MyType;"" +
+ ""a.b.c.myFunc = function(x) {};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void applyAlias() {
+ typeReference.setString(aliasName);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue772() throws Exception {
+ CompilerOptions options = createCompilerOptions();
+ options.closurePass = true;
+ options.checkTypes = true;
+ test(
+ options,
+ ""/** @const */ var a = {};"" +
+ ""/** @const */ a.b = {};"" +
+ ""/** @const */ a.b.c = {};"" +
+ ""goog.scope(function() {"" +
+ "" var b = a.b;"" +
+ "" var c = b.c;"" +
+ "" /** @typedef {string} */"" +
+ "" c.MyType;"" +
+ "" /** @param {c.MyType} x The variable. */"" +
+ "" c.myFunc = function(x) {};"" +
+ ""});"",
+ ""/** @const */ var a = {};"" +
+ ""/** @const */ a.b = {};"" +
+ ""/** @const */ a.b.c = {};"" +
+ ""a.b.c.MyType;"" +
+ ""a.b.c.myFunc = function(x) {};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void fixTypeNode(Node typeNode) {
+ if (typeNode.isString()) {
+ String name = typeNode.getString();
+ int endIndex = name.indexOf('.');
+ if (endIndex == -1) {
+ endIndex = name.length();
+ }
+ String baseName = name.substring(0, endIndex);
+ Var aliasVar = aliases.get(baseName);
+ if (aliasVar != null) {
+ Node aliasedNode = aliasVar.getInitialValue();
+ aliasUsages.add(new AliasedTypeNode(typeNode, aliasedNode.getQualifiedName() + name.substring(endIndex)));
+ }
+ }
+
+ for (Node child = typeNode.getFirstChild(); child != null;
+ child = child.getNext()) {
+ fixTypeNode(child);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue772() throws Exception {
+ CompilerOptions options = createCompilerOptions();
+ options.closurePass = true;
+ options.checkTypes = true;
+ test(
+ options,
+ ""/** @const */ var a = {};"" +
+ ""/** @const */ a.b = {};"" +
+ ""/** @const */ a.b.c = {};"" +
+ ""goog.scope(function() {"" +
+ "" var b = a.b;"" +
+ "" var c = b.c;"" +
+ "" /** @typedef {string} */"" +
+ "" c.MyType;"" +
+ "" /** @param {c.MyType} x The variable. */"" +
+ "" c.myFunc = function(x) {};"" +
+ ""});"",
+ ""/** @const */ var a = {};"" +
+ ""/** @const */ a.b = {};"" +
+ ""/** @const */ a.b.c = {};"" +
+ ""a.b.c.MyType;"" +
+ ""a.b.c.myFunc = function(x) {};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void initOptions(CompilerOptions options) {
+ this.options = options;
+ if (errorManager == null) {
+ if (outStream == null) {
+ setErrorManager(
+ new LoggerErrorManager(createMessageFormatter(), logger));
+ } else {
+ PrintStreamErrorManager printer =
+ new PrintStreamErrorManager(createMessageFormatter(), outStream);
+ printer.setSummaryDetailLevel(options.summaryDetailLevel);
+ setErrorManager(printer);
+ }
+ }
+
+ // DiagnosticGroups override the plain checkTypes option.
+ if (options.enables(DiagnosticGroups.CHECK_TYPES)) {
+ options.checkTypes = true;
+ } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {
+ options.checkTypes = false;
+ } else if (!options.checkTypes) {
+ // If DiagnosticGroups did not override the plain checkTypes
+ // option, and checkTypes is enabled, then turn off the
+ // parser type warnings.
+ options.setWarningLevel(
+ DiagnosticGroup.forType(
+ RhinoErrorReporter.TYPE_PARSE_ERROR),
+ CheckLevel.OFF);
+ }
+
+ if (options.checkGlobalThisLevel.isOn()) {
+ options.setWarningLevel(
+ DiagnosticGroups.GLOBAL_THIS,
+ options.checkGlobalThisLevel);
+ }
+
+ // Initialize the warnings guard.
+ List guards = Lists.newArrayList();
+ guards.add(
+ new SuppressDocWarningsGuard(
+ getDiagnosticGroups().getRegisteredGroups()));
+ guards.add(options.getWarningsGuard());
+
+
+ // All passes must run the variable check. This synthesizes
+ // variables later so that the compiler doesn't crash. It also
+ // checks the externs file for validity. If you don't want to warn
+ // about missing variable declarations, we shut that specific
+ // error off.
+ if (!options.checkSymbols &&
+ (warningsGuard == null || !warningsGuard.disables(
+ DiagnosticGroups.CHECK_VARIABLES))) {
+ guards.add(new DiagnosticGroupWarningsGuard(
+ DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));
+ }
+
+ this.warningsGuard = new ComposeWarningsGuard(guards);
+ }
+
+// Test Case
+[/INST]
+ public void testCheckSymbolsOverrideForQuiet() {
+ args.add(""--warning_level=QUIET"");
+ args.add(""--jscomp_error=undefinedVars"");
+ test(""x = 3;"", VarCheck.UNDEFINED_VAR_ERROR);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryFoldArrayAccess(Node n, Node left, Node right) {
+ Node parent = n.getParent();
+ // If GETPROP/GETELEM is used as assignment target the array literal is
+ // acting as a temporary we can't fold it here:
+ // ""[][0] += 1""
+
+ if (right.getType() != Token.NUMBER) {
+ // Sometimes people like to use complex expressions to index into
+ // arrays, or strings to index into array methods.
+ return n;
+ }
+
+ double index = right.getDouble();
+ int intIndex = (int) index;
+ if (intIndex != index) {
+ error(INVALID_GETELEM_INDEX_ERROR, right);
+ return n;
+ }
+
+ if (intIndex < 0) {
+ error(INDEX_OUT_OF_BOUNDS_ERROR, right);
+ return n;
+ }
+
+ Node elem = left.getFirstChild();
+ for (int i = 0; elem != null && i < intIndex; i++) {
+ elem = elem.getNext();
+ }
+
+ if (elem == null) {
+ error(INDEX_OUT_OF_BOUNDS_ERROR, right);
+ return n;
+ }
+
+ if (elem.getType() == Token.EMPTY) {
+ elem = NodeUtil.newUndefinedNode(elem);
+ } else {
+ left.removeChild(elem);
+ }
+
+ // Replace the entire GETELEM with the value
+ n.getParent().replaceChild(n, elem);
+ reportCodeChange();
+ return elem;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue522() {
+ testSame(""[][1] = 1;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void enterScope(NodeTraversal t) {
+ Node n = t.getCurrentNode().getParent();
+ if (n != null && isCallToScopeMethod(n)) {
+ transformation = transformationHandler.logAliasTransformation(
+ n.getSourceFileName(), getSourceRegion(n));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testForwardJsDoc() {
+ testScoped(
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""foo.Foo = function() {};"" +
+ ""/** @param {Foo.Bar} x */ function actual(x) {3}"" +
+ ""var Foo = foo.Foo;"" +
+ ""/** @constructor */ Foo.Bar = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function expected(x) {}"",
+
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""foo.Foo = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function actual(x) {3}"" +
+ ""/** @constructor */ foo.Foo.Bar = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function expected(x) {}"");
+ verifyTypes();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (isCallToScopeMethod(n)) {
+ validateScopeCall(t, n, n.getParent());
+ }
+
+
+
+ // Validate the top level of the goog.scope block.
+ if (t.getScopeDepth() == 2) {
+ int type = n.getType();
+ if (type == Token.NAME && parent.getType() == Token.VAR) {
+ if (n.hasChildren() && n.getFirstChild().isQualifiedName()) {
+ String name = n.getString();
+ Var aliasVar = t.getScope().getVar(name);
+ aliases.put(name, aliasVar);
+ aliasDefinitionsInOrder.add(n);
+
+ String qualifiedName =
+ aliasVar.getInitialValue().getQualifiedName();
+ transformation.addAlias(name, qualifiedName);
+ // Return early, to ensure that we don't record a definition
+ // twice.
+ return;
+ } else {
+ report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
+ }
+ }
+ if (type == Token.NAME && NodeUtil.isAssignmentOp(parent) &&
+ n == parent.getFirstChild()) {
+ report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString());
+ }
+
+ if (type == Token.RETURN) {
+ report(t, n, GOOG_SCOPE_USES_RETURN);
+ } else if (type == Token.THIS) {
+ report(t, n, GOOG_SCOPE_REFERENCES_THIS);
+ } else if (type == Token.THROW) {
+ report(t, n, GOOG_SCOPE_USES_THROW);
+ }
+ }
+
+ // Validate all descendent scopes of the goog.scope block.
+ if (t.getScopeDepth() >= 2) {
+ // Check if this name points to an alias.
+ if (n.getType() == Token.NAME) {
+ String name = n.getString();
+ Var aliasVar = aliases.get(name);
+ if (aliasVar != null &&
+ t.getScope().getVar(name) == aliasVar) {
+ // Note, to support the transitive case, it's important we don't
+ // clone aliasedNode here. For example,
+ // var g = goog; var d = g.dom; d.createElement('DIV');
+ // The node in aliasedNode (which is ""g"") will be replaced in the
+ // changes pass above with ""goog"". If we cloned here, we'd end up
+ // with g.dom.createElement('DIV').
+ Node aliasedNode = aliasVar.getInitialValue();
+ aliasUsages.add(new AliasedNode(n, aliasedNode));
+ }
+ }
+
+ JSDocInfo info = n.getJSDocInfo();
+ if (info != null) {
+ for (Node node : info.getTypeNodes()) {
+ fixTypeNode(node);
+ }
+ }
+
+ // TODO(robbyw): Error for goog.scope not at root.
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testForwardJsDoc() {
+ testScoped(
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""foo.Foo = function() {};"" +
+ ""/** @param {Foo.Bar} x */ function actual(x) {3}"" +
+ ""var Foo = foo.Foo;"" +
+ ""/** @constructor */ Foo.Bar = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function expected(x) {}"",
+
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""foo.Foo = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function actual(x) {3}"" +
+ ""/** @constructor */ foo.Foo.Bar = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function expected(x) {}"");
+ verifyTypes();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testForwardJsDoc() {
+ testScoped(
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""foo.Foo = function() {};"" +
+ ""/** @param {Foo.Bar} x */ function actual(x) {3}"" +
+ ""var Foo = foo.Foo;"" +
+ ""/** @constructor */ Foo.Bar = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function expected(x) {}"",
+
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" */\n"" +
+ ""foo.Foo = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function actual(x) {3}"" +
+ ""/** @constructor */ foo.Foo.Bar = function() {};"" +
+ ""/** @param {foo.Foo.Bar} x */ function expected(x) {}"");
+ verifyTypes();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void moveMethods(Collection allNameInfo) {
+ boolean hasStubDeclaration = idGenerator.hasGeneratedAnyIds();
+ for (NameInfo nameInfo : allNameInfo) {
+ if (!nameInfo.isReferenced()) {
+ // The code below can't do anything with unreferenced name
+ // infos. They should be skipped to avoid NPE since their
+ // deepestCommonModuleRef is null.
+ continue;
+ }
+
+ if (nameInfo.readsClosureVariables()) {
+ continue;
+ }
+
+ JSModule deepestCommonModuleRef = nameInfo.getDeepestCommonModuleRef();
+ if (deepestCommonModuleRef == null) {
+ compiler.report(JSError.make(NULL_COMMON_MODULE_ERROR));
+ continue;
+ }
+
+ Iterator declarations =
+ nameInfo.getDeclarations().descendingIterator();
+ while (declarations.hasNext()) {
+ Symbol symbol = declarations.next();
+ if (!(symbol instanceof Property)) {
+ continue;
+ }
+ Property prop = (Property) symbol;
+
+ // We should only move a property across modules if:
+ // 1) We can move it deeper in the module graph, and
+ // 2) it's a function, and
+ // 3) it is not a get or a set, and
+ // 4) the class is available in the global scope.
+ //
+ // #1 should be obvious. #2 is more subtle. It's possible
+ // to copy off of a prototype, as in the code:
+ // for (var k in Foo.prototype) {
+ // doSomethingWith(Foo.prototype[k]);
+ // }
+ // This is a common way to implement pseudo-multiple inheritance in JS.
+ //
+ // So if we move a prototype method into a deeper module, we must
+ // replace it with a stub function so that it preserves its original
+ // behavior.
+
+ Node value = prop.getValue();
+ if (moduleGraph.dependsOn(deepestCommonModuleRef, prop.getModule()) &&
+ value.isFunction()) {
+ Node valueParent = value.getParent();
+ if (valueParent.isGetterDef()
+ || valueParent.isSetterDef()) {
+ // TODO(johnlenz): a GET or SET can't be deferred like a normal
+ // FUNCTION property definition as a mix-in would get the result
+ // of a GET instead of the function itself.
+ continue;
+ }
+ Node proto = prop.getPrototype();
+ int stubId = idGenerator.newId();
+
+ // example: JSCompiler_stubMethod(id);
+ Node stubCall = IR.call(
+ IR.name(STUB_METHOD_NAME),
+ IR.number(stubId))
+ .copyInformationFromForTree(value);
+ stubCall.putBooleanProp(Node.FREE_CALL, true);
+
+ // stub out the method in the original module
+ // A.prototype.b = JSCompiler_stubMethod(id);
+ valueParent.replaceChild(value, stubCall);
+
+ // unstub the function body in the deeper module
+ Node unstubParent = compiler.getNodeForCodeInsertion(
+ deepestCommonModuleRef);
+ Node unstubCall = IR.call(
+ IR.name(UNSTUB_METHOD_NAME),
+ IR.number(stubId),
+ value);
+ unstubCall.putBooleanProp(Node.FREE_CALL, true);
+ unstubParent.addChildToFront(
+ // A.prototype.b = JSCompiler_unstubMethod(id, body);
+ IR.exprResult(
+ IR.assign(
+ IR.getprop(
+ proto.cloneTree(),
+ IR.string(nameInfo.name)),
+ unstubCall))
+ .copyInformationFromForTree(value));
+
+ compiler.reportCodeChange();
+ }
+ }
+ }
+
+ if (!hasStubDeclaration && idGenerator.hasGeneratedAnyIds()) {
+ // Declare stub functions in the top-most module.
+ Node declarations = compiler.parseSyntheticCode(STUB_DECLARATIONS);
+ compiler.getNodeForCodeInsertion(null).addChildrenToFront(
+ declarations.removeChildren());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private ProcessProperties() {
+ symbolStack.push(new NameContext(globalNode));
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void enterScope(NodeTraversal t) {
+ symbolStack.peek().scope = t.getScope();
+ // NOTE(nicksantos): We use the same anonymous node for all
+ // functions that do not have reasonable names. I can't remember
+ // at the moment why we do this. I think it's because anonymous
+ // nodes can never have in-edges. They're just there as a placeholder
+ // for scope information, and do not matter in the edge propagation.
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void exitScope(NodeTraversal t) {
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
+ // Process prototype assignments to non-functions.
+ if (isPrototypePropertyAssign(n)) {
+ symbolStack.push(new NameContext(getNameInfoForName(
+ n.getFirstChild().getLastChild().getString(), PROPERTY)));
+ } else if (isGlobalFunctionDeclaration(t, n)) {
+ String name = parent.isName() ?
+ parent.getString() /* VAR */ :
+ n.getFirstChild().getString() /* named function */;
+ symbolStack.push(new NameContext(getNameInfoForName(name, VAR)));
+ } else if (n.isFunction()) {
+ symbolStack.push(new NameContext(anonymousNode));
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (n.isGetProp()) {
+ String propName = n.getFirstChild().getNext().getString();
+
+ if (propName.equals(""prototype"")) {
+ processPrototypeParent(t, parent);
+ } else if (compiler.getCodingConvention().isExported(propName)) {
+ addGlobalUseOfSymbol(propName, t.getModule(), PROPERTY);
+ } else {
+ // Do not mark prototype prop assigns as a 'use' in the global scope.
+ addSymbolUse(propName, t.getModule(), PROPERTY);
+ }
+
+ } else if (n.isObjectLit() &&
+ // Make sure that we're not handling object literals being
+ // assigned to a prototype, as in:
+ // Foo.prototype = {bar: 3, baz: 5};
+ !(parent.isAssign() &&
+ parent.getFirstChild().isGetProp() &&
+ parent.getFirstChild().getLastChild().getString().equals(
+ ""prototype""))) {
+
+ // var x = {a: 1, b: 2}
+ // should count as a use of property a and b.
+ for (Node propNameNode = n.getFirstChild(); propNameNode != null;
+ propNameNode = propNameNode.getNext()) {
+ // May be STRING, GET, or SET, but NUMBER isn't interesting.
+ if (!propNameNode.isQuotedString()) {
+ addSymbolUse(propNameNode.getString(), t.getModule(), PROPERTY);
+ }
+ }
+ } else if (n.isName()) {
+ String name = n.getString();
+
+ Var var = t.getScope().getVar(name);
+ if (var != null) {
+ // Only process global functions.
+ if (var.isGlobal()) {
+ if (var.getInitialValue() != null &&
+ var.getInitialValue().isFunction()) {
+ if (t.inGlobalScope()) {
+ if (!processGlobalFunctionDeclaration(t, n, parent,
+ parent.getParent())) {
+ addGlobalUseOfSymbol(name, t.getModule(), VAR);
+ }
+ } else {
+ addSymbolUse(name, t.getModule(), VAR);
+ }
+ }
+
+ // If it is not a global, it might be accessing a local of the outer
+ // scope. If that's the case the functions between the variable's
+ // declaring scope and the variable reference scope cannot be moved.
+ } else if (var.getScope() != t.getScope()){
+ for (int i = symbolStack.size() - 1; i >= 0; i--) {
+ NameContext context = symbolStack.get(i);
+ if (context.scope == var.getScope()) {
+ break;
+ }
+
+ context.name.readClosureVariables = true;
+ }
+ }
+ }
+ }
+
+ // Process prototype assignments to non-functions.
+ if (isPrototypePropertyAssign(n) ||
+ isGlobalFunctionDeclaration(t, n) ||
+ n.isFunction()) {
+ symbolStack.pop();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isGlobalFunctionDeclaration(NodeTraversal t, Node n) {
+ // Make sure we're either in the global scope, or the function
+ // we're looking at is the root of the current local scope.
+
+ return t.inGlobalScope() &&
+ (NodeUtil.isFunctionDeclaration(n) ||
+ n.isFunction() &&
+ n.getParent().isName());
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isPrototypePropertyAssign(Node assign) {
+ Node n = assign.getFirstChild();
+ if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)
+ && n.isGetProp()
+ && assign.getParent().isExprResult()) {
+ boolean isChainedProperty =
+ n.getFirstChild().isGetProp();
+
+ /**
+ * Returns the name of a prototype property being assigned to this r-value.
+ *
+ * Returns null if this is not the R-value of a prototype property, or if
+ * the R-value is used in multiple expressions (i.e., if there's
+ * a prototype property assignment in a more complex expression).
+ */
+ if (isChainedProperty) {
+ Node child = n.getFirstChild().getFirstChild().getNext();
+
+ if (child.isString() &&
+ child.getString().equals(""prototype"")) {
+ return true;
+ }
+ }
+ }
+
+
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean processGlobalFunctionDeclaration(NodeTraversal t,
+ Node nameNode, Node parent, Node gramps) {
+ Node firstChild = nameNode.getFirstChild();
+
+ if (// Check for a named FUNCTION.
+ isGlobalFunctionDeclaration(t, parent) ||
+ // Check for a VAR declaration.
+ firstChild != null &&
+ isGlobalFunctionDeclaration(t, firstChild)) {
+ String name = nameNode.getString();
+ getNameInfoForName(name, VAR).getDeclarations().add(
+ new GlobalFunction(nameNode, parent, gramps, t.getModule()));
+
+ // If the function name is exported, we should create an edge here
+ // so that it's never removed.
+ if (compiler.getCodingConvention().isExported(name) ||
+ anchorUnusedVars) {
+ addGlobalUseOfSymbol(name, t.getModule(), VAR);
+ }
+
+ return true;
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void processPrototypeParent(NodeTraversal t, Node n) {
+
+ switch (n.getType()) {
+ // Foo.prototype.getBar = function() { ... }
+ case Token.GETPROP:
+ Node dest = n.getFirstChild().getNext();
+ Node parent = n.getParent();
+ Node grandParent = parent.getParent();
+
+ if (dest.isString() &&
+ NodeUtil.isExprAssign(grandParent) &&
+ NodeUtil.isVarOrSimpleAssignLhs(n, parent)) {
+ String name = dest.getString();
+ Property prop = new AssignmentProperty(
+ grandParent,
+ t.getModule());
+ getNameInfoForName(name, PROPERTY).getDeclarations().add(prop);
+ }
+ break;
+
+ // Foo.prototype = { ""getBar"" : function() { ... } }
+ case Token.ASSIGN:
+ Node map = n.getFirstChild().getNext();
+ if (map.isObjectLit()) {
+ for (Node key = map.getFirstChild();
+ key != null; key = key.getNext()) {
+ // May be STRING, GET, or SET,
+ String name = key.getString();
+ Property prop = new LiteralProperty(
+ key, key.getFirstChild(), map, n,
+ t.getModule());
+ getNameInfoForName(name, PROPERTY).getDeclarations().add(prop);
+ }
+ }
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ GlobalFunction(Node nameNode, Node parent, Node gramps, JSModule module) {
+ Preconditions.checkState(
+ parent.isVar() ||
+ NodeUtil.isFunctionDeclaration(parent));
+ this.nameNode = nameNode;
+ this.module = module;
+ }
+
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ LiteralProperty(Node key, Node value, Node map, Node assign,
+ JSModule module) {
+ this.key = key;
+ this.value = value;
+ this.map = map;
+ this.assign = assign;
+ this.module = module;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ NameContext(NameInfo name) {
+ this.name = name;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue600b() {
+ testSame(
+ createModuleChain(
+ ""var jQuery1 = (function() {\n"" +
+ "" var jQuery2 = function() {};\n"" +
+ "" jQuery2.prototype = {\n"" +
+ "" size: function() {\n"" +
+ "" return 1;\n"" +
+ "" }\n"" +
+ "" };\n"" +
+ "" return jQuery2;\n"" +
+ ""})();\n"",
+
+ ""(function() {"" +
+ "" var div = jQuery1('div');"" +
+ "" div.size();"" +
+ ""})();""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean isSubtype(JSType other) {
+ if (!(other instanceof ArrowType)) {
+ return false;
+ }
+
+ ArrowType that = (ArrowType) other;
+
+ // This is described in Draft 2 of the ES4 spec,
+ // Section 3.4.7: Subtyping Function Types.
+
+ // this.returnType <: that.returnType (covariant)
+ if (!this.returnType.isSubtype(that.returnType)) {
+ return false;
+ }
+
+ // that.paramType[i] <: this.paramType[i] (contravariant)
+ //
+ // If this.paramType[i] is required,
+ // then that.paramType[i] is required.
+ //
+ // In theory, the ""required-ness"" should work in the other direction as
+ // well. In other words, if we have
+ //
+ // function f(number, number) {}
+ // function g(number) {}
+ //
+ // Then f *should* not be a subtype of g, and g *should* not be
+ // a subtype of f. But in practice, we do not implement it this way.
+ // We want to support the use case where you can pass g where f is
+ // expected, and pretend that g ignores the second argument.
+ // That way, you can have a single ""no-op"" function, and you don't have
+ // to create a new no-op function for every possible type signature.
+ //
+ // So, in this case, g < f, but f !< g
+ Node thisParam = parameters.getFirstChild();
+ Node thatParam = that.parameters.getFirstChild();
+ while (thisParam != null && thatParam != null) {
+ JSType thisParamType = thisParam.getJSType();
+ JSType thatParamType = thatParam.getJSType();
+ if (thisParamType != null) {
+ if (thatParamType == null ||
+ !thatParamType.isSubtype(thisParamType)) {
+ return false;
+ }
+ }
+
+ boolean thisIsVarArgs = thisParam.isVarArgs();
+ boolean thatIsVarArgs = thatParam.isVarArgs();
+
+ // ""that"" can't be a supertype, because it's missing a required argument.
+ // NOTE(nicksantos): In our type system, we use {function(...?)} and
+ // {function(...NoType)} to to indicate that arity should not be
+ // checked. Strictly speaking, this is not a correct formulation,
+ // because now a sub-function can required arguments that are var_args
+ // in the super-function. So we special-case this.
+
+ // don't advance if we have variable arguments
+ if (!thisIsVarArgs) {
+ thisParam = thisParam.getNext();
+ }
+ if (!thatIsVarArgs) {
+ thatParam = thatParam.getNext();
+ }
+
+ // both var_args indicates the end
+ if (thisIsVarArgs && thatIsVarArgs) {
+ thisParam = null;
+ thatParam = null;
+ }
+ }
+
+ // ""that"" can't be a supertype, because it's missing a required arguement.
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testMethodInference7() throws Exception {
+ testTypes(
+ ""/** @constructor */ function F() {}"" +
+ ""F.prototype.foo = function() { };"" +
+ ""/** @constructor \n * @extends {F} */ "" +
+ ""function G() {}"" +
+ ""/** @override */ G.prototype.foo = function(x, y) { };"",
+ ""mismatch of the foo property type and the type of the property "" +
+ ""it overrides from superclass F\n"" +
+ ""original: function (this:F): undefined\n"" +
+ ""override: function (this:G, ?, ?): undefined"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ RecordType(JSTypeRegistry registry, Map properties) {
+ super(registry, null, null);
+ setPrettyPrint(true);
+
+ for (String property : properties.keySet()) {
+ RecordProperty prop = properties.get(property);
+ if (prop == null) {
+ throw new IllegalStateException(
+ ""RecordProperty associated with a property should not be null!"");
+ }
+ defineDeclaredProperty(
+ property, prop.getType(), prop.getPropertyNode());
+ }
+
+ // Freeze the record type.
+ isFrozen = true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue725() throws Exception {
+ testTypes(
+ ""/** @typedef {{name: string}} */ var RecordType1;"" +
+ ""/** @typedef {{name2: string}} */ var RecordType2;"" +
+ ""/** @param {RecordType1} rec */ function f(rec) {"" +
+ "" alert(rec.name2);"" +
+ ""}"",
+ ""Property name2 never defined on rec"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JSType build() {
+ // If we have an empty record, simply return the object type.
+ if (isEmpty) {
+ return registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE);
+ }
+
+ return new RecordType(
+ registry, Collections.unmodifiableMap(properties));
+ }
+
+// Test Case
+[/INST]
+ public void testIssue725() throws Exception {
+ testTypes(
+ ""/** @typedef {{name: string}} */ var RecordType1;"" +
+ ""/** @typedef {{name2: string}} */ var RecordType2;"" +
+ ""/** @param {RecordType1} rec */ function f(rec) {"" +
+ "" alert(rec.name2);"" +
+ ""}"",
+ ""Property name2 never defined on rec"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ JSType getGreatestSubtypeHelper(JSType that) {
+ if (that.isRecordType()) {
+ RecordType thatRecord = that.toMaybeRecordType();
+ RecordTypeBuilder builder = new RecordTypeBuilder(registry);
+
+ // The greatest subtype consists of those *unique* properties of both
+ // record types. If any property conflicts, then the NO_TYPE type
+ // is returned.
+ for (String property : properties.keySet()) {
+ if (thatRecord.hasProperty(property) &&
+ !thatRecord.getPropertyType(property).isEquivalentTo(
+ getPropertyType(property))) {
+ return registry.getNativeObjectType(JSTypeNative.NO_TYPE);
+ }
+
+ builder.addProperty(property, getPropertyType(property),
+ getPropertyNode(property));
+ }
+
+ for (String property : thatRecord.properties.keySet()) {
+ if (!hasProperty(property)) {
+ builder.addProperty(property, thatRecord.getPropertyType(property),
+ thatRecord.getPropertyNode(property));
+ }
+ }
+
+ return builder.build();
+ }
+
+ JSType greatestSubtype = registry.getNativeType(
+ JSTypeNative.NO_OBJECT_TYPE);
+ JSType thatRestrictedToObj =
+ registry.getNativeType(JSTypeNative.OBJECT_TYPE)
+ .getGreatestSubtype(that);
+ if (!thatRestrictedToObj.isEmptyType()) {
+ // In this branch, the other type is some object type. We find
+ // the greatest subtype with the following algorithm:
+ // 1) For each property ""x"" of this record type, take the union
+ // of all classes with a property ""x"" with a compatible property type.
+ // and which are a subtype of {@code that}.
+ // 2) Take the intersection of all of these unions.
+ for (Map.Entry entry : properties.entrySet()) {
+ String propName = entry.getKey();
+ JSType propType = entry.getValue();
+ UnionTypeBuilder builder = new UnionTypeBuilder(registry);
+ for (ObjectType alt :
+ registry.getEachReferenceTypeWithProperty(propName)) {
+ JSType altPropType = alt.getPropertyType(propName);
+ if (altPropType != null && !alt.isEquivalentTo(this) &&
+ alt.isSubtype(that) &&
+ (propType.isUnknownType() || altPropType.isUnknownType() ||
+ altPropType.isEquivalentTo(propType))) {
+ builder.addAlternate(alt);
+ }
+ }
+ greatestSubtype = greatestSubtype.getLeastSupertype(builder.build());
+ }
+ }
+ return greatestSubtype;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue725() throws Exception {
+ testTypes(
+ ""/** @typedef {{name: string}} */ var RecordType1;"" +
+ ""/** @typedef {{name2: string}} */ var RecordType2;"" +
+ ""/** @param {RecordType1} rec */ function f(rec) {"" +
+ "" alert(rec.name2);"" +
+ ""}"",
+ ""Property name2 never defined on rec"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean canPropertyBeDefined(JSType type, String propertyName) {
+ if (typesIndexedByProperty.containsKey(propertyName)) {
+ for (JSType alt :
+ typesIndexedByProperty.get(propertyName).getAlternates()) {
+ JSType greatestSubtype = alt.getGreatestSubtype(type);
+ if (!greatestSubtype.isEmptyType()) {
+ // We've found a type with this property. Now we just have to make
+ // sure it's not a type used for internal bookkeeping.
+
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue725() throws Exception {
+ testTypes(
+ ""/** @typedef {{name: string}} */ var RecordType1;"" +
+ ""/** @typedef {{name2: string}} */ var RecordType2;"" +
+ ""/** @param {RecordType1} rec */ function f(rec) {"" +
+ "" alert(rec.name2);"" +
+ ""}"",
+ ""Property name2 never defined on rec"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testIssue725() throws Exception {
+ testTypes(
+ ""/** @typedef {{name: string}} */ var RecordType1;"" +
+ ""/** @typedef {{name2: string}} */ var RecordType2;"" +
+ ""/** @param {RecordType1} rec */ function f(rec) {"" +
+ "" alert(rec.name2);"" +
+ ""}"",
+ ""Property name2 never defined on rec"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void matchConstraint(JSType constraint) {
+ // We only want to match constraints on anonymous types.
+ if (hasReferenceName()) {
+ return;
+ }
+
+ // Handle the case where the constraint object is a record type.
+ //
+ // param constraint {{prop: (number|undefined)}}
+ // function f(constraint) {}
+ // f({});
+ //
+ // We want to modify the object literal to match the constraint, by
+ // taking any each property on the record and trying to match
+ // properties on this object.
+ if (constraint.isRecordType()) {
+ matchRecordTypeConstraint(constraint.toObjectType());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testRecordInference() {
+ inFunction(
+ ""/** @param {{a: (boolean|undefined)}|{b: (string|undefined)}} x */"" +
+ ""function f(x) {}"" +
+ ""var out = {};"" +
+ ""f(out);"");
+ assertEquals(""{a: (boolean|undefined), b: (string|undefined)}"",
+ getType(""out"").toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope caseEquality(Node left, Node right, FlowScope blindScope,
+ Function merging) {
+ // left type
+ JSType leftType = getTypeIfRefinable(left, blindScope);
+ boolean leftIsRefineable;
+ if (leftType != null) {
+ leftIsRefineable = true;
+ } else {
+ leftIsRefineable = false;
+ leftType = left.getJSType();
+ }
+
+ // right type
+ JSType rightType = getTypeIfRefinable(right, blindScope);
+ boolean rightIsRefineable;
+ if (rightType != null) {
+ rightIsRefineable = true;
+ } else {
+ rightIsRefineable = false;
+ rightType = right.getJSType();
+ }
+
+ // merged types
+ TypePair merged = merging.apply(new TypePair(leftType, rightType));
+
+ // creating new scope
+ if (merged != null) {
+ return maybeRestrictTwoNames(
+ blindScope,
+ left, leftIsRefineable, merged.typeA,
+ right, rightIsRefineable, merged.typeB);
+ }
+ return blindScope;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue783() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var Type = function () {"" +
+ "" /** @type {Type} */"" +
+ "" this.me_ = this;"" +
+ ""};"" +
+ ""Type.prototype.doIt = function() {"" +
+ "" var me = this.me_;"" +
+ "" for (var i = 0; i < me.unknownProp; i++) {}"" +
+ ""};"",
+ ""Property unknownProp never defined on Type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope caseAndOrNotShortCircuiting(Node left, Node right,
+ FlowScope blindScope, boolean condition) {
+ // left type
+ JSType leftType = getTypeIfRefinable(left, blindScope);
+ boolean leftIsRefineable;
+ if (leftType != null) {
+ leftIsRefineable = true;
+ } else {
+ leftIsRefineable = false;
+ leftType = left.getJSType();
+ blindScope = firstPreciserScopeKnowingConditionOutcome(
+ left, blindScope, condition);
+ }
+
+ // restricting left type
+ JSType restrictedLeftType = (leftType == null) ? null :
+ leftType.getRestrictedTypeGivenToBooleanOutcome(condition);
+ if (restrictedLeftType == null) {
+ return firstPreciserScopeKnowingConditionOutcome(
+ right, blindScope, condition);
+ }
+
+ // right type
+ JSType rightType = getTypeIfRefinable(right, blindScope);
+ boolean rightIsRefineable;
+ if (rightType != null) {
+ rightIsRefineable = true;
+ } else {
+ rightIsRefineable = false;
+ rightType = right.getJSType();
+ blindScope = firstPreciserScopeKnowingConditionOutcome(
+ right, blindScope, condition);
+ }
+
+ if (condition) {
+ JSType restrictedRightType = (rightType == null) ? null :
+ rightType.getRestrictedTypeGivenToBooleanOutcome(condition);
+
+ // creating new scope
+ return maybeRestrictTwoNames(
+ blindScope,
+ left, leftIsRefineable, restrictedLeftType,
+ right, rightIsRefineable, restrictedRightType);
+ }
+ return blindScope;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue783() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var Type = function () {"" +
+ "" /** @type {Type} */"" +
+ "" this.me_ = this;"" +
+ ""};"" +
+ ""Type.prototype.doIt = function() {"" +
+ "" var me = this.me_;"" +
+ "" for (var i = 0; i < me.unknownProp; i++) {}"" +
+ ""};"",
+ ""Property unknownProp never defined on Type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope maybeRestrictName(
+ FlowScope blindScope, Node node, JSType originalType, JSType restrictedType) {
+ if (restrictedType != null && !restrictedType.equals(originalType)) {
+ FlowScope informed = blindScope.createChildFlowScope();
+ declareNameInScope(informed, node, restrictedType);
+ return informed;
+ }
+ return blindScope;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue783() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var Type = function () {"" +
+ "" /** @type {Type} */"" +
+ "" this.me_ = this;"" +
+ ""};"" +
+ ""Type.prototype.doIt = function() {"" +
+ "" var me = this.me_;"" +
+ "" for (var i = 0; i < me.unknownProp; i++) {}"" +
+ ""};"",
+ ""Property unknownProp never defined on Type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope maybeRestrictTwoNames(
+ FlowScope blindScope,
+ Node left, boolean leftIsRefineable, JSType restrictedLeftType,
+ Node right, boolean rightIsRefineable, JSType restrictedRightType) {
+ boolean shouldRefineLeft =
+ leftIsRefineable && restrictedLeftType != null;
+ boolean shouldRefineRight =
+ rightIsRefineable && restrictedRightType != null;
+ if (shouldRefineLeft || shouldRefineRight) {
+ FlowScope informed = blindScope.createChildFlowScope();
+ if (shouldRefineLeft) {
+ declareNameInScope(informed, left, restrictedLeftType);
+ }
+ if (shouldRefineRight) {
+ declareNameInScope(informed, right, restrictedRightType);
+ }
+ return informed;
+ }
+ return blindScope;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue783() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var Type = function () {"" +
+ "" /** @type {Type} */"" +
+ "" this.me_ = this;"" +
+ ""};"" +
+ ""Type.prototype.doIt = function() {"" +
+ "" var me = this.me_;"" +
+ "" for (var i = 0; i < me.unknownProp; i++) {}"" +
+ ""};"",
+ ""Property unknownProp never defined on Type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope caseNameOrGetProp(Node name, FlowScope blindScope,
+ boolean outcome) {
+ JSType type = getTypeIfRefinable(name, blindScope);
+ if (type != null) {
+ JSType restrictedType =
+ type.getRestrictedTypeGivenToBooleanOutcome(outcome);
+ FlowScope informed = blindScope.createChildFlowScope();
+ declareNameInScope(informed, name, restrictedType);
+ return informed;
+ }
+ return blindScope;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue783() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var Type = function () {"" +
+ "" /** @type {Type} */"" +
+ "" this.me_ = this;"" +
+ ""};"" +
+ ""Type.prototype.doIt = function() {"" +
+ "" var me = this.me_;"" +
+ "" for (var i = 0; i < me.unknownProp; i++) {}"" +
+ ""};"",
+ ""Property unknownProp never defined on Type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JSType getRestrictedTypeGivenToBooleanOutcome(boolean outcome) {
+
+ BooleanLiteralSet literals = getPossibleToBooleanOutcomes();
+ if (literals.contains(outcome)) {
+ return this;
+ } else {
+ return getNativeType(JSTypeNative.NO_TYPE);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue783() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var Type = function () {"" +
+ "" /** @type {Type} */"" +
+ "" this.me_ = this;"" +
+ ""};"" +
+ ""Type.prototype.doIt = function() {"" +
+ "" var me = this.me_;"" +
+ "" for (var i = 0; i < me.unknownProp; i++) {}"" +
+ ""};"",
+ ""Property unknownProp never defined on Type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override public void visit(NodeTraversal t, Node n, Node parent) {
+ if (t.inGlobalScope()) {
+ return;
+ }
+
+ if (n.isReturn() && n.getFirstChild() != null) {
+ data.get(t.getScopeRoot()).recordNonEmptyReturn();
+ }
+
+ if (t.getScopeDepth() <= 2) {
+ // The first-order function analyzer looks at two types of variables:
+ //
+ // 1) Local variables that are assigned in inner scopes (""escaped vars"")
+ //
+ // 2) Local variables that are assigned more than once.
+ //
+ // We treat all global variables as escaped by default, so there's
+ // no reason to do this extra computation for them.
+ return;
+ }
+
+ if (n.isName() && NodeUtil.isLValue(n) &&
+ // Be careful of bleeding functions, which create variables
+ // in the inner scope, not the scope where the name appears.
+ !NodeUtil.isBleedingFunctionName(n)) {
+ String name = n.getString();
+ Scope scope = t.getScope();
+ Var var = scope.getVar(name);
+ if (var != null) {
+ Scope ownerScope = var.getScope();
+ if (ownerScope.isLocal()) {
+ data.get(ownerScope.getRootNode()).recordAssignedName(name);
+ }
+
+ if (scope != ownerScope && ownerScope.isLocal()) {
+ data.get(ownerScope.getRootNode()).recordEscapedVarName(name);
+ }
+ }
+ } else if (n.isGetProp() && n.isUnscopedQualifiedName() &&
+ NodeUtil.isLValue(n)) {
+ String name = NodeUtil.getRootOfQualifiedName(n).getString();
+ Scope scope = t.getScope();
+ Var var = scope.getVar(name);
+ if (var != null) {
+ Scope ownerScope = var.getScope();
+ if (scope != ownerScope && ownerScope.isLocal()) {
+ data.get(ownerScope.getRootNode())
+ .recordEscapedQualifiedName(n.getQualifiedName());
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue726() throws Exception {
+ testTypes(
+ ""/** @constructor */ function Foo() {}"" +
+ ""/** @param {number} x */ Foo.prototype.bar = function(x) {};"" +
+ ""/** @return {!Function} */ "" +
+ ""Foo.prototype.getDeferredBar = function() { "" +
+ "" var self = this;"" +
+ "" return function() {"" +
+ "" self.bar(true);"" +
+ "" };"" +
+ ""};"",
+ ""actual parameter 1 of Foo.prototype.bar does not match formal parameter\n"" +
+ ""found : boolean\n"" +
+ ""required: number"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean checkRecordEquivalenceHelper(
+ RecordType otherRecord, boolean tolerateUnknowns) {
+ Set keySet = properties.keySet();
+ Map otherProps = otherRecord.properties;
+ if (!otherProps.keySet().equals(keySet)) {
+ return false;
+ }
+ for (String key : keySet) {
+ if (!otherProps.get(key).checkEquivalenceHelper(
+ properties.get(key), tolerateUnknowns)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ JSType getGreatestSubtypeHelper(JSType that) {
+ if (that.isRecordType()) {
+ RecordType thatRecord = that.toMaybeRecordType();
+ RecordTypeBuilder builder = new RecordTypeBuilder(registry);
+ builder.setSynthesized(true);
+
+ // The greatest subtype consists of those *unique* properties of both
+ // record types. If any property conflicts, then the NO_TYPE type
+ // is returned.
+ for (String property : properties.keySet()) {
+ if (thatRecord.hasProperty(property) &&
+ !thatRecord.getPropertyType(property).isInvariant(
+ getPropertyType(property))) {
+ return registry.getNativeObjectType(JSTypeNative.NO_TYPE);
+ }
+
+ builder.addProperty(property, getPropertyType(property),
+ getPropertyNode(property));
+ }
+
+ for (String property : thatRecord.properties.keySet()) {
+ if (!hasProperty(property)) {
+ builder.addProperty(property, thatRecord.getPropertyType(property),
+ thatRecord.getPropertyNode(property));
+ }
+ }
+
+ return builder.build();
+ }
+
+ JSType greatestSubtype = registry.getNativeType(
+ JSTypeNative.NO_OBJECT_TYPE);
+ JSType thatRestrictedToObj =
+ registry.getNativeType(JSTypeNative.OBJECT_TYPE)
+ .getGreatestSubtype(that);
+ if (!thatRestrictedToObj.isEmptyType()) {
+ // In this branch, the other type is some object type. We find
+ // the greatest subtype with the following algorithm:
+ // 1) For each property ""x"" of this record type, take the union
+ // of all classes with a property ""x"" with a compatible property type.
+ // and which are a subtype of {@code that}.
+ // 2) Take the intersection of all of these unions.
+ for (Map.Entry entry : properties.entrySet()) {
+ String propName = entry.getKey();
+ JSType propType = entry.getValue();
+ UnionTypeBuilder builder = new UnionTypeBuilder(registry);
+ for (ObjectType alt :
+ registry.getEachReferenceTypeWithProperty(propName)) {
+ JSType altPropType = alt.getPropertyType(propName);
+ if (altPropType != null && !alt.isEquivalentTo(this) &&
+ alt.isSubtype(that) &&
+ (propType.isUnknownType() || altPropType.isUnknownType() ||
+ altPropType.isEquivalentTo(propType))) {
+ builder.addAlternate(alt);
+ }
+ }
+ greatestSubtype = greatestSubtype.getLeastSupertype(builder.build());
+ }
+ }
+ return greatestSubtype;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean hasEqualParameters(ArrowType that, boolean tolerateUnknowns) {
+ Node thisParam = parameters.getFirstChild();
+ Node otherParam = that.parameters.getFirstChild();
+ while (thisParam != null && otherParam != null) {
+ JSType thisParamType = thisParam.getJSType();
+ JSType otherParamType = otherParam.getJSType();
+ if (thisParamType != null) {
+ // Both parameter lists give a type for this param, it should be equal
+ if (otherParamType != null &&
+ !thisParamType.checkEquivalenceHelper(
+ otherParamType, tolerateUnknowns)) {
+ return false;
+ }
+ } else {
+ if (otherParamType != null) {
+ return false;
+ }
+ }
+ thisParam = thisParam.getNext();
+ otherParam = otherParam.getNext();
+ }
+ // One of the parameters is null, so the types are only equal if both
+ // parameter lists are null (they are equal).
+ return thisParam == otherParam;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean checkArrowEquivalenceHelper(
+ ArrowType that, boolean tolerateUnknowns) {
+ // Please keep this method in sync with the hashCode() method below.
+ if (!returnType.checkEquivalenceHelper(that.returnType, tolerateUnknowns)) {
+ return false;
+ }
+ return hasEqualParameters(that, tolerateUnknowns);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean isSubtype(ObjectType typeA, RecordType typeB) {
+ // typeA is a subtype of record type typeB iff:
+ // 1) typeA has all the properties declared in typeB.
+ // 2) And for each property of typeB,
+ // 2a) if the property of typeA is declared, it must be equal
+ // to the type of the property of typeB,
+ // 2b) otherwise, it must be a subtype of the property of typeB.
+ //
+ // To figure out why this is true, consider the following pseudo-code:
+ // /** @type {{a: (Object,null)}} */ var x;
+ // /** @type {{a: !Object}} */ var y;
+ // var z = {a: {}};
+ // x.a = null;
+ //
+ // y cannot be assigned to x, because line 4 would violate y's declared
+ // properties. But z can be assigned to x. Even though z and y are the
+ // same type, the properties of z are inferred--and so an assignment
+ // to the property of z would not violate any restrictions on it.
+ for (String property : typeB.properties.keySet()) {
+ if (!typeA.hasProperty(property)) {
+ return false;
+ }
+
+ JSType propA = typeA.getPropertyType(property);
+ JSType propB = typeB.getPropertyType(property);
+ if (!propA.isUnknownType() && !propB.isUnknownType()) {
+ if (typeA.isPropertyTypeDeclared(property)) {
+ // If one declared property isn't invariant,
+ // then the whole record isn't covariant.
+ if (!propA.isInvariant(propB)) {
+ return false;
+ }
+ } else {
+ // If one inferred property isn't a subtype,
+ // then the whole record isn't covariant.
+ if (!propA.isSubtype(propB)) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean checkUnionEquivalenceHelper(
+ UnionType that, boolean tolerateUnknowns) {
+ if (!tolerateUnknowns
+ && alternates.size() != that.alternates.size()) {
+ return false;
+ }
+ for (JSType alternate : that.alternates) {
+ if (!hasAlternate(alternate, tolerateUnknowns)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean hasAlternate(JSType type, boolean tolerateUnknowns) {
+ for (JSType alternate : alternates) {
+ if (alternate.checkEquivalenceHelper(type, tolerateUnknowns)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final boolean isEquivalentTo(JSType that) {
+ return checkEquivalenceHelper(that, false);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final boolean isInvariant(JSType that) {
+ return checkEquivalenceHelper(that, false);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final boolean differsFrom(JSType that) {
+ return !checkEquivalenceHelper(that, true);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean checkEquivalenceHelper(JSType that, boolean tolerateUnknowns) {
+ if (this == that) {
+ return true;
+ }
+
+ boolean thisUnknown = isUnknownType();
+ boolean thatUnknown = that.isUnknownType();
+ if (thisUnknown || thatUnknown) {
+ if (tolerateUnknowns) {
+ // If we're checking for invariance, the unknown type is invariant
+ // with everyone.
+ // If we're checking data flow, then two types are the same if they're
+ // both unknown.
+ return thisUnknown && thatUnknown;
+ } else if (thisUnknown && thatUnknown &&
+ (isNominalType() ^ that.isNominalType())) {
+ // If they're both unknown, but one is a nominal type and the other
+ // is not, then we should fail out immediately. This ensures that
+ // we won't unbox the unknowns further down.
+ return false;
+ }
+ }
+
+ if (isUnionType() && that.isUnionType()) {
+ return this.toMaybeUnionType().checkUnionEquivalenceHelper(
+ that.toMaybeUnionType(), tolerateUnknowns);
+ }
+
+ if (isFunctionType() && that.isFunctionType()) {
+ return this.toMaybeFunctionType().checkFunctionEquivalenceHelper(
+ that.toMaybeFunctionType(), tolerateUnknowns);
+ }
+
+ if (isRecordType() && that.isRecordType()) {
+ return this.toMaybeRecordType().checkRecordEquivalenceHelper(
+ that.toMaybeRecordType(), tolerateUnknowns);
+ }
+
+ ParameterizedType thisParamType = toMaybeParameterizedType();
+ ParameterizedType thatParamType = that.toMaybeParameterizedType();
+ if (thisParamType != null || thatParamType != null) {
+ // Check if one type is parameterized, but the other is not.
+ boolean paramsMatch = false;
+ if (thisParamType != null && thatParamType != null) {
+ paramsMatch = thisParamType.getParameterType().checkEquivalenceHelper(
+ thatParamType.getParameterType(), tolerateUnknowns);
+ } else if (tolerateUnknowns) {
+ // If one of the type parameters is unknown, but the other is not,
+ // then we consider these the same for the purposes of data flow
+ // and invariance.
+ paramsMatch = true;
+ } else {
+ paramsMatch = false;
+ }
+
+ JSType thisRootType = thisParamType == null ?
+ this : thisParamType.getReferencedTypeInternal();
+ JSType thatRootType = thatParamType == null ?
+ that : thatParamType.getReferencedTypeInternal();
+ return paramsMatch &&
+ thisRootType.checkEquivalenceHelper(thatRootType, tolerateUnknowns);
+ }
+
+ if (isNominalType() && that.isNominalType()) {
+ return toObjectType().getReferenceName().equals(
+ that.toObjectType().getReferenceName());
+ }
+
+ // Unbox other proxies.
+ if (this instanceof ProxyObjectType) {
+ return ((ProxyObjectType) this)
+ .getReferencedTypeInternal().checkEquivalenceHelper(
+ that, tolerateUnknowns);
+ }
+
+ if (that instanceof ProxyObjectType) {
+ return checkEquivalenceHelper(
+ ((ProxyObjectType) that).getReferencedTypeInternal(),
+ tolerateUnknowns);
+ }
+
+ // Relies on the fact that for the base {@link JSType}, only one
+ // instance of each sub-type will ever be created in a given registry, so
+ // there is no need to verify members. If the object pointers are not
+ // identical, then the type member must be different.
+ return this == that;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FunctionType tryMergeFunctionPiecewise(
+ FunctionType other, boolean leastSuper) {
+ Node newParamsNode = null;
+ if (call.hasEqualParameters(other.call, false)) {
+ newParamsNode = call.parameters;
+ } else {
+ // If the parameters are not equal, don't try to merge them.
+ // Someday, we should try to merge the individual params.
+ return null;
+ }
+
+ JSType newReturnType = leastSuper ?
+ call.returnType.getLeastSupertype(other.call.returnType) :
+ call.returnType.getGreatestSubtype(other.call.returnType);
+
+ ObjectType newTypeOfThis = null;
+ if (isEquivalent(typeOfThis, other.typeOfThis)) {
+ newTypeOfThis = typeOfThis;
+ } else {
+ JSType maybeNewTypeOfThis = leastSuper ?
+ typeOfThis.getLeastSupertype(other.typeOfThis) :
+ typeOfThis.getGreatestSubtype(other.typeOfThis);
+ if (maybeNewTypeOfThis instanceof ObjectType) {
+ newTypeOfThis = (ObjectType) maybeNewTypeOfThis;
+ } else {
+ newTypeOfThis = leastSuper ?
+ registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE) :
+ registry.getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE);
+ }
+ }
+
+ boolean newReturnTypeInferred =
+ call.returnTypeInferred || other.call.returnTypeInferred;
+
+ return new FunctionType(
+ registry, null, null,
+ new ArrowType(
+ registry, newParamsNode, newReturnType, newReturnTypeInferred),
+ newTypeOfThis, null, false, false);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean checkFunctionEquivalenceHelper(
+ FunctionType that, boolean tolerateUnknowns) {
+ if (isConstructor()) {
+ if (that.isConstructor()) {
+ return this == that;
+ }
+ return false;
+ }
+ if (isInterface()) {
+ if (that.isInterface()) {
+ return getReferenceName().equals(that.getReferenceName());
+ }
+ return false;
+ }
+ if (that.isInterface()) {
+ return false;
+ }
+
+ return typeOfThis.checkEquivalenceHelper(
+ that.typeOfThis, tolerateUnknowns) &&
+ call.checkArrowEquivalenceHelper(that.call, tolerateUnknowns);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean hasEqualCallType(FunctionType otherType) {
+ return this.call.checkArrowEquivalenceHelper(otherType.call, false);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testIssue791() throws Exception {
+ testTypes(
+ ""/** @param {{func: function()}} obj */"" +
+ ""function test1(obj) {}"" +
+ ""var fnStruc1 = {};"" +
+ ""fnStruc1.func = function() {};"" +
+ ""test1(fnStruc1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JSType getDeclaredType(String sourceName, JSDocInfo info,
+ Node lValue, @Nullable Node rValue) {
+ if (info != null && info.hasType()) {
+ return getDeclaredTypeInAnnotation(sourceName, lValue, info);
+ } else if (rValue != null && rValue.isFunction() &&
+ shouldUseFunctionLiteralType(
+ JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) {
+ return rValue.getJSType();
+ } else if (info != null) {
+ if (info.hasEnumParameterType()) {
+ if (rValue != null && rValue.isObjectLit()) {
+ return rValue.getJSType();
+ } else {
+ return createEnumTypeFromNodes(
+ rValue, lValue.getQualifiedName(), info, lValue);
+ }
+ } else if (info.isConstructor() || info.isInterface()) {
+ return createFunctionTypeFromNodes(
+ rValue, lValue.getQualifiedName(), info, lValue);
+ } else {
+ // Check if this is constant, and if it has a known type.
+ if (info.isConstant()) {
+ JSType knownType = null;
+ if (rValue != null) {
+ if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) {
+ // If rValue has a type-cast, we use the type in the type-cast.
+ // If rValue's type was already computed during scope creation,
+ // then we can safely use that.
+ return rValue.getJSType();
+ } else if (rValue.isOr()) {
+ // Check for a very specific JS idiom:
+ // var x = x || TYPE;
+ // This is used by Closure's base namespace for esoteric
+ // reasons.
+ Node firstClause = rValue.getFirstChild();
+ Node secondClause = firstClause.getNext();
+ boolean namesMatch = firstClause.isName()
+ && lValue.isName()
+ && firstClause.getString().equals(lValue.getString());
+ if (namesMatch && secondClause.getJSType() != null
+ && !secondClause.getJSType().isUnknownType()) {
+ return secondClause.getJSType();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return getDeclaredTypeInAnnotation(sourceName, lValue, info);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue688() throws Exception {
+ testTypes(
+ ""/** @const */ var SOME_DEFAULT =\n"" +
+ "" /** @type {TwoNumbers} */ ({first: 1, second: 2});\n"" +
+ ""/**\n"" +
+ ""* Class defining an interface with two numbers.\n"" +
+ ""* @interface\n"" +
+ ""*/\n"" +
+ ""function TwoNumbers() {}\n"" +
+ ""/** @type number */\n"" +
+ ""TwoNumbers.prototype.first;\n"" +
+ ""/** @type number */\n"" +
+ ""TwoNumbers.prototype.second;\n"" +
+ ""/** @return {number} */ function f() { return SOME_DEFAULT; }"",
+ ""inconsistent return type\n"" +
+ ""found : (TwoNumbers|null)\n"" +
+ ""required: number"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void getNumUseInUseCfgNode(final Node cfgNode) {
+
+ numUsesWithinCfgNode = 0;
+ AbstractCfgNodeTraversalCallback gatherCb =
+ new AbstractCfgNodeTraversalCallback() {
+
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (n.isName() && n.getString().equals(varName) &&
+ // We make a special exception when the entire cfgNode is a chain
+ // of assignments, since in that case the assignment statements
+ // will happen after the inlining of the right hand side.
+ // TODO(blickly): Make the SIDE_EFFECT_PREDICATE check more exact
+ // and remove this special case.
+ !(parent.isAssign() &&
+ (parent.getFirstChild() == n))) {
+ // Don't count lhs of top-level assignment chain
+ numUsesWithinCfgNode++;
+ }
+ }
+
+ };
+
+ NodeTraversal.traverse(compiler, cfgNode, gatherCb);
+ }
+
+// Test Case
+[/INST]
+ public void testVarAssinInsideHookIssue965() {
+ noInline(""var i = 0; return 1 ? (i = 5) : 0, i;"");
+ noInline(""var i = 0; return (1 ? (i = 5) : 0) ? i : 0;"");
+ noInline(""var i = 0; return (1 ? (i = 5) : 0) || i;"");
+ noInline(""var i = 0; return (1 ? (i = 5) : 0) * i;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope traverseObjectLiteral(Node n, FlowScope scope) {
+ JSType type = n.getJSType();
+ Preconditions.checkNotNull(type);
+
+ for (Node name = n.getFirstChild(); name != null; name = name.getNext()) {
+ scope = traverse(name.getFirstChild(), scope);
+ }
+
+ // Object literals can be reflected on other types.
+ // See CodingConvention#getObjectLiteralCase and goog.object.reflect.
+ // Ignore these types of literals.
+ ObjectType objectType = ObjectType.cast(type);
+ if (objectType == null) {
+ return scope;
+ }
+ boolean hasLendsName = n.getJSDocInfo() != null &&
+ n.getJSDocInfo().getLendsName() != null;
+ if (objectType.hasReferenceName() && !hasLendsName) {
+ return scope;
+ }
+
+ String qObjName = NodeUtil.getBestLValueName(
+ NodeUtil.getBestLValue(n));
+ for (Node name = n.getFirstChild(); name != null;
+ name = name.getNext()) {
+ String memberName = NodeUtil.getObjectLitKeyName(name);
+ if (memberName != null) {
+ JSType rawValueType = name.getFirstChild().getJSType();
+ JSType valueType = NodeUtil.getObjectLitKeyTypeFromValueType(
+ name, rawValueType);
+ if (valueType == null) {
+ valueType = unknownType;
+ }
+ objectType.defineInferredProperty(memberName, valueType, name);
+
+ // Do normal flow inference if this is a direct property assignment.
+ if (qObjName != null && name.isStringKey()) {
+ String qKeyName = qObjName + ""."" + memberName;
+ Var var = syntacticScope.getVar(qKeyName);
+ JSType oldType = var == null ? null : var.getType();
+ if (var != null && var.isTypeInferred()) {
+ var.setType(oldType == null ?
+ valueType : oldType.getLeastSupertype(oldType));
+ }
+
+ scope.inferQualifiedSlot(name, qKeyName,
+ oldType == null ? unknownType : oldType,
+ valueType);
+ }
+ } else {
+ n.setJSType(unknownType);
+ }
+ }
+ return scope;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1023() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""function F() {}"" +
+ ""(function () {"" +
+ "" F.prototype = {"" +
+ "" /** @param {string} x */"" +
+ "" bar: function (x) { }"" +
+ "" };"" +
+ ""})();"" +
+ ""(new F()).bar(true)"",
+ ""actual parameter 1 of F.prototype.bar does not match formal parameter\n"" +
+ ""found : boolean\n"" +
+ ""required: string"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isQualifiedNameInferred(
+ String qName, Node n, JSDocInfo info,
+ Node rhsValue, JSType valueType) {
+ if (valueType == null) {
+ return true;
+ }
+
+ // Prototype sets are always declared.
+
+ boolean inferred = true;
+ if (info != null) {
+ inferred = !(info.hasType()
+ || info.hasEnumParameterType()
+ || (isConstantSymbol(info, n) && valueType != null
+ && !valueType.isUnknownType())
+ || FunctionTypeBuilder.isFunctionTypeDeclaration(info));
+ }
+
+ if (inferred && rhsValue != null && rhsValue.isFunction()) {
+ if (info != null) {
+ return false;
+ } else if (!scope.isDeclared(qName, false) &&
+ n.isUnscopedQualifiedName()) {
+
+ // Check if this is in a conditional block.
+ // Functions assigned in conditional blocks are inferred.
+ for (Node current = n.getParent();
+ !(current.isScript() || current.isFunction());
+ current = current.getParent()) {
+ if (NodeUtil.isControlStructure(current)) {
+ return true;
+ }
+ }
+
+ // Check if this is assigned in an inner scope.
+ // Functions assigned in inner scopes are inferred.
+ AstFunctionContents contents =
+ getFunctionAnalysisResults(scope.getRootNode());
+ if (contents == null ||
+ !contents.getEscapedQualifiedNames().contains(qName)) {
+ return false;
+ }
+ }
+ }
+ return inferred;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1023() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""function F() {}"" +
+ ""(function () {"" +
+ "" F.prototype = {"" +
+ "" /** @param {string} x */"" +
+ "" bar: function (x) { }"" +
+ "" };"" +
+ ""})();"" +
+ ""(new F()).bar(true)"",
+ ""actual parameter 1 of F.prototype.bar does not match formal parameter\n"" +
+ ""found : boolean\n"" +
+ ""required: string"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isQualifiedNameInferred(
+ String qName, Node n, JSDocInfo info,
+ Node rhsValue, JSType valueType) {
+ if (valueType == null) {
+ return true;
+ }
+
+ // Prototypes of constructors and interfaces are always declared.
+ if (qName != null && qName.endsWith("".prototype"")) {
+ return false;
+ }
+
+ boolean inferred = true;
+ if (info != null) {
+ inferred = !(info.hasType()
+ || info.hasEnumParameterType()
+ || (isConstantSymbol(info, n) && valueType != null
+ && !valueType.isUnknownType())
+ || FunctionTypeBuilder.isFunctionTypeDeclaration(info));
+ }
+
+ if (inferred && rhsValue != null && rhsValue.isFunction()) {
+ if (info != null) {
+ return false;
+ } else if (!scope.isDeclared(qName, false) &&
+ n.isUnscopedQualifiedName()) {
+
+ // Check if this is in a conditional block.
+ // Functions assigned in conditional blocks are inferred.
+ for (Node current = n.getParent();
+ !(current.isScript() || current.isFunction());
+ current = current.getParent()) {
+ if (NodeUtil.isControlStructure(current)) {
+ return true;
+ }
+ }
+
+ // Check if this is assigned in an inner scope.
+ // Functions assigned in inner scopes are inferred.
+ AstFunctionContents contents =
+ getFunctionAnalysisResults(scope.getRootNode());
+ if (contents == null ||
+ !contents.getEscapedQualifiedNames().contains(qName)) {
+ return false;
+ }
+ }
+ }
+ return inferred;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1024() throws Exception {
+ testTypes(
+ ""/** @param {Object} a */\n"" +
+ ""function f(a) {\n"" +
+ "" a.prototype = '__proto'\n"" +
+ ""}\n"" +
+ ""/** @param {Object} b\n"" +
+ "" * @return {!Object}\n"" +
+ "" */\n"" +
+ ""function g(b) {\n"" +
+ "" return b.prototype\n"" +
+ ""}\n"");
+ /* TODO(blickly): Make this warning go away.
+ * This is old behavior, but it doesn't make sense to warn about since
+ * both assignments are inferred.
+ */
+ testTypes(
+ ""/** @param {Object} a */\n"" +
+ ""function f(a) {\n"" +
+ "" a.prototype = {foo:3};\n"" +
+ ""}\n"" +
+ ""/** @param {Object} b\n"" +
+ "" */\n"" +
+ ""function g(b) {\n"" +
+ "" b.prototype = function(){};\n"" +
+ ""}\n"",
+ ""assignment to property prototype of Object\n"" +
+ ""found : {foo: number}\n"" +
+ ""required: function (): undefined"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ @SuppressWarnings(""fallthrough"")
+ public Node optimizeSubtree(Node node) {
+ switch(node.getType()) {
+ case Token.TRUE:
+ case Token.FALSE:
+ return reduceTrueFalse(node);
+
+ case Token.NEW:
+ node = tryFoldStandardConstructors(node);
+ if (!node.isCall()) {
+ return node;
+ }
+ // Fall through on purpose because tryFoldStandardConstructors() may
+ // convert a NEW node into a CALL node
+ case Token.CALL:
+ Node result = tryFoldLiteralConstructor(node);
+ if (result == node) {
+ result = tryFoldSimpleFunctionCall(node);
+ if (result == node) {
+ result = tryFoldImmediateCallToBoundFunction(node);
+ }
+ }
+ return result;
+
+ case Token.RETURN:
+ return tryReduceReturn(node);
+
+ case Token.COMMA:
+ return trySplitComma(node);
+
+ case Token.NAME:
+ return tryReplaceUndefined(node);
+
+ case Token.ARRAYLIT:
+ return tryMinimizeArrayLiteral(node);
+
+
+ default:
+ return node; //Nothing changed
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPrint() {
+ assertPrint(""10 + a + b"", ""10+a+b"");
+ assertPrint(""10 + (30*50)"", ""10+30*50"");
+ assertPrint(""with(x) { x + 3; }"", ""with(x)x+3"");
+ assertPrint(""\""aa'a\"""", ""\""aa'a\"""");
+ assertPrint(""\""aa\\\""a\"""", ""'aa\""a'"");
+ assertPrint(""function foo()\n{return 10;}"", ""function foo(){return 10}"");
+ assertPrint(""a instanceof b"", ""a instanceof b"");
+ assertPrint(""typeof(a)"", ""typeof a"");
+ assertPrint(
+ ""var foo = x ? { a : 1 } : {a: 3, b:4, \""default\"": 5, \""foo-bar\"": 6}"",
+ ""var foo=x?{a:1}:{a:3,b:4,\""default\"":5,\""foo-bar\"":6}"");
+
+ // Safari: needs ';' at the end of a throw statement
+ assertPrint(""function foo(){throw 'error';}"",
+ ""function foo(){throw\""error\"";}"");
+ // Safari 3 needs a ""{"" around a single function
+ assertPrint(""if (true) function foo(){return}"",
+ ""if(true){function foo(){return}}"");
+
+ assertPrint(""var x = 10; { var y = 20; }"", ""var x=10;var y=20"");
+
+ assertPrint(""while (x-- > 0);"", ""while(x-- >0);"");
+ assertPrint(""x-- >> 1"", ""x-- >>1"");
+
+ assertPrint(""(function () {})(); "",
+ ""(function(){})()"");
+
+ // Associativity
+ assertPrint(""var a,b,c,d;a || (b&& c) && (a || d)"",
+ ""var a,b,c,d;a||b&&c&&(a||d)"");
+ assertPrint(""var a,b,c; a || (b || c); a * (b * c); a | (b | c)"",
+ ""var a,b,c;a||(b||c);a*(b*c);a|(b|c)"");
+ assertPrint(""var a,b,c; a / b / c;a / (b / c); a - (b - c);"",
+ ""var a,b,c;a/b/c;a/(b/c);a-(b-c)"");
+
+ // Nested assignments
+ assertPrint(""var a,b; a = b = 3;"",
+ ""var a,b;a=b=3"");
+ assertPrint(""var a,b,c,d; a = (b = c = (d = 3));"",
+ ""var a,b,c,d;a=b=c=d=3"");
+ assertPrint(""var a,b,c; a += (b = c += 3);"",
+ ""var a,b,c;a+=b=c+=3"");
+ assertPrint(""var a,b,c; a *= (b -= c);"",
+ ""var a,b,c;a*=b-=c"");
+
+ // Precedence
+ assertPrint(""a ? delete b[0] : 3"", ""a?delete b[0]:3"");
+ assertPrint(""(delete a[0])/10"", ""delete a[0]/10"");
+
+ // optional '()' for new
+
+ // simple new
+ assertPrint(""new A"", ""new A"");
+ assertPrint(""new A()"", ""new A"");
+ assertPrint(""new A('x')"", ""new A(\""x\"")"");
+
+ // calling instance method directly after new
+ assertPrint(""new A().a()"", ""(new A).a()"");
+ assertPrint(""(new A).a()"", ""(new A).a()"");
+
+ // this case should be fixed
+ assertPrint(""new A('y').a()"", ""(new A(\""y\"")).a()"");
+
+ // internal class
+ assertPrint(""new A.B"", ""new A.B"");
+ assertPrint(""new A.B()"", ""new A.B"");
+ assertPrint(""new A.B('z')"", ""new A.B(\""z\"")"");
+
+ // calling instance method directly after new internal class
+ assertPrint(""(new A.B).a()"", ""(new A.B).a()"");
+ assertPrint(""new A.B().a()"", ""(new A.B).a()"");
+ // this case should be fixed
+ assertPrint(""new A.B('w').a()"", ""(new A.B(\""w\"")).a()"");
+
+ // Operators: make sure we don't convert binary + and unary + into ++
+ assertPrint(""x + +y"", ""x+ +y"");
+ assertPrint(""x - (-y)"", ""x- -y"");
+ assertPrint(""x++ +y"", ""x++ +y"");
+ assertPrint(""x-- -y"", ""x-- -y"");
+ assertPrint(""x++ -y"", ""x++-y"");
+
+ // Label
+ assertPrint(""foo:for(;;){break foo;}"", ""foo:for(;;)break foo"");
+ assertPrint(""foo:while(1){continue foo;}"", ""foo:while(1)continue foo"");
+
+ // Object literals.
+ assertPrint(""({})"", ""({})"");
+ assertPrint(""var x = {};"", ""var x={}"");
+ assertPrint(""({}).x"", ""({}).x"");
+ assertPrint(""({})['x']"", ""({})[\""x\""]"");
+ assertPrint(""({}) instanceof Object"", ""({})instanceof Object"");
+ assertPrint(""({}) || 1"", ""({})||1"");
+ assertPrint(""1 || ({})"", ""1||{}"");
+ assertPrint(""({}) ? 1 : 2"", ""({})?1:2"");
+ assertPrint(""0 ? ({}) : 2"", ""0?{}:2"");
+ assertPrint(""0 ? 1 : ({})"", ""0?1:{}"");
+ assertPrint(""typeof ({})"", ""typeof{}"");
+ assertPrint(""f({})"", ""f({})"");
+
+ // Anonymous function expressions.
+ assertPrint(""(function(){})"", ""(function(){})"");
+ assertPrint(""(function(){})()"", ""(function(){})()"");
+ assertPrint(""(function(){})instanceof Object"",
+ ""(function(){})instanceof Object"");
+ assertPrint(""(function(){}).bind().call()"",
+ ""(function(){}).bind().call()"");
+ assertPrint(""var x = function() { };"", ""var x=function(){}"");
+ assertPrint(""var x = function() { }();"", ""var x=function(){}()"");
+ assertPrint(""(function() {}), 2"", ""(function(){}),2"");
+
+ // Name functions expression.
+ assertPrint(""(function f(){})"", ""(function f(){})"");
+
+ // Function declaration.
+ assertPrint(""function f(){}"", ""function f(){}"");
+
+ // Make sure we don't treat non-Latin character escapes as raw strings.
+ assertPrint(""({ 'a': 4, '\\u0100': 4 })"", ""({\""a\"":4,\""\\u0100\"":4})"");
+ assertPrint(""({ a: 4, '\\u0100': 4 })"", ""({a:4,\""\\u0100\"":4})"");
+
+ // Test if statement and for statements with single statements in body.
+ assertPrint(""if (true) { alert();}"", ""if(true)alert()"");
+ assertPrint(""if (false) {} else {alert(\""a\"");}"",
+ ""if(false);else alert(\""a\"")"");
+ assertPrint(""for(;;) { alert();};"", ""for(;;)alert()"");
+
+ assertPrint(""do { alert(); } while(true);"",
+ ""do alert();while(true)"");
+ assertPrint(""myLabel: { alert();}"",
+ ""myLabel:alert()"");
+ assertPrint(""myLabel: for(;;) continue myLabel;"",
+ ""myLabel:for(;;)continue myLabel"");
+
+ // Test nested var statement
+ assertPrint(""if (true) var x; x = 4;"", ""if(true)var x;x=4"");
+
+ // Non-latin identifier. Make sure we keep them escaped.
+ assertPrint(""\\u00fb"", ""\\u00fb"");
+ assertPrint(""\\u00fa=1"", ""\\u00fa=1"");
+ assertPrint(""function \\u00f9(){}"", ""function \\u00f9(){}"");
+ assertPrint(""x.\\u00f8"", ""x.\\u00f8"");
+ assertPrint(""x.\\u00f8"", ""x.\\u00f8"");
+ assertPrint(""abc\\u4e00\\u4e01jkl"", ""abc\\u4e00\\u4e01jkl"");
+
+ // Test the right-associative unary operators for spurious parens
+ assertPrint(""! ! true"", ""!!true"");
+ assertPrint(""!(!(true))"", ""!!true"");
+ assertPrint(""typeof(void(0))"", ""typeof void 0"");
+ assertPrint(""typeof(void(!0))"", ""typeof void!0"");
+ assertPrint(""+ - + + - + 3"", ""+-+ +-+3""); // chained unary plus/minus
+ assertPrint(""+(--x)"", ""+--x"");
+ assertPrint(""-(++x)"", ""-++x"");
+
+ // needs a space to prevent an ambiguous parse
+ assertPrint(""-(--x)"", ""- --x"");
+ assertPrint(""!(~~5)"", ""!~~5"");
+ assertPrint(""~(a/b)"", ""~(a/b)"");
+
+ // Preserve parens to overcome greedy binding of NEW
+ assertPrint(""new (foo.bar()).factory(baz)"", ""new (foo.bar().factory)(baz)"");
+ assertPrint(""new (bar()).factory(baz)"", ""new (bar().factory)(baz)"");
+ assertPrint(""new (new foobar(x)).factory(baz)"",
+ ""new (new foobar(x)).factory(baz)"");
+
+ // Make sure that HOOK is right associative
+ assertPrint(""a ? b : (c ? d : e)"", ""a?b:c?d:e"");
+ assertPrint(""a ? (b ? c : d) : e"", ""a?b?c:d:e"");
+ assertPrint(""(a ? b : c) ? d : e"", ""(a?b:c)?d:e"");
+
+ // Test nested ifs
+ assertPrint(""if (x) if (y); else;"", ""if(x)if(y);else;"");
+
+ // Test comma.
+ assertPrint(""a,b,c"", ""a,b,c"");
+ assertPrint(""(a,b),c"", ""a,b,c"");
+ assertPrint(""a,(b,c)"", ""a,b,c"");
+ assertPrint(""x=a,b,c"", ""x=a,b,c"");
+ assertPrint(""x=(a,b),c"", ""x=(a,b),c"");
+ assertPrint(""x=a,(b,c)"", ""x=a,b,c"");
+ assertPrint(""x=a,y=b,z=c"", ""x=a,y=b,z=c"");
+ assertPrint(""x=(a,y=b,z=c)"", ""x=(a,y=b,z=c)"");
+ assertPrint(""x=[a,b,c,d]"", ""x=[a,b,c,d]"");
+ assertPrint(""x=[(a,b,c),d]"", ""x=[(a,b,c),d]"");
+ assertPrint(""x=[(a,(b,c)),d]"", ""x=[(a,b,c),d]"");
+ assertPrint(""x=[a,(b,c,d)]"", ""x=[a,(b,c,d)]"");
+ assertPrint(""var x=(a,b)"", ""var x=(a,b)"");
+ assertPrint(""var x=a,b,c"", ""var x=a,b,c"");
+ assertPrint(""var x=(a,b),c"", ""var x=(a,b),c"");
+ assertPrint(""var x=a,b=(c,d)"", ""var x=a,b=(c,d)"");
+ assertPrint(""foo(a,b,c,d)"", ""foo(a,b,c,d)"");
+ assertPrint(""foo((a,b,c),d)"", ""foo((a,b,c),d)"");
+ assertPrint(""foo((a,(b,c)),d)"", ""foo((a,b,c),d)"");
+ assertPrint(""f(a+b,(c,d,(e,f,g)))"", ""f(a+b,(c,d,e,f,g))"");
+ assertPrint(""({}) , 1 , 2"", ""({}),1,2"");
+ assertPrint(""({}) , {} , {}"", ""({}),{},{}"");
+
+ // EMPTY nodes
+ assertPrint(""if (x){}"", ""if(x);"");
+ assertPrint(""if(x);"", ""if(x);"");
+ assertPrint(""if(x)if(y);"", ""if(x)if(y);"");
+ assertPrint(""if(x){if(y);}"", ""if(x)if(y);"");
+ assertPrint(""if(x){if(y){};;;}"", ""if(x)if(y);"");
+ assertPrint(""if(x){;;function y(){};;}"", ""if(x){function y(){}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void add(Node n, Context context) {
+ if (!cc.continueProcessing()) {
+ return;
+ }
+
+ int type = n.getType();
+ String opstr = NodeUtil.opToStr(type);
+ int childCount = n.getChildCount();
+ Node first = n.getFirstChild();
+ Node last = n.getLastChild();
+
+ // Handle all binary operators
+ if (opstr != null && first != last) {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad binary operator \""%s\"": expected 2 arguments but got %s"",
+ opstr, childCount);
+ int p = NodeUtil.precedence(type);
+
+ // For right-hand-side of operations, only pass context if it's
+ // the IN_FOR_INIT_CLAUSE one.
+ Context rhsContext = getContextForNoInOperator(context);
+
+ if (last.getType() == type &&
+ NodeUtil.isAssociative(type)) {
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p, rhsContext);
+ } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {
+ // Assignments are the only right-associative binary operators
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p, rhsContext);
+ } else {
+ unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1);
+ }
+ return;
+ }
+
+ cc.startSourceMapping(n);
+
+ switch (type) {
+ case Token.TRY: {
+ Preconditions.checkState(first.getNext().isBlock() &&
+ !first.getNext().hasMoreThanOneChild());
+ Preconditions.checkState(childCount >= 2 && childCount <= 3);
+
+ add(""try"");
+ add(first, Context.PRESERVE_BLOCK);
+
+ // second child contains the catch block, or nothing if there
+ // isn't a catch block
+ Node catchblock = first.getNext().getFirstChild();
+ if (catchblock != null) {
+ add(catchblock);
+ }
+
+ if (childCount == 3) {
+ add(""finally"");
+ add(last, Context.PRESERVE_BLOCK);
+ }
+ break;
+ }
+
+ case Token.CATCH:
+ Preconditions.checkState(childCount == 2);
+ add(""catch("");
+ add(first);
+ add("")"");
+ add(last, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.THROW:
+ Preconditions.checkState(childCount == 1);
+ add(""throw"");
+ add(first);
+
+ // Must have a ';' after a throw statement, otherwise safari can't
+ // parse this.
+ cc.endStatement(true);
+ break;
+
+ case Token.RETURN:
+ add(""return"");
+ if (childCount == 1) {
+ add(first);
+ } else {
+ Preconditions.checkState(childCount == 0);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.VAR:
+ if (first != null) {
+ add(""var "");
+ addList(first, false, getContextForNoInOperator(context));
+ }
+ break;
+
+ case Token.LABEL_NAME:
+ Preconditions.checkState(!n.getString().isEmpty());
+ addIdentifier(n.getString());
+ break;
+
+ case Token.NAME:
+ if (first == null || first.isEmpty()) {
+ addIdentifier(n.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ addIdentifier(n.getString());
+ cc.addOp(""="", true);
+ if (first.isComma()) {
+ addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);
+ } else {
+ // Add expression, consider nearby code at lowest level of
+ // precedence.
+ addExpr(first, 0, getContextForNoInOperator(context));
+ }
+ }
+ break;
+
+ case Token.ARRAYLIT:
+ add(""["");
+ addArrayList(first);
+ add(""]"");
+ break;
+
+ case Token.PARAM_LIST:
+ add(""("");
+ addList(first);
+ add("")"");
+ break;
+
+ case Token.COMMA:
+ Preconditions.checkState(childCount == 2);
+ unrollBinaryOperator(n, Token.COMMA, "","", context,
+ getContextForNoInOperator(context), 0, 0);
+ break;
+
+ case Token.NUMBER:
+ Preconditions.checkState(childCount == 0);
+ cc.addNumber(n.getDouble());
+ break;
+
+ case Token.TYPEOF:
+ case Token.VOID:
+ case Token.NOT:
+ case Token.BITNOT:
+ case Token.POS: {
+ // All of these unary operators are right-associative
+ Preconditions.checkState(childCount == 1);
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type), Context.OTHER);
+ break;
+ }
+
+ case Token.NEG: {
+ Preconditions.checkState(childCount == 1);
+
+ // It's important to our sanity checker that the code
+ // we print produces the same AST as the code we parse back.
+ // NEG is a weird case because Rhino parses ""- -2"" as ""2"".
+ if (n.getFirstChild().isNumber()) {
+ cc.addNumber(-n.getFirstChild().getDouble());
+ } else {
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type), Context.OTHER);
+ }
+
+ break;
+ }
+
+ case Token.HOOK: {
+ Preconditions.checkState(childCount == 3);
+ int p = NodeUtil.precedence(type);
+ Context rhsContext = getContextForNoInOperator(context);
+ addExpr(first, p + 1, context);
+ cc.addOp(""?"", true);
+ addExpr(first.getNext(), 1, rhsContext);
+ cc.addOp("":"", true);
+ addExpr(last, 1, rhsContext);
+ break;
+ }
+
+ case Token.REGEXP:
+ if (!first.isString() ||
+ !last.isString()) {
+ throw new Error(""Expected children to be strings"");
+ }
+
+ String regexp = regexpEscape(first.getString(), outputCharsetEncoder);
+
+ // I only use one .add because whitespace matters
+ if (childCount == 2) {
+ add(regexp + last.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ add(regexp);
+ }
+ break;
+
+ case Token.FUNCTION:
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ Preconditions.checkState(childCount == 3);
+ boolean funcNeedsParens = (context == Context.START_OF_EXPR);
+ if (funcNeedsParens) {
+ add(""("");
+ }
+
+ add(""function"");
+ add(first);
+
+ add(first.getNext());
+ add(last, Context.PRESERVE_BLOCK);
+ cc.endFunction(context == Context.STATEMENT);
+
+ if (funcNeedsParens) {
+ add("")"");
+ }
+ break;
+
+ case Token.GETTER_DEF:
+ case Token.SETTER_DEF:
+ Preconditions.checkState(n.getParent().isObjectLit());
+ Preconditions.checkState(childCount == 1);
+ Preconditions.checkState(first.isFunction());
+
+ // Get methods are unnamed
+ Preconditions.checkState(first.getFirstChild().getString().isEmpty());
+ if (type == Token.GETTER_DEF) {
+ // Get methods have no parameters.
+ Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());
+ add(""get "");
+ } else {
+ // Set methods have one parameter.
+ Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());
+ add(""set "");
+ }
+
+ // The name is on the GET or SET node.
+ String name = n.getString();
+ Node fn = first;
+ Node parameters = fn.getChildAtIndex(1);
+ Node body = fn.getLastChild();
+
+ // Add the property name.
+ if (!n.isQuotedString() &&
+ TokenStream.isJSIdentifier(name) &&
+ // do not encode literally any non-literal characters that were
+ // Unicode escaped.
+ NodeUtil.isLatin(name)) {
+ add(name);
+ } else {
+ // Determine if the string is a simple number.
+ double d = getSimpleNumber(name);
+ if (!Double.isNaN(d)) {
+ cc.addNumber(d);
+ } else {
+ addJsString(n);
+ }
+ }
+
+ add(parameters);
+ add(body, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.SCRIPT:
+ case Token.BLOCK: {
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ boolean preserveBlock = context == Context.PRESERVE_BLOCK;
+ if (preserveBlock) {
+ cc.beginBlock();
+ }
+
+ boolean preferLineBreaks =
+ type == Token.SCRIPT ||
+ (type == Token.BLOCK &&
+ !preserveBlock &&
+ n.getParent() != null &&
+ n.getParent().isScript());
+ for (Node c = first; c != null; c = c.getNext()) {
+ add(c, Context.STATEMENT);
+
+ // VAR doesn't include ';' since it gets used in expressions
+ if (c.isVar()) {
+ cc.endStatement();
+ }
+
+ if (c.isFunction()) {
+ cc.maybeLineBreak();
+ }
+
+ // Prefer to break lines in between top-level statements
+ // because top-level statements are more homogeneous.
+ if (preferLineBreaks) {
+ cc.notePreferredLineBreak();
+ }
+ }
+ if (preserveBlock) {
+ cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
+ }
+ break;
+ }
+
+ case Token.FOR:
+ if (childCount == 4) {
+ add(""for("");
+ if (first.isVar()) {
+ add(first, Context.IN_FOR_INIT_CLAUSE);
+ } else {
+ addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);
+ }
+ add("";"");
+ add(first.getNext());
+ add("";"");
+ add(first.getNext().getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ Preconditions.checkState(childCount == 3);
+ add(""for("");
+ add(first);
+ add(""in"");
+ add(first.getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ }
+ break;
+
+ case Token.DO:
+ Preconditions.checkState(childCount == 2);
+ add(""do"");
+ addNonEmptyStatement(first, Context.OTHER, false);
+ add(""while("");
+ add(last);
+ add("")"");
+ cc.endStatement();
+ break;
+
+ case Token.WHILE:
+ Preconditions.checkState(childCount == 2);
+ add(""while("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.EMPTY:
+ Preconditions.checkState(childCount == 0);
+ break;
+
+ case Token.GETPROP: {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETPROP: expected 2 children, but got %s"", childCount);
+ Preconditions.checkState(
+ last.isString(),
+ ""Bad GETPROP: RHS should be STRING"");
+ boolean needsParens = (first.isNumber());
+ if (needsParens) {
+ add(""("");
+ }
+ addExpr(first, NodeUtil.precedence(type), context);
+ if (needsParens) {
+ add("")"");
+ }
+ if (this.languageMode == LanguageMode.ECMASCRIPT3
+ && TokenStream.isKeyword(last.getString())) {
+ // Check for ECMASCRIPT3 keywords.
+ add(""["");
+ add(last);
+ add(""]"");
+ } else {
+ add(""."");
+ addIdentifier(last.getString());
+ }
+ break;
+ }
+
+ case Token.GETELEM:
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETELEM: expected 2 children but got %s"", childCount);
+ addExpr(first, NodeUtil.precedence(type), context);
+ add(""["");
+ add(first.getNext());
+ add(""]"");
+ break;
+
+ case Token.WITH:
+ Preconditions.checkState(childCount == 2);
+ add(""with("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.INC:
+ case Token.DEC: {
+ Preconditions.checkState(childCount == 1);
+ String o = type == Token.INC ? ""++"" : ""--"";
+ int postProp = n.getIntProp(Node.INCRDECR_PROP);
+ // A non-zero post-prop value indicates a post inc/dec, default of zero
+ // is a pre-inc/dec.
+ if (postProp != 0) {
+ addExpr(first, NodeUtil.precedence(type), context);
+ cc.addOp(o, false);
+ } else {
+ cc.addOp(o, false);
+ add(first);
+ }
+ break;
+ }
+
+ case Token.CALL:
+ // We have two special cases here:
+ // 1) If the left hand side of the call is a direct reference to eval,
+ // then it must have a DIRECT_EVAL annotation. If it does not, then
+ // that means it was originally an indirect call to eval, and that
+ // indirectness must be preserved.
+ // 2) If the left hand side of the call is a property reference,
+ // then the call must not a FREE_CALL annotation. If it does, then
+ // that means it was originally an call without an explicit this and
+ // that must be preserved.
+ if (isIndirectEval(first)
+ || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {
+ add(""(0,"");
+ addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);
+ add("")"");
+ } else {
+ addExpr(first, NodeUtil.precedence(type), context);
+ }
+ add(""("");
+ addList(first.getNext());
+ add("")"");
+ break;
+
+ case Token.IF:
+ boolean hasElse = childCount == 3;
+ boolean ambiguousElseClause =
+ context == Context.BEFORE_DANGLING_ELSE && !hasElse;
+ if (ambiguousElseClause) {
+ cc.beginBlock();
+ }
+
+ add(""if("");
+ add(first);
+ add("")"");
+
+ if (hasElse) {
+ addNonEmptyStatement(
+ first.getNext(), Context.BEFORE_DANGLING_ELSE, false);
+ add(""else"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ addNonEmptyStatement(first.getNext(), Context.OTHER, false);
+ Preconditions.checkState(childCount == 2);
+ }
+
+ if (ambiguousElseClause) {
+ cc.endBlock();
+ }
+ break;
+
+ case Token.NULL:
+ Preconditions.checkState(childCount == 0);
+ cc.addConstant(""null"");
+ break;
+
+ case Token.THIS:
+ Preconditions.checkState(childCount == 0);
+ add(""this"");
+ break;
+
+ case Token.FALSE:
+ Preconditions.checkState(childCount == 0);
+ cc.addConstant(""false"");
+ break;
+
+ case Token.TRUE:
+ Preconditions.checkState(childCount == 0);
+ cc.addConstant(""true"");
+ break;
+
+ case Token.CONTINUE:
+ Preconditions.checkState(childCount <= 1);
+ add(""continue"");
+ if (childCount == 1) {
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.DEBUGGER:
+ Preconditions.checkState(childCount == 0);
+ add(""debugger"");
+ cc.endStatement();
+ break;
+
+ case Token.BREAK:
+ Preconditions.checkState(childCount <= 1);
+ add(""break"");
+ if (childCount == 1) {
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.EXPR_RESULT:
+ Preconditions.checkState(childCount == 1);
+ add(first, Context.START_OF_EXPR);
+ cc.endStatement();
+ break;
+
+ case Token.NEW:
+ add(""new "");
+ int precedence = NodeUtil.precedence(type);
+
+ // If the first child contains a CALL, then claim higher precedence
+ // to force parentheses. Otherwise, when parsed, NEW will bind to the
+ // first viable parentheses (don't traverse into functions).
+ if (NodeUtil.containsType(
+ first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {
+ precedence = NodeUtil.precedence(first.getType()) + 1;
+ }
+ addExpr(first, precedence, Context.OTHER);
+
+ // '()' is optional when no arguments are present
+ Node next = first.getNext();
+ if (next != null) {
+ add(""("");
+ addList(next);
+ add("")"");
+ }
+ break;
+
+ case Token.STRING_KEY:
+ Preconditions.checkState(
+ childCount == 1, ""Object lit key must have 1 child"");
+ addJsString(n);
+ break;
+
+ case Token.STRING:
+ Preconditions.checkState(
+ childCount == 0, ""A string may not have children"");
+ addJsString(n);
+ break;
+
+ case Token.DELPROP:
+ Preconditions.checkState(childCount == 1);
+ add(""delete "");
+ add(first);
+ break;
+
+ case Token.OBJECTLIT: {
+ boolean needsParens = (context == Context.START_OF_EXPR);
+ if (needsParens) {
+ add(""("");
+ }
+ add(""{"");
+ for (Node c = first; c != null; c = c.getNext()) {
+ if (c != first) {
+ cc.listSeparator();
+ }
+
+ if (c.isGetterDef() || c.isSetterDef()) {
+ add(c);
+ } else {
+ Preconditions.checkState(c.isStringKey());
+ String key = c.getString();
+ // Object literal property names don't have to be quoted if they
+ // are not JavaScript keywords
+ if (!c.isQuotedString()
+ && !(languageMode == LanguageMode.ECMASCRIPT3
+ && TokenStream.isKeyword(key))
+ && TokenStream.isJSIdentifier(key)
+ // do not encode literally any non-literal characters that
+ // were Unicode escaped.
+ && NodeUtil.isLatin(key)) {
+ add(key);
+ } else {
+ // Determine if the string is a simple number.
+ double d = getSimpleNumber(key);
+ if (!Double.isNaN(d)) {
+ cc.addNumber(d);
+ } else {
+ addExpr(c, 1, Context.OTHER);
+ }
+ }
+ add("":"");
+ addExpr(c.getFirstChild(), 1, Context.OTHER);
+ }
+ }
+ add(""}"");
+ if (needsParens) {
+ add("")"");
+ }
+ break;
+ }
+
+ case Token.SWITCH:
+ add(""switch("");
+ add(first);
+ add("")"");
+ cc.beginBlock();
+ addAllSiblings(first.getNext());
+ cc.endBlock(context == Context.STATEMENT);
+ break;
+
+ case Token.CASE:
+ Preconditions.checkState(childCount == 2);
+ add(""case "");
+ add(first);
+ addCaseBody(last);
+ break;
+
+ case Token.DEFAULT_CASE:
+ Preconditions.checkState(childCount == 1);
+ add(""default"");
+ addCaseBody(first);
+ break;
+
+ case Token.LABEL:
+ Preconditions.checkState(childCount == 2);
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add(first);
+ add("":"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), true);
+ break;
+
+ case Token.CAST:
+ add(""("");
+ add(first);
+ add("")"");
+ break;
+
+ default:
+ throw new Error(""Unknown type "" + type + ""\n"" + n.toStringTree());
+ }
+
+ cc.endSourceMapping(n);
+ }
+
+// Test Case
+[/INST]
+ public void testPrint() {
+ assertPrint(""10 + a + b"", ""10+a+b"");
+ assertPrint(""10 + (30*50)"", ""10+30*50"");
+ assertPrint(""with(x) { x + 3; }"", ""with(x)x+3"");
+ assertPrint(""\""aa'a\"""", ""\""aa'a\"""");
+ assertPrint(""\""aa\\\""a\"""", ""'aa\""a'"");
+ assertPrint(""function foo()\n{return 10;}"", ""function foo(){return 10}"");
+ assertPrint(""a instanceof b"", ""a instanceof b"");
+ assertPrint(""typeof(a)"", ""typeof a"");
+ assertPrint(
+ ""var foo = x ? { a : 1 } : {a: 3, b:4, \""default\"": 5, \""foo-bar\"": 6}"",
+ ""var foo=x?{a:1}:{a:3,b:4,\""default\"":5,\""foo-bar\"":6}"");
+
+ // Safari: needs ';' at the end of a throw statement
+ assertPrint(""function foo(){throw 'error';}"",
+ ""function foo(){throw\""error\"";}"");
+ // Safari 3 needs a ""{"" around a single function
+ assertPrint(""if (true) function foo(){return}"",
+ ""if(true){function foo(){return}}"");
+
+ assertPrint(""var x = 10; { var y = 20; }"", ""var x=10;var y=20"");
+
+ assertPrint(""while (x-- > 0);"", ""while(x-- >0);"");
+ assertPrint(""x-- >> 1"", ""x-- >>1"");
+
+ assertPrint(""(function () {})(); "",
+ ""(function(){})()"");
+
+ // Associativity
+ assertPrint(""var a,b,c,d;a || (b&& c) && (a || d)"",
+ ""var a,b,c,d;a||b&&c&&(a||d)"");
+ assertPrint(""var a,b,c; a || (b || c); a * (b * c); a | (b | c)"",
+ ""var a,b,c;a||(b||c);a*(b*c);a|(b|c)"");
+ assertPrint(""var a,b,c; a / b / c;a / (b / c); a - (b - c);"",
+ ""var a,b,c;a/b/c;a/(b/c);a-(b-c)"");
+
+ // Nested assignments
+ assertPrint(""var a,b; a = b = 3;"",
+ ""var a,b;a=b=3"");
+ assertPrint(""var a,b,c,d; a = (b = c = (d = 3));"",
+ ""var a,b,c,d;a=b=c=d=3"");
+ assertPrint(""var a,b,c; a += (b = c += 3);"",
+ ""var a,b,c;a+=b=c+=3"");
+ assertPrint(""var a,b,c; a *= (b -= c);"",
+ ""var a,b,c;a*=b-=c"");
+
+ // Precedence
+ assertPrint(""a ? delete b[0] : 3"", ""a?delete b[0]:3"");
+ assertPrint(""(delete a[0])/10"", ""delete a[0]/10"");
+
+ // optional '()' for new
+
+ // simple new
+ assertPrint(""new A"", ""new A"");
+ assertPrint(""new A()"", ""new A"");
+ assertPrint(""new A('x')"", ""new A(\""x\"")"");
+
+ // calling instance method directly after new
+ assertPrint(""new A().a()"", ""(new A).a()"");
+ assertPrint(""(new A).a()"", ""(new A).a()"");
+
+ // this case should be fixed
+ assertPrint(""new A('y').a()"", ""(new A(\""y\"")).a()"");
+
+ // internal class
+ assertPrint(""new A.B"", ""new A.B"");
+ assertPrint(""new A.B()"", ""new A.B"");
+ assertPrint(""new A.B('z')"", ""new A.B(\""z\"")"");
+
+ // calling instance method directly after new internal class
+ assertPrint(""(new A.B).a()"", ""(new A.B).a()"");
+ assertPrint(""new A.B().a()"", ""(new A.B).a()"");
+ // this case should be fixed
+ assertPrint(""new A.B('w').a()"", ""(new A.B(\""w\"")).a()"");
+
+ // Operators: make sure we don't convert binary + and unary + into ++
+ assertPrint(""x + +y"", ""x+ +y"");
+ assertPrint(""x - (-y)"", ""x- -y"");
+ assertPrint(""x++ +y"", ""x++ +y"");
+ assertPrint(""x-- -y"", ""x-- -y"");
+ assertPrint(""x++ -y"", ""x++-y"");
+
+ // Label
+ assertPrint(""foo:for(;;){break foo;}"", ""foo:for(;;)break foo"");
+ assertPrint(""foo:while(1){continue foo;}"", ""foo:while(1)continue foo"");
+
+ // Object literals.
+ assertPrint(""({})"", ""({})"");
+ assertPrint(""var x = {};"", ""var x={}"");
+ assertPrint(""({}).x"", ""({}).x"");
+ assertPrint(""({})['x']"", ""({})[\""x\""]"");
+ assertPrint(""({}) instanceof Object"", ""({})instanceof Object"");
+ assertPrint(""({}) || 1"", ""({})||1"");
+ assertPrint(""1 || ({})"", ""1||{}"");
+ assertPrint(""({}) ? 1 : 2"", ""({})?1:2"");
+ assertPrint(""0 ? ({}) : 2"", ""0?{}:2"");
+ assertPrint(""0 ? 1 : ({})"", ""0?1:{}"");
+ assertPrint(""typeof ({})"", ""typeof{}"");
+ assertPrint(""f({})"", ""f({})"");
+
+ // Anonymous function expressions.
+ assertPrint(""(function(){})"", ""(function(){})"");
+ assertPrint(""(function(){})()"", ""(function(){})()"");
+ assertPrint(""(function(){})instanceof Object"",
+ ""(function(){})instanceof Object"");
+ assertPrint(""(function(){}).bind().call()"",
+ ""(function(){}).bind().call()"");
+ assertPrint(""var x = function() { };"", ""var x=function(){}"");
+ assertPrint(""var x = function() { }();"", ""var x=function(){}()"");
+ assertPrint(""(function() {}), 2"", ""(function(){}),2"");
+
+ // Name functions expression.
+ assertPrint(""(function f(){})"", ""(function f(){})"");
+
+ // Function declaration.
+ assertPrint(""function f(){}"", ""function f(){}"");
+
+ // Make sure we don't treat non-Latin character escapes as raw strings.
+ assertPrint(""({ 'a': 4, '\\u0100': 4 })"", ""({\""a\"":4,\""\\u0100\"":4})"");
+ assertPrint(""({ a: 4, '\\u0100': 4 })"", ""({a:4,\""\\u0100\"":4})"");
+
+ // Test if statement and for statements with single statements in body.
+ assertPrint(""if (true) { alert();}"", ""if(true)alert()"");
+ assertPrint(""if (false) {} else {alert(\""a\"");}"",
+ ""if(false);else alert(\""a\"")"");
+ assertPrint(""for(;;) { alert();};"", ""for(;;)alert()"");
+
+ assertPrint(""do { alert(); } while(true);"",
+ ""do alert();while(true)"");
+ assertPrint(""myLabel: { alert();}"",
+ ""myLabel:alert()"");
+ assertPrint(""myLabel: for(;;) continue myLabel;"",
+ ""myLabel:for(;;)continue myLabel"");
+
+ // Test nested var statement
+ assertPrint(""if (true) var x; x = 4;"", ""if(true)var x;x=4"");
+
+ // Non-latin identifier. Make sure we keep them escaped.
+ assertPrint(""\\u00fb"", ""\\u00fb"");
+ assertPrint(""\\u00fa=1"", ""\\u00fa=1"");
+ assertPrint(""function \\u00f9(){}"", ""function \\u00f9(){}"");
+ assertPrint(""x.\\u00f8"", ""x.\\u00f8"");
+ assertPrint(""x.\\u00f8"", ""x.\\u00f8"");
+ assertPrint(""abc\\u4e00\\u4e01jkl"", ""abc\\u4e00\\u4e01jkl"");
+
+ // Test the right-associative unary operators for spurious parens
+ assertPrint(""! ! true"", ""!!true"");
+ assertPrint(""!(!(true))"", ""!!true"");
+ assertPrint(""typeof(void(0))"", ""typeof void 0"");
+ assertPrint(""typeof(void(!0))"", ""typeof void!0"");
+ assertPrint(""+ - + + - + 3"", ""+-+ +-+3""); // chained unary plus/minus
+ assertPrint(""+(--x)"", ""+--x"");
+ assertPrint(""-(++x)"", ""-++x"");
+
+ // needs a space to prevent an ambiguous parse
+ assertPrint(""-(--x)"", ""- --x"");
+ assertPrint(""!(~~5)"", ""!~~5"");
+ assertPrint(""~(a/b)"", ""~(a/b)"");
+
+ // Preserve parens to overcome greedy binding of NEW
+ assertPrint(""new (foo.bar()).factory(baz)"", ""new (foo.bar().factory)(baz)"");
+ assertPrint(""new (bar()).factory(baz)"", ""new (bar().factory)(baz)"");
+ assertPrint(""new (new foobar(x)).factory(baz)"",
+ ""new (new foobar(x)).factory(baz)"");
+
+ // Make sure that HOOK is right associative
+ assertPrint(""a ? b : (c ? d : e)"", ""a?b:c?d:e"");
+ assertPrint(""a ? (b ? c : d) : e"", ""a?b?c:d:e"");
+ assertPrint(""(a ? b : c) ? d : e"", ""(a?b:c)?d:e"");
+
+ // Test nested ifs
+ assertPrint(""if (x) if (y); else;"", ""if(x)if(y);else;"");
+
+ // Test comma.
+ assertPrint(""a,b,c"", ""a,b,c"");
+ assertPrint(""(a,b),c"", ""a,b,c"");
+ assertPrint(""a,(b,c)"", ""a,b,c"");
+ assertPrint(""x=a,b,c"", ""x=a,b,c"");
+ assertPrint(""x=(a,b),c"", ""x=(a,b),c"");
+ assertPrint(""x=a,(b,c)"", ""x=a,b,c"");
+ assertPrint(""x=a,y=b,z=c"", ""x=a,y=b,z=c"");
+ assertPrint(""x=(a,y=b,z=c)"", ""x=(a,y=b,z=c)"");
+ assertPrint(""x=[a,b,c,d]"", ""x=[a,b,c,d]"");
+ assertPrint(""x=[(a,b,c),d]"", ""x=[(a,b,c),d]"");
+ assertPrint(""x=[(a,(b,c)),d]"", ""x=[(a,b,c),d]"");
+ assertPrint(""x=[a,(b,c,d)]"", ""x=[a,(b,c,d)]"");
+ assertPrint(""var x=(a,b)"", ""var x=(a,b)"");
+ assertPrint(""var x=a,b,c"", ""var x=a,b,c"");
+ assertPrint(""var x=(a,b),c"", ""var x=(a,b),c"");
+ assertPrint(""var x=a,b=(c,d)"", ""var x=a,b=(c,d)"");
+ assertPrint(""foo(a,b,c,d)"", ""foo(a,b,c,d)"");
+ assertPrint(""foo((a,b,c),d)"", ""foo((a,b,c),d)"");
+ assertPrint(""foo((a,(b,c)),d)"", ""foo((a,b,c),d)"");
+ assertPrint(""f(a+b,(c,d,(e,f,g)))"", ""f(a+b,(c,d,e,f,g))"");
+ assertPrint(""({}) , 1 , 2"", ""({}),1,2"");
+ assertPrint(""({}) , {} , {}"", ""({}),{},{}"");
+
+ // EMPTY nodes
+ assertPrint(""if (x){}"", ""if(x);"");
+ assertPrint(""if(x);"", ""if(x);"");
+ assertPrint(""if(x)if(y);"", ""if(x)if(y);"");
+ assertPrint(""if(x){if(y);}"", ""if(x)if(y);"");
+ assertPrint(""if(x){if(y){};;;}"", ""if(x)if(y);"");
+ assertPrint(""if(x){;;function y(){};;}"", ""if(x){function y(){}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void parse(AbstractCompiler compiler) {
+ try {
+ ParserRunner.ParseResult result = ParserRunner.parse(sourceFile, sourceFile.getCode(),
+ compiler.getParserConfig(),
+ compiler.getDefaultErrorReporter(),
+ logger_);
+ root = result.ast;
+ compiler.setOldParseTree(sourceFile.getName(), result.oldAst);
+ } catch (IOException e) {
+ compiler.report(
+ JSError.make(AbstractCompiler.READ_ERROR, sourceFile.getName()));
+ }
+
+
+ if (root == null || compiler.hasHaltingErrors()) {
+ // Most passes try to report as many errors as possible,
+ // so there may already be errors. We only care if there were
+ // errors in the code we just parsed.
+ // There was a parse error or IOException, so use a dummy block.
+ root = IR.script();
+ } else {
+ compiler.prepareAst(root);
+ }
+
+ // Set the source name so that the compiler passes can track
+ // the source file and module.
+ root.setStaticSourceFile(sourceFile);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1103a() {
+ test(""goog.scope(function () {"" +
+ "" var a;"" +
+ "" foo.bar = function () { a = 1; };"" +
+ ""});"",
+ SCOPE_NAMESPACE + ""foo.bar = function () { $jscomp.scope.a = 1; }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void findAliases(NodeTraversal t) {
+ Scope scope = t.getScope();
+ for (Var v : scope.getVarIterable()) {
+ Node n = v.getNode();
+ Node parent = n.getParent();
+ boolean isVarAssign = parent.isVar() && n.hasChildren();
+ if (isVarAssign && n.getFirstChild().isQualifiedName()) {
+ recordAlias(v);
+ } else if (v.isBleedingFunction()) {
+ // Bleeding functions already get a BAD_PARAMETERS error, so just
+ // do nothing.
+ } else if (parent.getType() == Token.LP) {
+ // Parameters of the scope function also get a BAD_PARAMETERS
+ // error.
+ } else if (isVarAssign) {
+ Node value = v.getInitialValue().detachFromParent();
+ String name = n.getString();
+ int nameCount = scopedAliasNames.count(name);
+ scopedAliasNames.add(name);
+ String globalName =
+ ""$jscomp.scope."" + name + (nameCount == 0 ? """" : (""$"" + nameCount));
+
+ compiler.ensureLibraryInjected(""base"");
+
+ // Add $jscomp.scope.name = EXPR;
+ // Make sure we copy over all the jsdoc and debug info.
+ Node newDecl = NodeUtil.newQualifiedNameNodeDeclaration(
+ compiler.getCodingConvention(),
+ globalName,
+ value,
+ v.getJSDocInfo())
+ .useSourceInfoIfMissingFromForTree(n);
+ NodeUtil.setDebugInformation(
+ newDecl.getFirstChild().getFirstChild(), n, name);
+ parent.getParent().addChildBefore(newDecl, parent);
+
+ // Rewrite ""var name = EXPR;"" to ""var name = $jscomp.scope.name;""
+ v.getNameNode().addChildToFront(
+ NodeUtil.newQualifiedNameNode(
+ compiler.getCodingConvention(), globalName, n, name));
+
+ recordAlias(v);
+ } else {
+ // Do not allow hoisted functions or other kinds of local symbols.
+ report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1103a() {
+ test(""goog.scope(function () {"" +
+ "" var a;"" +
+ "" foo.bar = function () { a = 1; };"" +
+ ""});"",
+ SCOPE_NAMESPACE + ""foo.bar = function () { $jscomp.scope.a = 1; }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Node newQualifiedNameNodeDeclaration(
+ CodingConvention convention, String name, Node value, JSDocInfo info) {
+ Node result;
+ Node nameNode = newQualifiedNameNode(convention, name);
+ if (nameNode.isName()) {
+ result = IR.var(nameNode, value);
+ result.setJSDocInfo(info);
+ } else {
+ result = IR.exprResult(IR.assign(nameNode, value));
+ result.getFirstChild().setJSDocInfo(info);
+ }
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1103a() {
+ test(""goog.scope(function () {"" +
+ "" var a;"" +
+ "" foo.bar = function () { a = 1; };"" +
+ ""});"",
+ SCOPE_NAMESPACE + ""foo.bar = function () { $jscomp.scope.a = 1; }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ CanInlineResult canInlineReferenceToFunction(NodeTraversal t,
+ Node callNode, Node fnNode, Set needAliases,
+ InliningMode mode, boolean referencesThis, boolean containsFunctions) {
+ // TODO(johnlenz): This function takes too many parameter, without
+ // context. Modify the API to take a structure describing the function.
+
+ // Allow direct function calls or ""fn.call"" style calls.
+ if (!isSupportedCallType(callNode)) {
+ return CanInlineResult.NO;
+ }
+
+ // Limit where functions that contain functions can be inline. Introducing
+ // an inner function into another function can capture a variable and cause
+ // a memory leak. This isn't a problem in the global scope as those values
+ // last until explicitly cleared.
+ if (containsFunctions) {
+ if (!assumeMinimumCapture && !t.inGlobalScope()) {
+ // TODO(johnlenz): Allow inlining into any scope without local names or
+ // inner functions.
+ return CanInlineResult.NO;
+ } else if (NodeUtil.isWithinLoop(callNode)) {
+ // An inner closure maybe relying on a local value holding a value for a
+ // single iteration through a loop.
+ return CanInlineResult.NO;
+ }
+ }
+
+ // TODO(johnlenz): Add support for 'apply'
+ if (referencesThis && !NodeUtil.isFunctionObjectCall(callNode)) {
+ // TODO(johnlenz): Allow 'this' references to be replaced with a
+ // global 'this' object.
+ return CanInlineResult.NO;
+ }
+
+ if (mode == InliningMode.DIRECT) {
+ return canInlineReferenceDirectly(callNode, fnNode);
+ } else {
+ return canInlineReferenceAsStatementBlock(
+ t, callNode, fnNode, needAliases);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1101a() {
+ helperCanInlineReferenceToFunction(CanInlineResult.NO,
+ ""function foo(a){return modifiyX() + a;} foo(x);"", ""foo"",
+ INLINE_DIRECT);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ 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));
+ }
+ }
+
+ Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();
+ while (cArg != null || fnParam != null) {
+ if (fnParam != null) {
+ if (cArg != null) {
+ if (NodeUtil.mayEffectMutableState(cArg, compiler)
+ && NodeUtil.getNameReferenceCount(
+ block, fnParam.getString()) > 1) {
+ return CanInlineResult.NO;
+ }
+ }
+ fnParam = fnParam.getNext();
+ }
+ // Limit the inlining
+ if (cArg != null) {
+ if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {
+ return CanInlineResult.NO;
+ }
+ cArg = cArg.getNext();
+ }
+ }
+
+ return CanInlineResult.YES;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1101a() {
+ helperCanInlineReferenceToFunction(CanInlineResult.NO,
+ ""function foo(a){return modifiyX() + a;} foo(x);"", ""foo"",
+ INLINE_DIRECT);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateScopeForTypeChange(
+ FlowScope scope, Node left, JSType leftType, JSType resultType) {
+ Preconditions.checkNotNull(resultType);
+ switch (left.getType()) {
+ case Token.NAME:
+ String varName = left.getString();
+ Var var = syntacticScope.getVar(varName);
+ boolean isVarDeclaration = left.hasChildren();
+
+ // When looking at VAR initializers for declared VARs, we tend
+ // to use the declared type over the type it's being
+ // initialized to in the global scope.
+ //
+ // For example,
+ // /** @param {number} */ var f = goog.abstractMethod;
+ // it's obvious that the programmer wants you to use
+ // the declared function signature, not the inferred signature.
+ //
+ // Or,
+ // /** @type {Object.} */ var x = {};
+ // the one-time anonymous object on the right side
+ // is as narrow as it can possibly be, but we need to make
+ // sure we back-infer the element constraint on
+ // the left hand side, so we use the left hand side.
+
+ boolean isVarTypeBetter = !isVarDeclaration || var == null || var.isTypeInferred();
+ // Makes it easier to check for NPEs.
+
+ // TODO(nicksantos): This might be a better check once we have
+ // back-inference of object/array constraints. It will probably
+ // introduce more type warnings. It uses the result type iff it's
+ // strictly narrower than the declared var type.
+ //
+ //boolean isVarTypeBetter = isVarDeclaration &&
+ // (varType.restrictByNotNullOrUndefined().isSubtype(resultType)
+ // || !resultType.isSubtype(varType));
+
+
+ if (isVarTypeBetter) {
+ redeclareSimpleVar(scope, left, resultType);
+ }
+ left.setJSType(isVarDeclaration || leftType == null ?
+ resultType : null);
+
+ if (var != null && var.isTypeInferred()) {
+ JSType oldType = var.getType();
+ var.setType(oldType == null ?
+ resultType : oldType.getLeastSupertype(resultType));
+ }
+ break;
+ case Token.GETPROP:
+ String qualifiedName = left.getQualifiedName();
+ if (qualifiedName != null) {
+ scope.inferQualifiedSlot(left, qualifiedName,
+ leftType == null ? unknownType : leftType,
+ resultType);
+ }
+
+ left.setJSType(resultType);
+ ensurePropertyDefined(left, resultType);
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1056() throws Exception {
+ testTypes(
+ ""/** @type {Array} */ var x = null;"" +
+ ""x.push('hi');"",
+ ""No properties on this expression\n"" +
+ ""found : null\n"" +
+ ""required: Object"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Node parseInputs() {
+ boolean devMode = options.devMode != DevMode.OFF;
+
+ // If old roots exist (we are parsing a second time), detach each of the
+ // individual file parse trees.
+ if (externsRoot != null) {
+ externsRoot.detachChildren();
+ }
+ if (jsRoot != null) {
+ jsRoot.detachChildren();
+ }
+
+ // Parse main JS sources.
+ jsRoot = IR.block();
+ jsRoot.setIsSyntheticBlock(true);
+
+ externsRoot = IR.block();
+ externsRoot.setIsSyntheticBlock(true);
+
+ externAndJsRoot = IR.block(externsRoot, jsRoot);
+ externAndJsRoot.setIsSyntheticBlock(true);
+
+ if (options.tracer.isOn()) {
+ tracker = new PerformanceTracker(jsRoot, options.tracer);
+ addChangeHandler(tracker.getCodeChangeHandler());
+ }
+
+ Tracer tracer = newTracer(""parseInputs"");
+
+ try {
+ // Parse externs sources.
+ for (CompilerInput input : externs) {
+ Node n = input.getAstRoot(this);
+ if (hasErrors()) {
+ return null;
+ }
+ externsRoot.addChildToBack(n);
+ }
+
+ // Modules inferred in ProcessCommonJS pass.
+ if (options.transformAMDToCJSModules || options.processCommonJSModules) {
+ processAMDAndCommonJSModules();
+ }
+
+ hoistExterns(externsRoot);
+
+ // Check if the sources need to be re-ordered.
+ boolean staleInputs = false;
+ if (options.dependencyOptions.needsManagement() && options.closurePass) {
+ for (CompilerInput input : inputs) {
+ // Forward-declare all the provided types, so that they
+ // are not flagged even if they are dropped from the process.
+ for (String provide : input.getProvides()) {
+ getTypeRegistry().forwardDeclareType(provide);
+ }
+ }
+
+ try {
+ inputs =
+ (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)
+ .manageDependencies(options.dependencyOptions, inputs);
+ staleInputs = true;
+ } catch (CircularDependencyException e) {
+ report(JSError.make(
+ JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));
+
+ // If in IDE mode, we ignore the error and keep going.
+ if (hasErrors()) {
+ return null;
+ }
+ } catch (MissingProvideException e) {
+ report(JSError.make(
+ MISSING_ENTRY_ERROR, e.getMessage()));
+
+ // If in IDE mode, we ignore the error and keep going.
+ if (hasErrors()) {
+ return null;
+ }
+ }
+ }
+
+ hoistNoCompileFiles();
+
+ if (staleInputs) {
+ repartitionInputs();
+ }
+
+ // Build the AST.
+ for (CompilerInput input : inputs) {
+ Node n = input.getAstRoot(this);
+ if (n == null) {
+ continue;
+ }
+
+ if (devMode) {
+ runSanityCheck();
+ if (hasErrors()) {
+ return null;
+ }
+ }
+
+ if (options.sourceMapOutputPath != null ||
+ options.nameReferenceReportPath != null) {
+
+ // Annotate the nodes in the tree with information from the
+ // input file. This information is used to construct the SourceMap.
+ SourceInformationAnnotator sia =
+ new SourceInformationAnnotator(
+ input.getName(), options.devMode != DevMode.OFF);
+ NodeTraversal.traverse(this, n, sia);
+ }
+
+ jsRoot.addChildToBack(n);
+ }
+
+ if (hasErrors()) {
+ return null;
+ }
+ return externAndJsRoot;
+ } finally {
+ stopTracer(tracer, ""parseInputs"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDependencySorting() throws Exception {
+ CompilerOptions options = createCompilerOptions();
+ options.setDependencyOptions(
+ new DependencyOptions()
+ .setDependencySorting(true));
+ test(
+ options,
+ new String[] {
+ ""goog.require('x');"",
+ ""goog.provide('x');"",
+ },
+ new String[] {
+ ""goog.provide('x');"",
+ ""goog.require('x');"",
+
+ // For complicated reasons involving modules,
+ // the compiler creates a synthetic source file.
+ """",
+ });
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void declareNameInScope(FlowScope scope, Node node, JSType type) {
+ switch (node.getType()) {
+ case Token.NAME:
+ scope.inferSlotType(node.getString(), type);
+ break;
+
+ case Token.GETPROP:
+ String qualifiedName = node.getQualifiedName();
+ Preconditions.checkNotNull(qualifiedName);
+
+ JSType origType = node.getJSType();
+ origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType;
+ scope.inferQualifiedSlot(node, qualifiedName, origType, type);
+ break;
+
+ // ""this"" references aren't currently modeled in the CFG.
+
+ default:
+ throw new IllegalArgumentException(""Node cannot be refined. \n"" +
+ node.toStringTree());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNoThisInference() {
+ JSType thisType = createNullableType(OBJECT_TYPE);
+ assumingThisType(thisType);
+ inFunction(""var out = 3; if (goog.isNull(this)) out = this;"");
+ verify(""out"", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void checkInterfaceConflictProperties(NodeTraversal t, Node n,
+ String functionName, HashMap properties,
+ HashMap currentProperties,
+ ObjectType interfaceType) {
+ ObjectType implicitProto = interfaceType.getImplicitPrototype();
+ Set currentPropertyNames;
+ // This can be the case if interfaceType is proxy to a non-existent
+ // object (which is a bad type annotation, but shouldn't crash).
+ currentPropertyNames = implicitProto.getOwnPropertyNames();
+ for (String name : currentPropertyNames) {
+ ObjectType oType = properties.get(name);
+ if (oType != null) {
+ if (!interfaceType.getPropertyType(name).isEquivalentTo(
+ oType.getPropertyType(name))) {
+ compiler.report(
+ t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,
+ functionName, name, oType.toString(),
+ interfaceType.toString()));
+ }
+ }
+ currentProperties.put(name, interfaceType);
+ }
+ for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) {
+ checkInterfaceConflictProperties(t, n, functionName, properties,
+ currentProperties, iType);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBadInterfaceExtendsNonExistentInterfaces() throws Exception {
+ String js = ""/** @interface \n"" +
+ "" * @extends {nonExistent1} \n"" +
+ "" * @extends {nonExistent2} \n"" +
+ "" */function A() {}"";
+ String[] expectedWarnings = {
+ ""Bad type annotation. Unknown type nonExistent1"",
+ ""Bad type annotation. Unknown type nonExistent2""
+ };
+ testTypes(js, expectedWarnings);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryFoldSimpleFunctionCall(Node n) {
+ Preconditions.checkState(n.isCall());
+ Node callTarget = n.getFirstChild();
+ if (callTarget != null && callTarget.isName() &&
+ callTarget.getString().equals(""String"")) {
+ // Fold String(a) to '' + (a) on immutable literals,
+ // which allows further optimizations
+ //
+ // We can't do this in the general case, because String(a) has
+ // slightly different semantics than '' + (a). See
+ // http://code.google.com/p/closure-compiler/issues/detail?id=759
+ Node value = callTarget.getNext();
+ if (value != null) {
+ Node addition = IR.add(
+ IR.string("""").srcref(callTarget),
+ value.detachFromParent());
+ n.getParent().replaceChild(n, addition);
+ reportCodeChange();
+ return addition;
+ }
+ }
+ return n;
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleFunctionCall() {
+ test(""var a = String(23)"", ""var a = '' + 23"");
+ test(""var a = String('hello')"", ""var a = '' + 'hello'"");
+ testSame(""var a = String('hello', bar());"");
+ testSame(""var a = String({valueOf: function() { return 1; }});"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ // VOID nodes appear when there are extra semicolons at the BLOCK level.
+ // I've been unable to think of any cases where this indicates a bug,
+ // and apparently some people like keeping these semicolons around,
+ // so we'll allow it.
+ if (n.isEmpty() ||
+ n.isComma()) {
+ return;
+ }
+
+ if (parent == null) {
+ return;
+ }
+
+ // Do not try to remove a block or an expr result. We already handle
+ // these cases when we visit the child, and the peephole passes will
+ // fix up the tree in more clever ways when these are removed.
+ if (n.isExprResult()) {
+ return;
+ }
+
+ // This no-op statement was there so that JSDoc information could
+ // be attached to the name. This check should not complain about it.
+ if (n.isQualifiedName() && n.getJSDocInfo() != null) {
+ return;
+ }
+
+ boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);
+ boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());
+ if (parent.getType() == Token.COMMA) {
+ if (isResultUsed) {
+ return;
+ }
+ if (n == parent.getLastChild()) {
+ for (Node an : parent.getAncestors()) {
+ int ancestorType = an.getType();
+ if (ancestorType == Token.COMMA) continue;
+ if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK) return;
+ else break;
+ }
+ }
+ } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) {
+ if (! (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() || n == parent.getFirstChild().getNext().getNext()))) {
+ return;
+ }
+ }
+ if (
+ (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {
+ String msg = ""This code lacks side-effects. Is there a bug?"";
+ if (n.isString()) {
+ msg = ""Is there a missing '+' on the previous line?"";
+ } else if (isSimpleOp) {
+ msg = ""The result of the '"" + Token.name(n.getType()).toLowerCase() +
+ ""' operator is not being used."";
+ }
+
+ t.getCompiler().report(
+ t.makeError(n, level, USELESS_CODE_ERROR, msg));
+ // TODO(johnlenz): determine if it is necessary to
+ // try to protect side-effect free statements as well.
+ if (!NodeUtil.isStatement(n)) {
+ problemNodes.add(n);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testUselessCode() {
+ test(""function f(x) { if(x) return; }"", ok);
+ test(""function f(x) { if(x); }"", ""function f(x) { if(x); }"", e);
+
+ test(""if(x) x = y;"", ok);
+ test(""if(x) x == bar();"", ""if(x) JSCOMPILER_PRESERVE(x == bar());"", e);
+
+ test(""x = 3;"", ok);
+ test(""x == 3;"", ""JSCOMPILER_PRESERVE(x == 3);"", e);
+
+ test(""var x = 'test'"", ok);
+ test(""var x = 'test'\n'str'"",
+ ""var x = 'test'\nJSCOMPILER_PRESERVE('str')"", e);
+
+ test("""", ok);
+ test(""foo();;;;bar();;;;"", ok);
+
+ test(""var a, b; a = 5, b = 6"", ok);
+ test(""var a, b; a = 5, b == 6"",
+ ""var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)"", e);
+ test(""var a, b; a = (5, 6)"",
+ ""var a, b; a = (JSCOMPILER_PRESERVE(5), 6)"", e);
+ test(""var a, b; a = (bar(), 6, 7)"",
+ ""var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)"", e);
+ test(""var a, b; a = (bar(), bar(), 7, 8)"",
+ ""var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)"", e);
+ test(""var a, b; a = (b = 7, 6)"", ok);
+ test(""function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));"", ok);
+ test(""function x(){}\nfunction f(a, b){}\nf(1,(2, 3));"",
+ ""function x(){}\nfunction f(a, b){}\n"" +
+ ""f(1,(JSCOMPILER_PRESERVE(2), 3));"", e);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ // VOID nodes appear when there are extra semicolons at the BLOCK level.
+ // I've been unable to think of any cases where this indicates a bug,
+ // and apparently some people like keeping these semicolons around,
+ // so we'll allow it.
+ if (n.isEmpty() ||
+ n.isComma()) {
+ return;
+ }
+
+ if (parent == null) {
+ return;
+ }
+
+ // Do not try to remove a block or an expr result. We already handle
+ // these cases when we visit the child, and the peephole passes will
+ // fix up the tree in more clever ways when these are removed.
+ if (parent.getType() == Token.COMMA) {
+ Node gramps = parent.getParent();
+ if (gramps.isCall() && parent == gramps.getFirstChild()) {
+ if (n == parent.getFirstChild() && parent.getChildCount() == 2 && n.getNext().isName() && ""eval"".equals(n.getNext().getString())) {
+ return;
+ }
+ }
+
+ // This no-op statement was there so that JSDoc information could
+ // be attached to the name. This check should not complain about it.
+ if (n == parent.getLastChild()) {
+ for (Node an : parent.getAncestors()) {
+ int ancestorType = an.getType();
+ if (ancestorType == Token.COMMA)
+ continue;
+ if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK)
+ return;
+ else
+ break;
+ }
+ }
+ } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) {
+ if (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() ||
+ n == parent.getFirstChild().getNext().getNext())) {
+ } else {
+ return;
+ }
+ }
+
+ boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);
+ boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());
+ if (!isResultUsed &&
+ (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {
+ if (n.isQualifiedName() && n.getJSDocInfo() != null) {
+ return;
+ } else if (n.isExprResult()) {
+ return;
+ }
+ String msg = ""This code lacks side-effects. Is there a bug?"";
+ if (n.isString()) {
+ msg = ""Is there a missing '+' on the previous line?"";
+ } else if (isSimpleOp) {
+ msg = ""The result of the '"" + Token.name(n.getType()).toLowerCase() +
+ ""' operator is not being used."";
+ }
+
+ t.getCompiler().report(
+ t.makeError(n, level, USELESS_CODE_ERROR, msg));
+ // TODO(johnlenz): determine if it is necessary to
+ // try to protect side-effect free statements as well.
+ if (!NodeUtil.isStatement(n)) {
+ problemNodes.add(n);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testUselessCode() {
+ test(""function f(x) { if(x) return; }"", ok);
+ test(""function f(x) { if(x); }"", ""function f(x) { if(x); }"", e);
+
+ test(""if(x) x = y;"", ok);
+ test(""if(x) x == bar();"", ""if(x) JSCOMPILER_PRESERVE(x == bar());"", e);
+
+ test(""x = 3;"", ok);
+ test(""x == 3;"", ""JSCOMPILER_PRESERVE(x == 3);"", e);
+
+ test(""var x = 'test'"", ok);
+ test(""var x = 'test'\n'str'"",
+ ""var x = 'test'\nJSCOMPILER_PRESERVE('str')"", e);
+
+ test("""", ok);
+ test(""foo();;;;bar();;;;"", ok);
+
+ test(""var a, b; a = 5, b = 6"", ok);
+ test(""var a, b; a = 5, b == 6"",
+ ""var a, b; a = 5, JSCOMPILER_PRESERVE(b == 6)"", e);
+ test(""var a, b; a = (5, 6)"",
+ ""var a, b; a = (JSCOMPILER_PRESERVE(5), 6)"", e);
+ test(""var a, b; a = (bar(), 6, 7)"",
+ ""var a, b; a = (bar(), JSCOMPILER_PRESERVE(6), 7)"", e);
+ test(""var a, b; a = (bar(), bar(), 7, 8)"",
+ ""var a, b; a = (bar(), bar(), JSCOMPILER_PRESERVE(7), 8)"", e);
+ test(""var a, b; a = (b = 7, 6)"", ok);
+ test(""function x(){}\nfunction f(a, b){}\nf(1,(x(), 2));"", ok);
+ test(""function x(){}\nfunction f(a, b){}\nf(1,(2, 3));"",
+ ""function x(){}\nfunction f(a, b){}\n"" +
+ ""f(1,(JSCOMPILER_PRESERVE(2), 3));"", e);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryFoldArrayAccess(Node n, Node left, Node right) {
+ Node parent = n.getParent();
+ // If GETPROP/GETELEM is used as assignment target the array literal is
+ // acting as a temporary we can't fold it here:
+ // ""[][0] += 1""
+ if (isAssignmentTarget(n)) {
+ return n;
+ }
+
+ if (!right.isNumber()) {
+ // Sometimes people like to use complex expressions to index into
+ // arrays, or strings to index into array methods.
+ return n;
+ }
+
+ double index = right.getDouble();
+ int intIndex = (int) index;
+ if (intIndex != index) {
+ error(INVALID_GETELEM_INDEX_ERROR, right);
+ return n;
+ }
+
+ if (intIndex < 0) {
+ error(INDEX_OUT_OF_BOUNDS_ERROR, right);
+ return n;
+ }
+
+ Node current = left.getFirstChild();
+ Node elem = null;
+ for (int i = 0; current != null && i < intIndex; i++) {
+ elem = current;
+
+ current = current.getNext();
+ }
+
+ if (elem == null) {
+ error(INDEX_OUT_OF_BOUNDS_ERROR, right);
+ return n;
+ }
+
+ if (elem.isEmpty()) {
+ elem = NodeUtil.newUndefinedNode(elem);
+ } else {
+ left.removeChild(elem);
+ }
+
+ // Replace the entire GETELEM with the value
+ n.getParent().replaceChild(n, elem);
+ reportCodeChange();
+ return elem;
+ }
+
+// Test Case
+[/INST]
+ public void testFoldGetElem() {
+ fold(""x = [,10][0]"", ""x = void 0"");
+ fold(""x = [10, 20][0]"", ""x = 10"");
+ fold(""x = [10, 20][1]"", ""x = 20"");
+ fold(""x = [10, 20][0.5]"", """",
+ PeepholeFoldConstants.INVALID_GETELEM_INDEX_ERROR);
+ fold(""x = [10, 20][-1]"", """",
+ PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR);
+ fold(""x = [10, 20][2]"", """",
+ PeepholeFoldConstants.INDEX_OUT_OF_BOUNDS_ERROR);
+
+ foldSame(""x = [foo(), 0][1]"");
+ fold(""x = [0, foo()][1]"", ""x = foo()"");
+ foldSame(""x = [0, foo()][0]"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void findAliases(NodeTraversal t) {
+ Scope scope = t.getScope();
+ for (Var v : scope.getVarIterable()) {
+ Node n = v.getNode();
+ int type = n.getType();
+ Node parent = n.getParent();
+ if (parent.isVar()) {
+ if (n.hasChildren() && n.getFirstChild().isQualifiedName()) {
+ String name = n.getString();
+ Var aliasVar = scope.getVar(name);
+ aliases.put(name, aliasVar);
+
+ String qualifiedName =
+ aliasVar.getInitialValue().getQualifiedName();
+ transformation.addAlias(name, qualifiedName);
+ // Bleeding functions already get a BAD_PARAMETERS error, so just
+ // do nothing.
+ // Parameters of the scope function also get a BAD_PARAMETERS
+ // error.
+ } else {
+ // TODO(robbyw): Support using locals for private variables.
+ report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNonAliasLocal() {
+ testScopedFailure(""var x = 10"", ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL);
+ testScopedFailure(""var x = goog.dom + 10"",
+ ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL);
+ testScopedFailure(""var x = goog['dom']"",
+ ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL);
+ testScopedFailure(""var x = goog.dom, y = 10"",
+ ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL);
+ testScopedFailure(""function f() {}"",
+ ScopedAliases.GOOG_SCOPE_NON_ALIAS_LOCAL);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private FlowScope traverseNew(Node n, FlowScope scope) {
+
+ Node constructor = n.getFirstChild();
+ scope = traverse(constructor, scope);
+ JSType constructorType = constructor.getJSType();
+ JSType type = null;
+ if (constructorType != null) {
+ constructorType = constructorType.restrictByNotNullOrUndefined();
+ if (constructorType.isUnknownType()) {
+ type = getNativeType(UNKNOWN_TYPE);
+ } else {
+ FunctionType ct = constructorType.toMaybeFunctionType();
+ if (ct == null && constructorType instanceof FunctionType) {
+ // If constructorType is a NoObjectType, then toMaybeFunctionType will
+ // return null. But NoObjectType implements the FunctionType
+ // interface, precisely because it can validly construct objects.
+ ct = (FunctionType) constructorType;
+ }
+ if (ct != null && ct.isConstructor()) {
+ type = ct.getInstanceType();
+ }
+ }
+ }
+ n.setJSType(type);
+ for (Node arg = constructor.getNext(); arg != null; arg = arg.getNext()) {
+ scope = traverse(arg, scope);
+ }
+ return scope;
+ }
+
+// Test Case
+[/INST]
+ public void testBackwardsInferenceNew() {
+ inFunction(
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" * @param {{foo: (number|undefined)}} x\n"" +
+ "" */"" +
+ ""function F(x) {}"" +
+ ""var y = {};"" +
+ ""new F(y);"");
+
+ assertEquals(""{foo: (number|undefined)}"", getType(""y"").toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void emitOptionalModuleExportsOverride(Node script,
+ String moduleName) {
+
+ Node moduleExportsProp = IR.getprop(IR.name(moduleName),
+ IR.string(""module$exports""));
+ script.addChildToBack(IR.ifNode(
+ moduleExportsProp,
+ IR.block(IR.exprResult(IR.assign(IR.name(moduleName),
+ moduleExportsProp.cloneTree())))).copyInformationFromForTree(
+ script));
+ }
+
+// Test Case
+[/INST]
+ public void testTransformAMDAndProcessCJS() {
+ args.add(""--transform_amd_modules"");
+ args.add(""--process_common_js_modules"");
+ args.add(""--common_js_entry_module=foo/bar"");
+ setFilename(0, ""foo/bar.js"");
+ test(""define({foo: 1})"",
+ ""var module$foo$bar={}, module$foo$bar={foo:1};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitModuleExports(Node prop) {
+ String moduleName = guessCJSModuleName(prop.getSourceFileName());
+ Node module = prop.getChildAtIndex(0);
+ module.putProp(Node.ORIGINALNAME_PROP, ""module"");
+ module.setString(moduleName);
+ Node exports = prop.getChildAtIndex(1);
+ exports.putProp(Node.ORIGINALNAME_PROP, ""exports"");
+ exports.setString(""module$exports"");
+ }
+
+// Test Case
+[/INST]
+ public void testTransformAMDAndProcessCJS() {
+ args.add(""--transform_amd_modules"");
+ args.add(""--process_common_js_modules"");
+ args.add(""--common_js_entry_module=foo/bar"");
+ setFilename(0, ""foo/bar.js"");
+ test(""define({foo: 1})"",
+ ""var module$foo$bar={}, module$foo$bar={foo:1};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Node tryFinally(Node tryBody, Node finallyBody) {
+ Preconditions.checkState(tryBody.isLabelName());
+ Preconditions.checkState(finallyBody.isLabelName());
+ Node catchBody = block().copyInformationFrom(tryBody);
+ return new Node(Token.TRY, tryBody, catchBody, finallyBody);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue727_1() {
+ testIR(
+ IR.tryFinally(
+ IR.block(),
+ IR.block()),
+ ""TRY\n"" +
+ "" BLOCK\n"" +
+ "" BLOCK\n"" +
+ "" BLOCK\n"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Node tryCatch(Node tryBody, Node catchNode) {
+ Preconditions.checkState(tryBody.isBlock());
+ Preconditions.checkState(catchNode.isCatch());
+ Node catchBody = block(catchNode).copyInformationFrom(catchNode);
+ return new Node(Token.TRY, tryBody, catchBody);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue727_1() {
+ testIR(
+ IR.tryFinally(
+ IR.block(),
+ IR.block()),
+ ""TRY\n"" +
+ "" BLOCK\n"" +
+ "" BLOCK\n"" +
+ "" BLOCK\n"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testCost() {
+ checkCost(""1"", ""1"");
+ checkCost(""true"", ""1"");
+ checkCost(""false"", ""1"");
+ checkCost(""a"", ""xx"");
+ checkCost(""a + b"", ""xx+xx"");
+ checkCost(""foo()"", ""xx()"");
+ checkCost(""foo(a,b)"", ""xx(xx,xx)"");
+ checkCost(""10 + foo(a,b)"", ""0+xx(xx,xx)"");
+ checkCost(""1 + foo(a,b)"", ""1+xx(xx,xx)"");
+ checkCost(""a ? 1 : 0"", ""xx?1:0"");
+ checkCost(""a.b"", ""xx.xx"");
+ checkCost(""new Obj()"", ""new xx"");
+ checkCost(""function a() {return \""monkey\""}"",
+ ""function xx(){return\""monkey\""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isInlinableObject(List refs) {
+ boolean ret = false;
+ for (Reference ref : refs) {
+ Node name = ref.getNode();
+ Node parent = ref.getParent();
+ Node gramps = ref.getGrandparent();
+
+ // Ignore indirect references, like x.y (except x.y(), since
+ // the function referenced by y might reference 'this').
+ //
+ if (parent.isGetProp()) {
+ Preconditions.checkState(parent.getFirstChild() == name);
+ // A call target maybe using the object as a 'this' value.
+ if (gramps.isCall()
+ && gramps.getFirstChild() == parent) {
+ return false;
+ }
+
+ // NOTE(nicksantos): This pass's object-splitting algorithm has
+ // a blind spot. It assumes that if a property isn't defined on an
+ // object, then the value is undefined. This is not true, because
+ // Object.prototype can have arbitrary properties on it.
+ //
+ // We short-circuit this problem by bailing out if we see a reference
+ // to a property that isn't defined on the object literal. This
+ // isn't a perfect algorithm, but it should catch most cases.
+ continue;
+ }
+
+ // Only rewrite VAR declarations or simple assignment statements
+ if (!isVarOrAssignExprLhs(name)) {
+ return false;
+ }
+
+ Node val = ref.getAssignedValue();
+ if (val == null) {
+ // A var with no assignment.
+ continue;
+ }
+
+ // We're looking for object literal assignments only.
+ if (!val.isObjectLit()) {
+ return false;
+ }
+
+ // Make sure that the value is not self-refential. IOW,
+ // disallow things like x = {b: x.a}.
+ //
+ // TODO: Only exclude unorderable self-referential
+ // assignments. i.e. x = {a: x.b, b: x.a} is not orderable,
+ // but x = {a: 1, b: x.a} is.
+ //
+ // Also, ES5 getters/setters aren't handled by this pass.
+ for (Node child = val.getFirstChild(); child != null;
+ child = child.getNext()) {
+ if (child.isGetterDef() ||
+ child.isSetterDef()) {
+ // ES5 get/set not supported.
+ return false;
+ }
+
+
+ Node childVal = child.getFirstChild();
+ // Check if childVal is the parent of any of the passed in
+ // references, as that is how self-referential assignments
+ // will happen.
+ for (Reference t : refs) {
+ Node refNode = t.getParent();
+ while (!NodeUtil.isStatementBlock(refNode)) {
+ if (refNode == childVal) {
+ // There's a self-referential assignment
+ return false;
+ }
+ refNode = refNode.getParent();
+ }
+ }
+ }
+
+
+ // We have found an acceptable object literal assignment. As
+ // long as there are no other assignments that mess things up,
+ // we can inline.
+ ret = true;
+ }
+ return ret;
+ }
+
+// Test Case
+[/INST]
+ public void testObject10() {
+ testLocal(""var x; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b);"",
+ ""var JSCompiler_object_inline_a_0;"" +
+ ""var JSCompiler_object_inline_b_1;"" +
+ ""var b = f();"" +
+ ""JSCompiler_object_inline_a_0=a,JSCompiler_object_inline_b_1=b,true;"" +
+ ""if(JSCompiler_object_inline_a_0) g(JSCompiler_object_inline_b_1)"");
+ testLocal(""var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c"",
+ ""var x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c"");
+ testLocal(""var x; var b = f(); x = {a:a, b:b}; x.c = c; if(x.a) g(x.b) + x.c"",
+ ""var JSCompiler_object_inline_a_0;"" +
+ ""var JSCompiler_object_inline_b_1;"" +
+ ""var JSCompiler_object_inline_c_2;"" +
+ ""var b = f();"" +
+ ""JSCompiler_object_inline_a_0 = a,JSCompiler_object_inline_b_1 = b, "" +
+ "" JSCompiler_object_inline_c_2=void 0,true;"" +
+ ""JSCompiler_object_inline_c_2 = c;"" +
+ ""if (JSCompiler_object_inline_a_0)"" +
+ "" g(JSCompiler_object_inline_b_1) + JSCompiler_object_inline_c_2;"");
+ testLocal(""var x = {a:a}; if (b) x={b:b}; f(x.a||x.b);"",
+ ""var JSCompiler_object_inline_a_0 = a;"" +
+ ""var JSCompiler_object_inline_b_1;"" +
+ ""if(b) JSCompiler_object_inline_b_1 = b,"" +
+ "" JSCompiler_object_inline_a_0 = void 0,"" +
+ "" true;"" +
+ ""f(JSCompiler_object_inline_a_0 || JSCompiler_object_inline_b_1)"");
+ testLocal(""var x; var y = 5; x = {a:a, b:b, c:c}; if (b) x={b:b}; f(x.a||x.b);"",
+ ""var JSCompiler_object_inline_a_0;"" +
+ ""var JSCompiler_object_inline_b_1;"" +
+ ""var JSCompiler_object_inline_c_2;"" +
+ ""var y=5;"" +
+ ""JSCompiler_object_inline_a_0=a,"" +
+ ""JSCompiler_object_inline_b_1=b,"" +
+ ""JSCompiler_object_inline_c_2=c,"" +
+ ""true;"" +
+ ""if (b) JSCompiler_object_inline_b_1=b,"" +
+ "" JSCompiler_object_inline_a_0=void 0,"" +
+ "" JSCompiler_object_inline_c_2=void 0,"" +
+ "" true;"" +
+ ""f(JSCompiler_object_inline_a_0||JSCompiler_object_inline_b_1)"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void enterScope(NodeTraversal t) {
+
+ if (t.inGlobalScope()) {
+ return; // Don't even brother. All global variables are likely escaped.
+ }
+
+ if (LiveVariablesAnalysis.MAX_VARIABLES_TO_ANALYZE <
+ t.getScope().getVarCount()) {
+ return;
+ }
+
+ // Compute the forward reaching definition.
+ ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
+ // Process the body of the function.
+ Preconditions.checkState(t.getScopeRoot().isFunction());
+ cfa.process(null, t.getScopeRoot().getLastChild());
+ cfg = cfa.getCfg();
+ reachingDef = new MustBeReachingVariableDef(cfg, t.getScope(), compiler);
+ reachingDef.analyze();
+ candidates = Lists.newLinkedList();
+
+ // Using the forward reaching definition search to find all the inline
+ // candidates
+ new NodeTraversal(compiler, new GatherCandiates()).traverse(
+ t.getScopeRoot().getLastChild());
+
+ // Compute the backward reaching use. The CFG can be reused.
+ reachingUses = new MaybeReachingVariableUse(cfg, t.getScope(), compiler);
+ reachingUses.analyze();
+ for (Candidate c : candidates) {
+ if (c.canInline()) {
+ c.inlineVariable();
+
+ // If definition c has dependencies, then inlining it may have
+ // introduced new dependencies for our other inlining candidates.
+ //
+ // MustBeReachingVariableDef uses this dependency graph in its
+ // analysis, so some of these candidates may no longer be valid.
+ // We keep track of when the variable dependency graph changed
+ // so that we can back off appropriately.
+ if (!c.defMetadata.depends.isEmpty()) {
+ inlinedNewDependencies.add(t.getScope().getVar(c.varName));
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDoNotInlineCatchExpression1a() {
+ noInline(
+ ""var a;\n"" +
+ ""try {\n"" +
+ "" throw Error(\""\"");\n"" +
+ ""}catch(err) {"" +
+ "" a = err + 1;\n"" +
+ ""}\n"" +
+ ""return a.stack\n"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void enterScope(NodeTraversal t) {
+
+ if (t.inGlobalScope()) {
+ return; // Don't even brother. All global variables are likely escaped.
+ }
+
+ if (LiveVariablesAnalysis.MAX_VARIABLES_TO_ANALYZE <
+ t.getScope().getVarCount()) {
+ return;
+ }
+
+ // Compute the forward reaching definition.
+ ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
+ // Process the body of the function.
+ Preconditions.checkState(t.getScopeRoot().isFunction());
+ cfa.process(null, t.getScopeRoot().getLastChild());
+ cfg = cfa.getCfg();
+ reachingDef = new MustBeReachingVariableDef(cfg, t.getScope(), compiler);
+ reachingDef.analyze();
+ candidates = Lists.newLinkedList();
+
+ // Using the forward reaching definition search to find all the inline
+ // candidates
+ new NodeTraversal(compiler, new GatherCandiates()).traverse(
+ t.getScopeRoot().getLastChild());
+
+ // Compute the backward reaching use. The CFG can be reused.
+ reachingUses = new MaybeReachingVariableUse(cfg, t.getScope(), compiler);
+ reachingUses.analyze();
+ for (Candidate c : candidates) {
+ if (c.canInline()) {
+ c.inlineVariable();
+
+ // If definition c has dependencies, then inlining it may have
+ // introduced new dependencies for our other inlining candidates.
+ //
+ // MustBeReachingVariableDef uses this dependency graph in its
+ // analysis, so some of these candidates may no longer be valid.
+ // We keep track of when the variable dependency graph changed
+ // so that we can back off appropriately.
+ if (!c.defMetadata.depends.isEmpty()) {
+ inlinedNewDependencies.add(t.getScope().getVar(c.varName));
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDoNotInlineCatchExpression1a() {
+ noInline(
+ ""var a;\n"" +
+ ""try {\n"" +
+ "" throw Error(\""\"");\n"" +
+ ""}catch(err) {"" +
+ "" a = err + 1;\n"" +
+ ""}\n"" +
+ ""return a.stack\n"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean canInline() {
+ // Cannot inline a parameter.
+ if (getDefCfgNode().isFunction()) {
+ return false;
+ }
+
+ // If one of our dependencies has been inlined, then our dependency
+ // graph is wrong. Re-computing it would take another CFG computation,
+ // so we just back off for now.
+ for (Var dependency : defMetadata.depends) {
+ if (inlinedNewDependencies.contains(dependency)) {
+ return false;
+ }
+ }
+
+ getDefinition(getDefCfgNode(), null);
+ getNumUseInUseCfgNode(useCfgNode, null);
+
+ // Definition was not found.
+ if (def == null) {
+ return false;
+ }
+
+ // Check that the assignment isn't used as a R-Value.
+ // TODO(user): Certain cases we can still inline.
+ if (def.isAssign() && !NodeUtil.isExprAssign(def.getParent())) {
+ return false;
+ }
+
+ // The right of the definition has side effect:
+ // Example, for x:
+ // x = readProp(b), modifyProp(b); print(x);
+ if (checkRightOf(def, getDefCfgNode(), SIDE_EFFECT_PREDICATE)) {
+ return false;
+ }
+
+ // Similar check as the above but this time, all the sub-expressions
+ // left of the use of the variable.
+ // x = readProp(b); modifyProp(b), print(x);
+ if (checkLeftOf(use, useCfgNode, SIDE_EFFECT_PREDICATE)) {
+ return false;
+ }
+
+ // TODO(user): Side-effect is OK sometimes. As long as there are no
+ // side-effect function down all paths to the use. Once we have all the
+ // side-effect analysis tool.
+ if (NodeUtil.mayHaveSideEffects(def.getLastChild(), compiler)) {
+ return false;
+ }
+
+ // TODO(user): We could inline all the uses if the expression is short.
+
+ // Finally we have to make sure that there are no more than one use
+ // in the program and in the CFG node. Even when it is semantically
+ // correctly inlining twice increases code size.
+ if (numUseWithinUseCfgNode != 1) {
+ return false;
+ }
+
+ // Make sure that the name is not within a loop
+ if (NodeUtil.isWithinLoop(use)) {
+ return false;
+ }
+
+
+ Collection uses = reachingUses.getUses(varName, getDefCfgNode());
+
+ if (uses.size() != 1) {
+ return false;
+ }
+
+ // We give up inlining stuff with R-Value that has:
+ // 1) GETPROP, GETELEM,
+ // 2) anything that creates a new object.
+ // 3) a direct reference to a catch expression.
+ // Example:
+ // var x = a.b.c; j.c = 1; print(x);
+ // Inlining print(a.b.c) is not safe consider j and be alias to a.b.
+ // TODO(user): We could get more accuracy by looking more in-detail
+ // what j is and what x is trying to into to.
+ // TODO(johnlenz): rework catch expression handling when we
+ // have lexical scope support so catch expressions don't
+ // need to be special cased.
+ if (NodeUtil.has(def.getLastChild(),
+ new Predicate() {
+ @Override
+ public boolean apply(Node input) {
+ switch (input.getType()) {
+ case Token.GETELEM:
+ case Token.GETPROP:
+ case Token.ARRAYLIT:
+ case Token.OBJECTLIT:
+ case Token.REGEXP:
+ case Token.NEW:
+ return true;
+ }
+ return false;
+ }
+ },
+ new Predicate() {
+ @Override
+ public boolean apply(Node input) {
+ // Recurse if the node is not a function.
+ return !input.isFunction();
+ }
+ })) {
+ return false;
+ }
+
+ // We can skip the side effect check along the paths of two nodes if
+ // they are just next to each other.
+ if (NodeUtil.isStatementBlock(getDefCfgNode().getParent()) &&
+ getDefCfgNode().getNext() != useCfgNode) {
+ // Similar side effect check as above but this time the side effect is
+ // else where along the path.
+ // x = readProp(b); while(modifyProp(b)) {}; print(x);
+ CheckPathsBetweenNodes
+ pathCheck = new CheckPathsBetweenNodes(
+ cfg,
+ cfg.getDirectedGraphNode(getDefCfgNode()),
+ cfg.getDirectedGraphNode(useCfgNode),
+ SIDE_EFFECT_PREDICATE,
+ Predicates.
+ >alwaysTrue(),
+ false);
+ if (pathCheck.somePathsSatisfyPredicate()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testDoNotInlineCatchExpression1a() {
+ noInline(
+ ""var a;\n"" +
+ ""try {\n"" +
+ "" throw Error(\""\"");\n"" +
+ ""}catch(err) {"" +
+ "" a = err + 1;\n"" +
+ ""}\n"" +
+ ""return a.stack\n"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void process(Node externs, Node root) {
+ (new NodeTraversal(compiler, this)).traverse(root);
+ }
+
+// Test Case
+[/INST]
+ public void testInlineAcrossSideEffect1() {
+ // This can't be inlined because print() has side-effects and might change
+ // the definition of noSFX.
+ //
+ // noSFX must be both const and pure in order to inline it.
+ noInline(""var y; var x = noSFX(y); print(x)"");
+ //inline(""var y; var x = noSFX(y); print(x)"", ""var y;var x;print(noSFX(y))"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void computeDependence(final Definition def, Node rValue) {
+ NodeTraversal.traverse(compiler, rValue,
+ new AbstractCfgNodeTraversalCallback() {
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ if (n.isName() && jsScope.isDeclared(n.getString(), true)) {
+ Var dep = jsScope.getVar(n.getString());
+ def.depends.add(dep);
+ }
+ }
+ });
+ }
+
+// Test Case
+[/INST]
+ public void testInlineAcrossSideEffect1() {
+ // This can't be inlined because print() has side-effects and might change
+ // the definition of noSFX.
+ //
+ // noSFX must be both const and pure in order to inline it.
+ noInline(""var y; var x = noSFX(y); print(x)"");
+ //inline(""var y; var x = noSFX(y); print(x)"", ""var y;var x;print(noSFX(y))"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Node getDef(String name, Node useNode) {
+ Preconditions.checkArgument(getCfg().hasNode(useNode));
+ GraphNode n = getCfg().getNode(useNode);
+ FlowState state = n.getAnnotation();
+ Definition def = state.getIn().reachingDef.get(jsScope.getVar(name));
+ if (def == null) {
+ return null;
+ } else {
+ return def.node;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testInlineAcrossSideEffect1() {
+ // This can't be inlined because print() has side-effects and might change
+ // the definition of noSFX.
+ //
+ // noSFX must be both const and pure in order to inline it.
+ noInline(""var y; var x = noSFX(y); print(x)"");
+ //inline(""var y; var x = noSFX(y); print(x)"", ""var y;var x;print(noSFX(y))"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Node parseInputs() {
+ boolean devMode = options.devMode != DevMode.OFF;
+
+ // If old roots exist (we are parsing a second time), detach each of the
+ // individual file parse trees.
+ if (externsRoot != null) {
+ externsRoot.detachChildren();
+ }
+ if (jsRoot != null) {
+ jsRoot.detachChildren();
+ }
+
+ // Parse main js sources.
+ jsRoot = IR.block();
+ jsRoot.setIsSyntheticBlock(true);
+
+ externsRoot = IR.block();
+ externsRoot.setIsSyntheticBlock(true);
+
+ externAndJsRoot = IR.block(externsRoot, jsRoot);
+ externAndJsRoot.setIsSyntheticBlock(true);
+
+ if (options.tracer.isOn()) {
+ tracker = new PerformanceTracker(jsRoot, options.tracer);
+ addChangeHandler(tracker.getCodeChangeHandler());
+ }
+
+ Tracer tracer = newTracer(""parseInputs"");
+
+ try {
+ // Parse externs sources.
+ for (CompilerInput input : externs) {
+ Node n = input.getAstRoot(this);
+ if (hasErrors()) {
+ return null;
+ }
+ externsRoot.addChildToBack(n);
+ }
+
+ // Modules inferred in ProcessCommonJS pass.
+ if (options.transformAMDToCJSModules || options.processCommonJSModules) {
+ processAMDAndCommonJSModules();
+ }
+
+ // Check if inputs need to be rebuilt from modules.
+ boolean staleInputs = false;
+
+ // Check if the sources need to be re-ordered.
+ if (options.dependencyOptions.needsManagement() &&
+ !options.skipAllPasses &&
+ options.closurePass) {
+ for (CompilerInput input : inputs) {
+ // Forward-declare all the provided types, so that they
+ // are not flagged even if they are dropped from the process.
+ for (String provide : input.getProvides()) {
+ getTypeRegistry().forwardDeclareType(provide);
+ }
+ }
+
+ try {
+ inputs =
+ (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)
+ .manageDependencies(options.dependencyOptions, inputs);
+ staleInputs = true;
+ } catch (CircularDependencyException e) {
+ report(JSError.make(
+ JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));
+
+ // If in IDE mode, we ignore the error and keep going.
+ if (hasErrors()) {
+ return null;
+ }
+ } catch (MissingProvideException e) {
+ report(JSError.make(
+ MISSING_ENTRY_ERROR, e.getMessage()));
+
+ // If in IDE mode, we ignore the error and keep going.
+ if (hasErrors()) {
+ return null;
+ }
+ }
+ }
+
+ for (CompilerInput input : inputs) {
+ Node n = input.getAstRoot(this);
+
+ // Inputs can have a null AST during initial parse.
+ if (n == null) {
+ continue;
+ }
+
+ if (n.getJSDocInfo() != null) {
+ JSDocInfo info = n.getJSDocInfo();
+ if (info.isExterns()) {
+ // If the input file is explicitly marked as an externs file, then
+ // assume the programmer made a mistake and throw it into
+ // the externs pile anyways.
+ externsRoot.addChildToBack(n);
+ input.setIsExtern(true);
+
+ input.getModule().remove(input);
+
+ externs.add(input);
+ staleInputs = true;
+ } else if (info.isNoCompile()) {
+ input.getModule().remove(input);
+ staleInputs = true;
+ }
+ }
+ }
+
+ if (staleInputs) {
+ fillEmptyModules(modules);
+ rebuildInputsFromModules();
+ }
+
+ // Build the AST.
+ for (CompilerInput input : inputs) {
+ Node n = input.getAstRoot(this);
+ if (n == null) {
+ continue;
+ }
+
+ if (devMode) {
+ runSanityCheck();
+ if (hasErrors()) {
+ return null;
+ }
+ }
+
+ if (options.sourceMapOutputPath != null ||
+ options.nameReferenceReportPath != null) {
+
+ // Annotate the nodes in the tree with information from the
+ // input file. This information is used to construct the SourceMap.
+ SourceInformationAnnotator sia =
+ new SourceInformationAnnotator(
+ input.getName(), options.devMode != DevMode.OFF);
+ NodeTraversal.traverse(this, n, sia);
+ }
+
+ jsRoot.addChildToBack(n);
+ }
+
+ if (hasErrors()) {
+ return null;
+ }
+ return externAndJsRoot;
+ } finally {
+ stopTracer(tracer, ""parseInputs"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDependencySortingWhitespaceMode() {
+ args.add(""--manage_closure_dependencies"");
+ args.add(""--compilation_level=WHITESPACE_ONLY"");
+ test(new String[] {
+ ""goog.require('beer');"",
+ ""goog.provide('beer');\ngoog.require('hops');"",
+ ""goog.provide('hops');"",
+ },
+ new String[] {
+ ""goog.provide('hops');"",
+ ""goog.provide('beer');\ngoog.require('hops');"",
+ ""goog.require('beer');""
+ });
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
+ WhitespaceOption option) {
+
+ if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
+ token == JsDocToken.EOF) {
+ return new ExtractionInfo("""", token);
+ }
+
+ stream.update();
+ int startLineno = stream.getLineno();
+ int startCharno = stream.getCharno() + 1;
+
+ // Read the content from the first line.
+ String line = stream.getRemainingJSDocLine();
+ if (option != WhitespaceOption.PRESERVE) {
+ line = line.trim();
+ }
+
+ StringBuilder builder = new StringBuilder();
+ builder.append(line);
+
+ state = State.SEARCHING_ANNOTATION;
+ token = next();
+
+ boolean ignoreStar = false;
+
+ // Track the start of the line to count whitespace that
+ // the tokenizer skipped. Because this case is rare, it's easier
+ // to do this here than in the tokenizer.
+
+ do {
+ switch (token) {
+ case STAR:
+ if (ignoreStar) {
+ // Mark the position after the star as the new start of the line.
+ } else {
+ // The star is part of the comment.
+ if (builder.length() > 0) {
+ builder.append(' ');
+ }
+
+ builder.append('*');
+ }
+
+ token = next();
+ continue;
+
+ case EOL:
+ if (option != WhitespaceOption.SINGLE_LINE) {
+ builder.append(""\n"");
+ }
+
+ ignoreStar = true;
+ token = next();
+ continue;
+
+ default:
+ ignoreStar = false;
+ state = State.SEARCHING_ANNOTATION;
+
+ // All tokens must be separated by a space.
+
+ if (token == JsDocToken.EOC ||
+ token == JsDocToken.EOF ||
+ // When we're capturing a license block, annotations
+ // in the block are ok.
+ (token == JsDocToken.ANNOTATION &&
+ option != WhitespaceOption.PRESERVE)) {
+ String multilineText = builder.toString();
+
+ if (option != WhitespaceOption.PRESERVE) {
+ multilineText = multilineText.trim();
+ }
+
+ int endLineno = stream.getLineno();
+ int endCharno = stream.getCharno();
+
+ if (multilineText.length() > 0) {
+ jsdocBuilder.markText(multilineText, startLineno, startCharno,
+ endLineno, endCharno);
+ }
+
+ return new ExtractionInfo(multilineText, token);
+ }
+
+ if (builder.length() > 0) {
+ builder.append(' ');
+ }
+ builder.append(toString(token));
+
+ line = stream.getRemainingJSDocLine();
+
+ if (option != WhitespaceOption.PRESERVE) {
+ line = trimEnd(line);
+ }
+
+ builder.append(line);
+ token = next();
+ }
+ } while (true);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue701() {
+ // Check ASCII art in license comments.
+ String ascii = ""/**\n"" +
+ "" * @preserve\n"" +
+ "" This\n"" +
+ "" is\n"" +
+ "" ASCII ART\n"" +
+ ""*/"";
+ String result = ""/*\n\n"" +
+ "" This\n"" +
+ "" is\n"" +
+ "" ASCII ART\n"" +
+ ""*/\n"";
+ testSame(createCompilerOptions(), ascii);
+ assertEquals(result, lastCompiler.toSource());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void matchConstraint(ObjectType constraintObj) {
+ // We only want to match contraints on anonymous types.
+
+ // Handle the case where the constraint object is a record type.
+ //
+ // param constraintObj {{prop: (number|undefined)}}
+ // function f(constraintObj) {}
+ // f({});
+ //
+ // We want to modify the object literal to match the constraint, by
+ // taking any each property on the record and trying to match
+ // properties on this object.
+ if (constraintObj.isRecordType()) {
+ for (String prop : constraintObj.getOwnPropertyNames()) {
+ JSType propType = constraintObj.getPropertyType(prop);
+ if (!isPropertyTypeDeclared(prop)) {
+ JSType typeToInfer = propType;
+ if (!hasProperty(prop)) {
+ typeToInfer = getNativeType(JSTypeNative.VOID_TYPE)
+ .getLeastSupertype(propType);
+ }
+ defineInferredProperty(prop, typeToInfer, null);
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue700() throws Exception {
+ testTypes(
+ ""/**\n"" +
+ "" * @param {{text: string}} opt_data\n"" +
+ "" * @return {string}\n"" +
+ "" */\n"" +
+ ""function temp1(opt_data) {\n"" +
+ "" return opt_data.text;\n"" +
+ ""}\n"" +
+ ""\n"" +
+ ""/**\n"" +
+ "" * @param {{activity: (boolean|number|string|null|Object)}} opt_data\n"" +
+ "" * @return {string}\n"" +
+ "" */\n"" +
+ ""function temp2(opt_data) {\n"" +
+ "" /** @notypecheck */\n"" +
+ "" function __inner() {\n"" +
+ "" return temp1(opt_data.activity);\n"" +
+ "" }\n"" +
+ "" return __inner();\n"" +
+ ""}\n"" +
+ ""\n"" +
+ ""/**\n"" +
+ "" * @param {{n: number, text: string, b: boolean}} opt_data\n"" +
+ "" * @return {string}\n"" +
+ "" */\n"" +
+ ""function temp3(opt_data) {\n"" +
+ "" return 'n: ' + opt_data.n + ', t: ' + opt_data.text + '.';\n"" +
+ ""}\n"" +
+ ""\n"" +
+ ""function callee() {\n"" +
+ "" var output = temp3({\n"" +
+ "" n: 0,\n"" +
+ "" text: 'a string',\n"" +
+ "" b: true\n"" +
+ "" })\n"" +
+ "" alert(output);\n"" +
+ ""}\n"" +
+ ""\n"" +
+ ""callee();"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void add(Node n, Context context) {
+ if (!cc.continueProcessing()) {
+ return;
+ }
+
+ int type = n.getType();
+ String opstr = NodeUtil.opToStr(type);
+ int childCount = n.getChildCount();
+ Node first = n.getFirstChild();
+ Node last = n.getLastChild();
+
+ // Handle all binary operators
+ if (opstr != null && first != last) {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad binary operator \""%s\"": expected 2 arguments but got %s"",
+ opstr, childCount);
+ int p = NodeUtil.precedence(type);
+
+ // For right-hand-side of operations, only pass context if it's
+ // the IN_FOR_INIT_CLAUSE one.
+ Context rhsContext = getContextForNoInOperator(context);
+
+ // Handle associativity.
+ // e.g. if the parse tree is a * (b * c),
+ // we can simply generate a * b * c.
+ if (last.getType() == type &&
+ NodeUtil.isAssociative(type)) {
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p, rhsContext);
+ } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {
+ // Assignments are the only right-associative binary operators
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p, rhsContext);
+ } else {
+ addExpr(first, p, context);
+ cc.addOp(opstr, true);
+ addExpr(last, p + 1, rhsContext);
+ }
+ return;
+ }
+
+ cc.startSourceMapping(n);
+
+ switch (type) {
+ case Token.TRY: {
+ Preconditions.checkState(first.getNext().isBlock() &&
+ !first.getNext().hasMoreThanOneChild());
+ Preconditions.checkState(childCount >= 2 && childCount <= 3);
+
+ add(""try"");
+ add(first, Context.PRESERVE_BLOCK);
+
+ // second child contains the catch block, or nothing if there
+ // isn't a catch block
+ Node catchblock = first.getNext().getFirstChild();
+ if (catchblock != null) {
+ add(catchblock);
+ }
+
+ if (childCount == 3) {
+ add(""finally"");
+ add(last, Context.PRESERVE_BLOCK);
+ }
+ break;
+ }
+
+ case Token.CATCH:
+ Preconditions.checkState(childCount == 2);
+ add(""catch("");
+ add(first);
+ add("")"");
+ add(last, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.THROW:
+ Preconditions.checkState(childCount == 1);
+ add(""throw"");
+ add(first);
+
+ // Must have a ';' after a throw statement, otherwise safari can't
+ // parse this.
+ cc.endStatement(true);
+ break;
+
+ case Token.RETURN:
+ add(""return"");
+ if (childCount == 1) {
+ add(first);
+ } else {
+ Preconditions.checkState(childCount == 0);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.VAR:
+ if (first != null) {
+ add(""var "");
+ addList(first, false, getContextForNoInOperator(context));
+ }
+ break;
+
+ case Token.LABEL_NAME:
+ Preconditions.checkState(!n.getString().isEmpty());
+ addIdentifier(n.getString());
+ break;
+
+ case Token.NAME:
+ if (first == null || first.isEmpty()) {
+ addIdentifier(n.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ addIdentifier(n.getString());
+ cc.addOp(""="", true);
+ if (first.isComma()) {
+ addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);
+ } else {
+ // Add expression, consider nearby code at lowest level of
+ // precedence.
+ addExpr(first, 0, getContextForNoInOperator(context));
+ }
+ }
+ break;
+
+ case Token.ARRAYLIT:
+ add(""["");
+ addArrayList(first);
+ add(""]"");
+ break;
+
+ case Token.PARAM_LIST:
+ add(""("");
+ addList(first);
+ add("")"");
+ break;
+
+ case Token.COMMA:
+ Preconditions.checkState(childCount == 2);
+ unrollBinaryOperator(n, Token.COMMA, "","", context, Context.OTHER, 0, 0);
+ break;
+
+ case Token.NUMBER:
+ Preconditions.checkState(childCount == 0);
+ cc.addNumber(n.getDouble());
+ break;
+
+ case Token.TYPEOF:
+ case Token.VOID:
+ case Token.NOT:
+ case Token.BITNOT:
+ case Token.POS: {
+ // All of these unary operators are right-associative
+ Preconditions.checkState(childCount == 1);
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type), Context.OTHER);
+ break;
+ }
+
+ case Token.NEG: {
+ Preconditions.checkState(childCount == 1);
+
+ // It's important to our sanity checker that the code
+ // we print produces the same AST as the code we parse back.
+ // NEG is a weird case because Rhino parses ""- -2"" as ""2"".
+ if (n.getFirstChild().isNumber()) {
+ cc.addNumber(-n.getFirstChild().getDouble());
+ } else {
+ cc.addOp(NodeUtil.opToStrNoFail(type), false);
+ addExpr(first, NodeUtil.precedence(type), Context.OTHER);
+ }
+
+ break;
+ }
+
+ case Token.HOOK: {
+ Preconditions.checkState(childCount == 3);
+ int p = NodeUtil.precedence(type);
+ addExpr(first, p + 1, context);
+ cc.addOp(""?"", true);
+ addExpr(first.getNext(), 1, Context.OTHER);
+ cc.addOp("":"", true);
+ addExpr(last, 1, Context.OTHER);
+ break;
+ }
+
+ case Token.REGEXP:
+ if (!first.isString() ||
+ !last.isString()) {
+ throw new Error(""Expected children to be strings"");
+ }
+
+ String regexp = regexpEscape(first.getString(), outputCharsetEncoder);
+
+ // I only use one .add because whitespace matters
+ if (childCount == 2) {
+ add(regexp + last.getString());
+ } else {
+ Preconditions.checkState(childCount == 1);
+ add(regexp);
+ }
+ break;
+
+ case Token.FUNCTION:
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ Preconditions.checkState(childCount == 3);
+ boolean funcNeedsParens = (context == Context.START_OF_EXPR);
+ if (funcNeedsParens) {
+ add(""("");
+ }
+
+ add(""function"");
+ add(first);
+
+ add(first.getNext());
+ add(last, Context.PRESERVE_BLOCK);
+ cc.endFunction(context == Context.STATEMENT);
+
+ if (funcNeedsParens) {
+ add("")"");
+ }
+ break;
+
+ case Token.GETTER_DEF:
+ case Token.SETTER_DEF:
+ Preconditions.checkState(n.getParent().isObjectLit());
+ Preconditions.checkState(childCount == 1);
+ Preconditions.checkState(first.isFunction());
+
+ // Get methods are unnamed
+ Preconditions.checkState(first.getFirstChild().getString().isEmpty());
+ if (type == Token.GETTER_DEF) {
+ // Get methods have no parameters.
+ Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());
+ add(""get "");
+ } else {
+ // Set methods have one parameter.
+ Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());
+ add(""set "");
+ }
+
+ // The name is on the GET or SET node.
+ String name = n.getString();
+ Node fn = first;
+ Node parameters = fn.getChildAtIndex(1);
+ Node body = fn.getLastChild();
+
+ // Add the property name.
+ if (!n.isQuotedString() &&
+ TokenStream.isJSIdentifier(name) &&
+ // do not encode literally any non-literal characters that were
+ // unicode escaped.
+ NodeUtil.isLatin(name)) {
+ add(name);
+ } else {
+ // Determine if the string is a simple number.
+ double d = getSimpleNumber(name);
+ if (!Double.isNaN(d)) {
+ cc.addNumber(d);
+ } else {
+ addJsString(n);
+ }
+ }
+
+ add(parameters);
+ add(body, Context.PRESERVE_BLOCK);
+ break;
+
+ case Token.SCRIPT:
+ case Token.BLOCK: {
+ if (n.getClass() != Node.class) {
+ throw new Error(""Unexpected Node subclass."");
+ }
+ boolean preserveBlock = context == Context.PRESERVE_BLOCK;
+ if (preserveBlock) {
+ cc.beginBlock();
+ }
+
+ boolean preferLineBreaks =
+ type == Token.SCRIPT ||
+ (type == Token.BLOCK &&
+ !preserveBlock &&
+ n.getParent() != null &&
+ n.getParent().isScript());
+ for (Node c = first; c != null; c = c.getNext()) {
+ add(c, Context.STATEMENT);
+
+ // VAR doesn't include ';' since it gets used in expressions
+ if (c.isVar()) {
+ cc.endStatement();
+ }
+
+ if (c.isFunction()) {
+ cc.maybeLineBreak();
+ }
+
+ // Prefer to break lines in between top-level statements
+ // because top level statements are more homogeneous.
+ if (preferLineBreaks) {
+ cc.notePreferredLineBreak();
+ }
+ }
+ if (preserveBlock) {
+ cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));
+ }
+ break;
+ }
+
+ case Token.FOR:
+ if (childCount == 4) {
+ add(""for("");
+ if (first.isVar()) {
+ add(first, Context.IN_FOR_INIT_CLAUSE);
+ } else {
+ addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);
+ }
+ add("";"");
+ add(first.getNext());
+ add("";"");
+ add(first.getNext().getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ Preconditions.checkState(childCount == 3);
+ add(""for("");
+ add(first);
+ add(""in"");
+ add(first.getNext());
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ }
+ break;
+
+ case Token.DO:
+ Preconditions.checkState(childCount == 2);
+ add(""do"");
+ addNonEmptyStatement(first, Context.OTHER, false);
+ add(""while("");
+ add(last);
+ add("")"");
+ cc.endStatement();
+ break;
+
+ case Token.WHILE:
+ Preconditions.checkState(childCount == 2);
+ add(""while("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.EMPTY:
+ Preconditions.checkState(childCount == 0);
+ break;
+
+ case Token.GETPROP: {
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETPROP: expected 2 children, but got %s"", childCount);
+ Preconditions.checkState(
+ last.isString(),
+ ""Bad GETPROP: RHS should be STRING"");
+ boolean needsParens = (first.isNumber());
+ if (needsParens) {
+ add(""("");
+ }
+ addExpr(first, NodeUtil.precedence(type), context);
+ if (needsParens) {
+ add("")"");
+ }
+ add(""."");
+ addIdentifier(last.getString());
+ break;
+ }
+
+ case Token.GETELEM:
+ Preconditions.checkState(
+ childCount == 2,
+ ""Bad GETELEM: expected 2 children but got %s"", childCount);
+ addExpr(first, NodeUtil.precedence(type), context);
+ add(""["");
+ add(first.getNext());
+ add(""]"");
+ break;
+
+ case Token.WITH:
+ Preconditions.checkState(childCount == 2);
+ add(""with("");
+ add(first);
+ add("")"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ break;
+
+ case Token.INC:
+ case Token.DEC: {
+ Preconditions.checkState(childCount == 1);
+ String o = type == Token.INC ? ""++"" : ""--"";
+ int postProp = n.getIntProp(Node.INCRDECR_PROP);
+ // A non-zero post-prop value indicates a post inc/dec, default of zero
+ // is a pre-inc/dec.
+ if (postProp != 0) {
+ addExpr(first, NodeUtil.precedence(type), context);
+ cc.addOp(o, false);
+ } else {
+ cc.addOp(o, false);
+ add(first);
+ }
+ break;
+ }
+
+ case Token.CALL:
+ // We have two special cases here:
+ // 1) If the left hand side of the call is a direct reference to eval,
+ // then it must have a DIRECT_EVAL annotation. If it does not, then
+ // that means it was originally an indirect call to eval, and that
+ // indirectness must be preserved.
+ // 2) If the left hand side of the call is a property reference,
+ // then the call must not a FREE_CALL annotation. If it does, then
+ // that means it was originally an call without an explicit this and
+ // that must be preserved.
+ if (isIndirectEval(first)
+ || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {
+ add(""(0,"");
+ addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);
+ add("")"");
+ } else {
+ addExpr(first, NodeUtil.precedence(type), context);
+ }
+ add(""("");
+ addList(first.getNext());
+ add("")"");
+ break;
+
+ case Token.IF:
+ boolean hasElse = childCount == 3;
+ boolean ambiguousElseClause =
+ context == Context.BEFORE_DANGLING_ELSE && !hasElse;
+ if (ambiguousElseClause) {
+ cc.beginBlock();
+ }
+
+ add(""if("");
+ add(first);
+ add("")"");
+
+ if (hasElse) {
+ addNonEmptyStatement(
+ first.getNext(), Context.BEFORE_DANGLING_ELSE, false);
+ add(""else"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), false);
+ } else {
+ addNonEmptyStatement(first.getNext(), Context.OTHER, false);
+ Preconditions.checkState(childCount == 2);
+ }
+
+ if (ambiguousElseClause) {
+ cc.endBlock();
+ }
+ break;
+
+ case Token.NULL:
+ Preconditions.checkState(childCount == 0);
+ add(""null"");
+ break;
+
+ case Token.THIS:
+ Preconditions.checkState(childCount == 0);
+ add(""this"");
+ break;
+
+ case Token.FALSE:
+ Preconditions.checkState(childCount == 0);
+ add(""false"");
+ break;
+
+ case Token.TRUE:
+ Preconditions.checkState(childCount == 0);
+ add(""true"");
+ break;
+
+ case Token.CONTINUE:
+ Preconditions.checkState(childCount <= 1);
+ add(""continue"");
+ if (childCount == 1) {
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.DEBUGGER:
+ Preconditions.checkState(childCount == 0);
+ add(""debugger"");
+ cc.endStatement();
+ break;
+
+ case Token.BREAK:
+ Preconditions.checkState(childCount <= 1);
+ add(""break"");
+ if (childCount == 1) {
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add("" "");
+ add(first);
+ }
+ cc.endStatement();
+ break;
+
+ case Token.EXPR_RESULT:
+ Preconditions.checkState(childCount == 1);
+ add(first, Context.START_OF_EXPR);
+ cc.endStatement();
+ break;
+
+ case Token.NEW:
+ add(""new "");
+ int precedence = NodeUtil.precedence(type);
+
+ // If the first child contains a CALL, then claim higher precedence
+ // to force parentheses. Otherwise, when parsed, NEW will bind to the
+ // first viable parentheses (don't traverse into functions).
+ if (NodeUtil.containsType(
+ first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {
+ precedence = NodeUtil.precedence(first.getType()) + 1;
+ }
+ addExpr(first, precedence, Context.OTHER);
+
+ // '()' is optional when no arguments are present
+ Node next = first.getNext();
+ if (next != null) {
+ add(""("");
+ addList(next);
+ add("")"");
+ }
+ break;
+
+ case Token.STRING:
+ if (childCount !=
+ ((n.getParent() != null &&
+ n.getParent().isObjectLit()) ? 1 : 0)) {
+ throw new IllegalStateException(
+ ""Unexpected String children: "" + n.getParent().toStringTree());
+ }
+ addJsString(n);
+ break;
+
+ case Token.DELPROP:
+ Preconditions.checkState(childCount == 1);
+ add(""delete "");
+ add(first);
+ break;
+
+ case Token.OBJECTLIT: {
+ boolean needsParens = (context == Context.START_OF_EXPR);
+ if (needsParens) {
+ add(""("");
+ }
+ add(""{"");
+ for (Node c = first; c != null; c = c.getNext()) {
+ if (c != first) {
+ cc.listSeparator();
+ }
+
+ if (c.isGetterDef() || c.isSetterDef()) {
+ add(c);
+ } else {
+ Preconditions.checkState(c.isString());
+ String key = c.getString();
+ // Object literal property names don't have to be quoted if they
+ // are not JavaScript keywords
+ if (!c.isQuotedString() &&
+ !TokenStream.isKeyword(key) &&
+ TokenStream.isJSIdentifier(key) &&
+ // do not encode literally any non-literal characters that
+ // were unicode escaped.
+ NodeUtil.isLatin(key)) {
+ add(key);
+ } else {
+ // Determine if the string is a simple number.
+ double d = getSimpleNumber(key);
+ if (!Double.isNaN(d)) {
+ cc.addNumber(d);
+ } else {
+ addExpr(c, 1, Context.OTHER);
+ }
+ }
+ add("":"");
+ addExpr(c.getFirstChild(), 1, Context.OTHER);
+ }
+ }
+ add(""}"");
+ if (needsParens) {
+ add("")"");
+ }
+ break;
+ }
+
+ case Token.SWITCH:
+ add(""switch("");
+ add(first);
+ add("")"");
+ cc.beginBlock();
+ addAllSiblings(first.getNext());
+ cc.endBlock(context == Context.STATEMENT);
+ break;
+
+ case Token.CASE:
+ Preconditions.checkState(childCount == 2);
+ add(""case "");
+ add(first);
+ addCaseBody(last);
+ break;
+
+ case Token.DEFAULT_CASE:
+ Preconditions.checkState(childCount == 1);
+ add(""default"");
+ addCaseBody(first);
+ break;
+
+ case Token.LABEL:
+ Preconditions.checkState(childCount == 2);
+ if (!first.isLabelName()) {
+ throw new Error(""Unexpected token type. Should be LABEL_NAME."");
+ }
+ add(first);
+ add("":"");
+ addNonEmptyStatement(
+ last, getContextForNonEmptyExpression(context), true);
+ break;
+
+ default:
+ throw new Error(""Unknown type "" + type + ""\n"" + n.toStringTree());
+ }
+
+ cc.endSourceMapping(n);
+ }
+
+// Test Case
+[/INST]
+ public void testManyAdds() {
+ int numAdds = 10000;
+ List numbers = Lists.newArrayList(""0"", ""1"");
+ Node current = new Node(Token.ADD, Node.newNumber(0), Node.newNumber(1));
+ for (int i = 2; i < numAdds; i++) {
+ current = new Node(Token.ADD, current);
+
+ // 1000 is printed as 1E3, and screws up our test.
+ int num = i % 1000;
+ numbers.add(String.valueOf(num));
+ current.addChildToBack(Node.newNumber(num));
+ }
+
+ String expected = Joiner.on(""+"").join(numbers);
+ String actual = printNode(current).replace(""\n"", """");
+ assertEquals(expected, actual);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ void appendOp(String op, boolean binOp) {
+ if (binOp) {
+ if (getLastChar() != ' ') {
+ append("" "");
+ }
+ append(op);
+ append("" "");
+ } else {
+ append(op);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testManyAdds() {
+ int numAdds = 10000;
+ List numbers = Lists.newArrayList(""0"", ""1"");
+ Node current = new Node(Token.ADD, Node.newNumber(0), Node.newNumber(1));
+ for (int i = 2; i < numAdds; i++) {
+ current = new Node(Token.ADD, current);
+
+ // 1000 is printed as 1E3, and screws up our test.
+ int num = i % 1000;
+ numbers.add(String.valueOf(num));
+ current.addChildToBack(Node.newNumber(num));
+ }
+
+ String expected = Joiner.on(""+"").join(numbers);
+ String actual = printNode(current).replace(""\n"", """");
+ assertEquals(expected, actual);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void unrollBinaryOperator(
+ Node n, int op, String opStr, Context context,
+ Context rhsContext, int leftPrecedence, int rightPrecedence) {
+ Node firstNonOperator = n.getFirstChild();
+ while (firstNonOperator.getType() == op) {
+ firstNonOperator = firstNonOperator.getFirstChild();
+ }
+
+ addExpr(firstNonOperator, leftPrecedence, context);
+
+ Node current = firstNonOperator;
+ do {
+ current = current.getParent();
+ cc.listSeparator();
+ addExpr(current.getFirstChild().getNext(), rightPrecedence, rhsContext);
+ } while (current != n);
+ }
+
+// Test Case
+[/INST]
+ public void testManyAdds() {
+ int numAdds = 10000;
+ List numbers = Lists.newArrayList(""0"", ""1"");
+ Node current = new Node(Token.ADD, Node.newNumber(0), Node.newNumber(1));
+ for (int i = 2; i < numAdds; i++) {
+ current = new Node(Token.ADD, current);
+
+ // 1000 is printed as 1E3, and screws up our test.
+ int num = i % 1000;
+ numbers.add(String.valueOf(num));
+ current.addChildToBack(Node.newNumber(num));
+ }
+
+ String expected = Joiner.on(""+"").join(numbers);
+ String actual = printNode(current).replace(""\n"", """");
+ assertEquals(expected, actual);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void inferPropertyTypesToMatchConstraint(
+ JSType type, JSType constraint) {
+ if (type == null || constraint == null) {
+ return;
+ }
+
+ ObjectType constraintObj =
+ ObjectType.cast(constraint.restrictByNotNullOrUndefined());
+ if (constraintObj != null && constraintObj.isRecordType()) {
+ ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined());
+ if (objType != null) {
+ for (String prop : constraintObj.getOwnPropertyNames()) {
+ JSType propType = constraintObj.getPropertyType(prop);
+ if (!objType.isPropertyTypeDeclared(prop)) {
+ JSType typeToInfer = propType;
+ if (!objType.hasProperty(prop)) {
+ typeToInfer =
+ getNativeType(VOID_TYPE).getLeastSupertype(propType);
+ }
+ objType.defineInferredProperty(prop, typeToInfer, null);
+ }
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue669() throws Exception {
+ testTypes(
+ ""/** @return {{prop1: (Object|undefined)}} */"" +
+ ""function f(a) {"" +
+ "" var results;"" +
+ "" if (a) {"" +
+ "" results = {};"" +
+ "" results.prop1 = {a: 3};"" +
+ "" } else {"" +
+ "" results = {prop2: 3};"" +
+ "" }"" +
+ "" return results;"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean canInline(
+ Reference declaration,
+ Reference initialization,
+ Reference reference) {
+ if (!isValidDeclaration(declaration)
+ || !isValidInitialization(initialization)
+ || !isValidReference(reference)) {
+ return false;
+ }
+
+ // If the value is read more than once, skip it.
+ // VAR declarations and EXPR_RESULT don't need the value, but other
+ // ASSIGN expressions parents do.
+ if (declaration != initialization &&
+ !initialization.getGrandparent().isExprResult()) {
+ return false;
+ }
+
+ // Be very conservative and do no cross control structures or
+ // scope boundaries
+ if (declaration.getBasicBlock() != initialization.getBasicBlock()
+ || declaration.getBasicBlock() != reference.getBasicBlock()) {
+ return false;
+ }
+
+ // Do not inline into a call node. This would change
+ // the context in which it was being called. For example,
+ // var a = b.c;
+ // a();
+ // should not be inlined, because it calls a in the context of b
+ // rather than the context of the window.
+ // var a = b.c;
+ // f(a)
+ // is ok.
+ Node value = initialization.getAssignedValue();
+ Preconditions.checkState(value != null);
+ if (value.isGetProp()
+ && reference.getParent().isCall()
+ && reference.getParent().getFirstChild() == reference.getNode()) {
+ return false;
+ }
+
+ if (value.isFunction()) {
+ Node callNode = reference.getParent();
+ if (reference.getParent().isCall()) {
+ CodingConvention convention = compiler.getCodingConvention();
+ // Bug 2388531: Don't inline subclass definitions into class defining
+ // calls as this confused class removing logic.
+ SubclassRelationship relationship =
+ convention.getClassesDefinedByCall(callNode);
+ if (relationship != null) {
+ return false;
+ }
+
+ // issue 668: Don't inline singleton getter methods
+ // calls as this confused class removing logic.
+ }
+ }
+
+ return canMoveAggressively(value) ||
+ canMoveModerately(initialization, reference);
+ }
+
+// Test Case
+[/INST]
+ public void testSingletonGetter1() {
+ CompilerOptions options = createCompilerOptions();
+ CompilationLevel.ADVANCED_OPTIMIZATIONS
+ .setOptionsForCompilationLevel(options);
+ options.setCodingConvention(new ClosureCodingConvention());
+ test(options,
+ ""/** @const */\n"" +
+ ""var goog = goog || {};\n"" +
+ ""goog.addSingletonGetter = function(ctor) {\n"" +
+ "" ctor.getInstance = function() {\n"" +
+ "" return ctor.instance_ || (ctor.instance_ = new ctor());\n"" +
+ "" };\n"" +
+ ""};"" +
+ ""function Foo() {}\n"" +
+ ""goog.addSingletonGetter(Foo);"" +
+ ""Foo.prototype.bar = 1;"" +
+ ""function Bar() {}\n"" +
+ ""goog.addSingletonGetter(Bar);"" +
+ ""Bar.prototype.bar = 1;"",
+ """");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void traverseFunction(Node n, Node parent) {
+ Preconditions.checkState(n.getChildCount() == 3);
+ Preconditions.checkState(n.isFunction());
+
+ final Node fnName = n.getFirstChild();
+
+ boolean isFunctionExpression = (parent != null)
+ && NodeUtil.isFunctionExpression(n);
+
+ if (!isFunctionExpression) {
+ // Functions declarations are in the scope containing the declaration.
+ traverseBranch(fnName, n);
+ }
+
+ curNode = n;
+ pushScope(n);
+
+ if (isFunctionExpression) {
+ // Function expression names are only accessible within the function
+ // scope.
+ traverseBranch(fnName, n);
+ }
+
+ final Node args = fnName.getNext();
+ final Node body = args.getNext();
+
+ // Args
+ traverseBranch(args, n);
+
+ // Body
+ Preconditions.checkState(body.getNext() == null &&
+ body.isBlock());
+ traverseBranch(body, n);
+
+ popScope();
+ }
+
+// Test Case
+[/INST]
+ public void testIncompleteFunction() {
+ CompilerOptions options = createCompilerOptions();
+ options.ideMode = true;
+ DiagnosticType[] warnings = new DiagnosticType[]{
+ RhinoErrorReporter.PARSE_ERROR,
+ RhinoErrorReporter.PARSE_ERROR,
+ RhinoErrorReporter.PARSE_ERROR,
+ RhinoErrorReporter.PARSE_ERROR};
+ test(options,
+ new String[] { ""var foo = {bar: function(e) }"" },
+ new String[] { ""var foo = {bar: function(e){}};"" },
+ warnings
+ );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ Node processFunctionNode(FunctionNode functionNode) {
+ Name name = functionNode.getFunctionName();
+ Boolean isUnnamedFunction = false;
+ if (name == null) {
+ int functionType = functionNode.getFunctionType();
+ if (functionType != FunctionNode.FUNCTION_EXPRESSION) {
+ errorReporter.error(
+ ""unnamed function statement"",
+ sourceName,
+ functionNode.getLineno(), """", 0);
+
+ // Return the bare minimum to put the AST in a valid state.
+ return newNode(Token.EXPR_RESULT, Node.newNumber(0));
+ }
+ name = new Name();
+ name.setIdentifier("""");
+ isUnnamedFunction = true;
+ }
+ Node node = newNode(Token.FUNCTION);
+ Node newName = transform(name);
+ if (isUnnamedFunction) {
+ // Old Rhino tagged the empty name node with the line number of the
+ // declaration.
+ newName.setLineno(functionNode.getLineno());
+ // TODO(bowdidge) Mark line number of paren correctly.
+ // Same problem as below - the left paren might not be on the
+ // same line as the function keyword.
+ int lpColumn = functionNode.getAbsolutePosition() +
+ functionNode.getLp();
+ newName.setCharno(position2charno(lpColumn));
+ maybeSetLengthFrom(newName, name);
+ }
+
+ node.addChildToBack(newName);
+ Node lp = newNode(Token.PARAM_LIST);
+ // The left paren's complicated because it's not represented by an
+ // AstNode, so there's nothing that has the actual line number that it
+ // appeared on. We know the paren has to appear on the same line as the
+ // function name (or else a semicolon will be inserted.) If there's no
+ // function name, assume the paren was on the same line as the function.
+ // TODO(bowdidge): Mark line number of paren correctly.
+ Name fnName = functionNode.getFunctionName();
+ if (fnName != null) {
+ lp.setLineno(fnName.getLineno());
+ } else {
+ lp.setLineno(functionNode.getLineno());
+ }
+ int lparenCharno = functionNode.getLp() +
+ functionNode.getAbsolutePosition();
+
+ lp.setCharno(position2charno(lparenCharno));
+ for (AstNode param : functionNode.getParams()) {
+ lp.addChildToBack(transform(param));
+ }
+ node.addChildToBack(lp);
+
+ Node bodyNode = transform(functionNode.getBody());
+ // When in ideMode Rhino tries to parse some constructs the compiler
+ // doesn't support, repair it here. see Rhino's
+ // Parser#parseFunctionBodyExpr.
+ parseDirectives(bodyNode);
+ node.addChildToBack(bodyNode);
+ return node;
+ }
+
+// Test Case
+[/INST]
+ public void testIncompleteFunction() {
+ CompilerOptions options = createCompilerOptions();
+ options.ideMode = true;
+ DiagnosticType[] warnings = new DiagnosticType[]{
+ RhinoErrorReporter.PARSE_ERROR,
+ RhinoErrorReporter.PARSE_ERROR,
+ RhinoErrorReporter.PARSE_ERROR,
+ RhinoErrorReporter.PARSE_ERROR};
+ test(options,
+ new String[] { ""var foo = {bar: function(e) }"" },
+ new String[] { ""var foo = {bar: function(e){}};"" },
+ warnings
+ );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void addNumber(double x) {
+ // This is not pretty printing. This is to prevent misparsing of x- -4 as
+ // x--4 (which is a syntax error).
+ char prev = getLastChar();
+ boolean negativeZero = isNegativeZero(x);
+ if (x < 0 && prev == '-') {
+ add("" "");
+ }
+
+ if ((long) x == x && !negativeZero) {
+ long value = (long) x;
+ long mantissa = value;
+ int exp = 0;
+ if (Math.abs(x) >= 100) {
+ while (mantissa / 10 * Math.pow(10, exp + 1) == value) {
+ mantissa /= 10;
+ exp++;
+ }
+ }
+ if (exp > 2) {
+ add(Long.toString(mantissa) + ""E"" + Integer.toString(exp));
+ } else {
+ add(Long.toString(value));
+ }
+ } else {
+ add(String.valueOf(x));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testMinusNegativeZero() {
+ // Negative zero is weird, because we have to be able to distinguish
+ // it from positive zero (there are some subtle differences in behavior).
+ assertPrint(""x- -0"", ""x- -0.0"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ String toStringHelper(boolean forAnnotations) {
+ if (hasReferenceName()) {
+ return getReferenceName();
+ } else if (prettyPrint) {
+ // Don't pretty print recursively.
+ prettyPrint = false;
+
+ // Use a tree set so that the properties are sorted.
+ Set propertyNames = Sets.newTreeSet();
+ for (ObjectType current = this;
+ current != null && !current.isNativeObjectType() &&
+ propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES;
+ current = current.getImplicitPrototype()) {
+ propertyNames.addAll(current.getOwnPropertyNames());
+ }
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(""{"");
+
+ int i = 0;
+ for (String property : propertyNames) {
+ if (i > 0) {
+ sb.append("", "");
+ }
+
+ sb.append(property);
+ sb.append("": "");
+ sb.append(getPropertyType(property).toString());
+
+ ++i;
+ if (i == MAX_PRETTY_PRINTED_PROPERTIES) {
+ sb.append("", ..."");
+ break;
+ }
+ }
+
+ sb.append(""}"");
+
+ prettyPrint = true;
+ return sb.toString();
+ } else {
+ return ""{...}"";
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testRecursiveRecord() {
+ ProxyObjectType loop = new ProxyObjectType(registry, NUMBER_TYPE);
+ JSType record = new RecordTypeBuilder(registry)
+ .addProperty(""loop"", loop, null)
+ .addProperty(""number"", NUMBER_TYPE, null)
+ .addProperty(""string"", STRING_TYPE, null)
+ .build();
+ assertEquals(""{loop: number, number: number, string: string}"",
+ record.toString());
+
+ loop.setReferencedType(record);
+ assertEquals(""{loop: {...}, number: number, string: string}"",
+ record.toString());
+ assertEquals(""{loop: ?, number: number, string: string}"",
+ record.toAnnotationString());
+
+ Asserts.assertEquivalenceOperations(record, loop);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ JSType resolveInternal(ErrorReporter t, StaticScope enclosing) {
+ // TODO(user): Investigate whether it is really necessary to keep two
+ // different mechanisms for resolving named types, and if so, which order
+ // makes more sense. Now, resolution via registry is first in order to
+ // avoid triggering the warnings built into the resolution via properties.
+ boolean resolved = resolveViaRegistry(t, enclosing);
+ if (detectImplicitPrototypeCycle()) {
+ handleTypeCycle(t);
+ }
+
+ if (resolved) {
+ super.resolveInternal(t, enclosing);
+ finishPropertyContinuations();
+ return registry.isLastGeneration() ?
+ getReferencedType() : this;
+ }
+
+ resolveViaProperties(t, enclosing);
+ if (detectImplicitPrototypeCycle()) {
+ handleTypeCycle(t);
+ }
+
+ super.resolveInternal(t, enclosing);
+ if (isResolved()) {
+ finishPropertyContinuations();
+ }
+ return registry.isLastGeneration() ?
+ getReferencedType() : this;
+ }
+
+// Test Case
+[/INST]
+ public void testImplementsExtendsLoop() throws Exception {
+ testClosureTypesMultipleWarnings(
+ suppressMissingProperty(""foo"") +
+ ""/** @constructor \n * @implements {F} */var G = function() {};"" +
+ ""/** @constructor \n * @extends {G} */var F = function() {};"" +
+ ""alert((new F).foo);"",
+ Lists.newArrayList(
+ ""Parse error. Cycle detected in inheritance chain of type F""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void visit(NodeTraversal t, Node n, Node parent) {
+
+ // Record global variable and function declarations
+ if (t.inGlobalScope()) {
+ if (NodeUtil.isVarDeclaration(n)) {
+ NameInformation ns = createNameInformation(t, n, parent);
+ Preconditions.checkNotNull(ns);
+ recordSet(ns.name, n);
+ } else if (NodeUtil.isFunctionDeclaration(n)) {
+ Node nameNode = n.getFirstChild();
+ NameInformation ns = createNameInformation(t, nameNode, n);
+ if (ns != null) {
+ JsName nameInfo = getName(nameNode.getString(), true);
+ recordSet(nameInfo.name, nameNode);
+ }
+ } else if (NodeUtil.isObjectLitKey(n, parent)) {
+ NameInformation ns = createNameInformation(t, n, parent);
+ if (ns != null) {
+ recordSet(ns.name, n);
+ }
+ }
+ }
+
+ // Record assignments and call sites
+ if (n.isAssign()) {
+ Node nameNode = n.getFirstChild();
+
+ NameInformation ns = createNameInformation(t, nameNode, n);
+ if (ns != null) {
+ if (ns.isPrototype) {
+ recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n);
+ } else {
+ recordSet(ns.name, nameNode);
+ }
+ }
+ } else if (n.isCall()) {
+ Node nameNode = n.getFirstChild();
+ NameInformation ns = createNameInformation(t, nameNode, n);
+ if (ns != null && ns.onlyAffectsClassDef) {
+ JsName name = getName(ns.name, false);
+ if (name != null) {
+ refNodes.add(new ClassDefiningFunctionNode(
+ name, n, parent, parent.getParent()));
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue284() {
+ CompilerOptions options = createCompilerOptions();
+ options.smartNameRemoval = true;
+ test(options,
+ ""var goog = {};"" +
+ ""goog.inherits = function(x, y) {};"" +
+ ""var ns = {};"" +
+ ""/** @constructor */"" +
+ ""ns.PageSelectionModel = function() {};"" +
+ ""/** @constructor */"" +
+ ""ns.PageSelectionModel.FooEvent = function() {};"" +
+ ""/** @constructor */"" +
+ ""ns.PageSelectionModel.SelectEvent = function() {};"" +
+ ""goog.inherits(ns.PageSelectionModel.ChangeEvent,"" +
+ "" ns.PageSelectionModel.FooEvent);"",
+ """");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ FunctionTypeBuilder inferFromOverriddenFunction(
+ @Nullable FunctionType oldType, @Nullable Node paramsParent) {
+ if (oldType == null) {
+ return this;
+ }
+
+ returnType = oldType.getReturnType();
+ returnTypeInferred = oldType.isReturnTypeInferred();
+ if (paramsParent == null) {
+ // Not a function literal.
+ parametersNode = oldType.getParametersNode();
+ if (parametersNode == null) {
+ parametersNode = new FunctionParamBuilder(typeRegistry).build();
+ }
+ } else {
+ // We're overriding with a function literal. Apply type information
+ // to each parameter of the literal.
+ FunctionParamBuilder paramBuilder =
+ new FunctionParamBuilder(typeRegistry);
+ Iterator oldParams = oldType.getParameters().iterator();
+ boolean warnedAboutArgList = false;
+ boolean oldParamsListHitOptArgs = false;
+ for (Node currentParam = paramsParent.getFirstChild();
+ currentParam != null; currentParam = currentParam.getNext()) {
+ if (oldParams.hasNext()) {
+ Node oldParam = oldParams.next();
+ Node newParam = paramBuilder.newParameterFromNode(oldParam);
+
+ oldParamsListHitOptArgs = oldParamsListHitOptArgs ||
+ oldParam.isVarArgs() ||
+ oldParam.isOptionalArg();
+
+ // The subclass method might write its var_args as individual
+ // arguments.
+ if (currentParam.getNext() != null && newParam.isVarArgs()) {
+ newParam.setVarArgs(false);
+ newParam.setOptionalArg(true);
+ }
+ } else {
+ warnedAboutArgList |= addParameter(
+ paramBuilder,
+ typeRegistry.getNativeType(UNKNOWN_TYPE),
+ warnedAboutArgList,
+ codingConvention.isOptionalParameter(currentParam) ||
+ oldParamsListHitOptArgs,
+ codingConvention.isVarArgsParameter(currentParam));
+ }
+ }
+
+ // Clone any remaining params that aren't in the function literal.
+
+ parametersNode = paramBuilder.build();
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testMethodInference6() throws Exception {
+ testTypes(
+ ""/** @constructor */ function F() {}"" +
+ ""/** @param {number} x */ F.prototype.foo = function(x) { };"" +
+ ""/** @constructor \n * @extends {F} */ "" +
+ ""function G() {}"" +
+ ""/** @override */ G.prototype.foo = function() { };"" +
+ ""(new G()).foo(1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ FunctionTypeBuilder inferParameterTypes(@Nullable Node argsParent,
+ @Nullable JSDocInfo info) {
+ if (argsParent == null) {
+ if (info == null) {
+ return this;
+ } else {
+ return inferParameterTypes(info);
+ }
+ }
+
+ // arguments
+ Node oldParameterType = null;
+ if (parametersNode != null) {
+ oldParameterType = parametersNode.getFirstChild();
+ }
+
+ FunctionParamBuilder builder = new FunctionParamBuilder(typeRegistry);
+ boolean warnedAboutArgList = false;
+ Set allJsDocParams = (info == null) ?
+ Sets.newHashSet() :
+ Sets.newHashSet(info.getParameterNames());
+ boolean foundTemplateType = false;
+ boolean isVarArgs = false;
+ for (Node arg : argsParent.children()) {
+ String argumentName = arg.getString();
+ allJsDocParams.remove(argumentName);
+
+ // type from JSDocInfo
+ JSType parameterType = null;
+ boolean isOptionalParam = isOptionalParameter(arg, info);
+ isVarArgs = isVarArgsParameter(arg, info);
+
+ if (info != null && info.hasParameterType(argumentName)) {
+ parameterType =
+ info.getParameterType(argumentName).evaluate(scope, typeRegistry);
+ } else if (oldParameterType != null &&
+ oldParameterType.getJSType() != null) {
+ parameterType = oldParameterType.getJSType();
+ isOptionalParam = oldParameterType.isOptionalArg();
+ isVarArgs = oldParameterType.isVarArgs();
+ } else {
+ parameterType = typeRegistry.getNativeType(UNKNOWN_TYPE);
+ }
+
+ if (templateTypeName != null &&
+ parameterType.restrictByNotNullOrUndefined().isTemplateType()) {
+ if (foundTemplateType) {
+ reportError(TEMPLATE_TYPE_DUPLICATED, fnName);
+ }
+ foundTemplateType = true;
+ }
+ warnedAboutArgList |= addParameter(
+ builder, parameterType, warnedAboutArgList,
+ isOptionalParam,
+ isVarArgs);
+
+ if (oldParameterType != null) {
+ oldParameterType = oldParameterType.getNext();
+ }
+ }
+
+ // Copy over any old parameters that aren't in the param list.
+
+ if (templateTypeName != null && !foundTemplateType) {
+ reportError(TEMPLATE_TYPE_EXPECTED, fnName);
+ }
+
+ for (String inexistentName : allJsDocParams) {
+ reportWarning(INEXISTANT_PARAM, inexistentName, fnName);
+ }
+
+ parametersNode = builder.build();
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testMethodInference6() throws Exception {
+ testTypes(
+ ""/** @constructor */ function F() {}"" +
+ ""/** @param {number} x */ F.prototype.foo = function(x) { };"" +
+ ""/** @constructor \n * @extends {F} */ "" +
+ ""function G() {}"" +
+ ""/** @override */ G.prototype.foo = function() { };"" +
+ ""(new G()).foo(1);"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Node processForInLoop(ForInLoop loopNode) {
+
+ // Return the bare minimum to put the AST in a valid state.
+ return newNode(
+ Token.FOR,
+ transform(loopNode.getIterator()),
+ transform(loopNode.getIteratedObject()),
+ transformBlock(loopNode.getBody()));
+ }
+
+// Test Case
+[/INST]
+ public void testForEach() {
+ parseError(
+ ""function f(stamp, status) {\n"" +
+ "" for each ( var curTiming in this.timeLog.timings ) {\n"" +
+ "" if ( curTiming.callId == stamp ) {\n"" +
+ "" curTiming.flag = status;\n"" +
+ "" break;\n"" +
+ "" }\n"" +
+ "" }\n"" +
+ ""};"",
+ ""unsupported language extension: for each"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void attachLiteralTypes(NodeTraversal t, Node n) {
+ switch (n.getType()) {
+ case Token.NULL:
+ n.setJSType(getNativeType(NULL_TYPE));
+ break;
+
+ case Token.VOID:
+ n.setJSType(getNativeType(VOID_TYPE));
+ break;
+
+ case Token.STRING:
+ // Defer keys to the Token.OBJECTLIT case
+ if (!NodeUtil.isObjectLitKey(n, n.getParent())) {
+ n.setJSType(getNativeType(STRING_TYPE));
+ }
+ break;
+
+ case Token.NUMBER:
+ n.setJSType(getNativeType(NUMBER_TYPE));
+ break;
+
+ case Token.TRUE:
+ case Token.FALSE:
+ n.setJSType(getNativeType(BOOLEAN_TYPE));
+ break;
+
+ case Token.REGEXP:
+ n.setJSType(getNativeType(REGEXP_TYPE));
+ break;
+
+ case Token.OBJECTLIT:
+ defineObjectLiteral(n);
+ break;
+
+ // NOTE(nicksantos): If we ever support Array tuples,
+ // we will need to put ARRAYLIT here as well.
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLends10() throws Exception {
+ testTypes(
+ ""function defineClass(x) { return function() {}; } "" +
+ ""/** @constructor */"" +
+ ""var Foo = defineClass("" +
+ "" /** @lends {Foo.prototype} */ ({/** @type {number} */ bar: 1}));"" +
+ ""/** @return {string} */ function f() { return (new Foo()).bar; }"",
+ ""inconsistent return type\n"" +
+ ""found : number\n"" +
+ ""required: string"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void add(String newcode) {
+ maybeEndStatement();
+
+ if (newcode.length() == 0) {
+ return;
+ }
+
+ char c = newcode.charAt(0);
+ if ((isWordChar(c) || c == '\\') &&
+ isWordChar(getLastChar())) {
+ // need space to separate. This is not pretty printing.
+ // For example: ""return foo;""
+ append("" "");
+ // Do not allow a forward slash to appear after a DIV.
+ // For example,
+ // REGEXP DIV REGEXP
+ // is valid and should print like
+ // / // / /
+ }
+
+ append(newcode);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue620() {
+ assertPrint(""alert(/ / / / /);"", ""alert(/ // / /)"");
+ assertPrint(""alert(/ // / /);"", ""alert(/ // / /)"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void interpretAssigns() {
+ boolean changes = false;
+ do {
+ changes = false;
+
+ // We can't use traditional iterators and iterables for this list,
+ // because our lazily-evaluated continuations will modify it while
+ // we traverse it.
+ for (int current = 0; current < maybeUnreferenced.size(); current++) {
+ Var var = maybeUnreferenced.get(current);
+ if (referenced.contains(var)) {
+ maybeUnreferenced.remove(current);
+ current--;
+ } else {
+ boolean assignedToUnknownValue = false;
+ boolean hasPropertyAssign = false;
+
+ if (var.getParentNode().isVar() &&
+ !NodeUtil.isForIn(var.getParentNode().getParent())) {
+ Node value = var.getInitialValue();
+ assignedToUnknownValue = value != null &&
+ !NodeUtil.isLiteralValue(value, true);
+ } else {
+ // This was initialized to a function arg or a catch param
+ // or a for...in variable.
+ assignedToUnknownValue = true;
+ }
+
+ for (Assign assign : assignsByVar.get(var)) {
+ if (assign.isPropertyAssign) {
+ hasPropertyAssign = true;
+ } else if (!NodeUtil.isLiteralValue(
+ assign.assignNode.getLastChild(), true)) {
+ assignedToUnknownValue = true;
+ }
+ }
+
+ if (assignedToUnknownValue && hasPropertyAssign) {
+ changes = markReferencedVar(var) || changes;
+ maybeUnreferenced.remove(current);
+ current--;
+ }
+ }
+ }
+ } while (changes);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue618_1() {
+ this.removeGlobal = false;
+ testSame(
+ ""function f() {\n"" +
+ "" var a = [], b;\n"" +
+ "" a.push(b = []);\n"" +
+ "" b[0] = 1;\n"" +
+ "" return a;\n"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Assign(Node assignNode, Node nameNode, boolean isPropertyAssign) {
+ Preconditions.checkState(NodeUtil.isAssignmentOp(assignNode));
+ this.assignNode = assignNode;
+ this.nameNode = nameNode;
+ this.isPropertyAssign = isPropertyAssign;
+
+ this.maybeAliased = !assignNode.getParent().isExprResult();
+ this.mayHaveSecondarySideEffects =
+ maybeAliased ||
+ NodeUtil.mayHaveSideEffects(assignNode.getFirstChild()) ||
+ NodeUtil.mayHaveSideEffects(assignNode.getLastChild());
+ }
+
+// Test Case
+[/INST]
+ public void testIssue618_1() {
+ this.removeGlobal = false;
+ testSame(
+ ""function f() {\n"" +
+ "" var a = [], b;\n"" +
+ "" a.push(b = []);\n"" +
+ "" b[0] = 1;\n"" +
+ "" return a;\n"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testRecordTypeLeastSuperType2() {
+ RecordTypeBuilder builder = new RecordTypeBuilder(registry);
+ builder.addProperty(""e"", NUMBER_TYPE, null);
+ builder.addProperty(""b"", STRING_TYPE, null);
+ builder.addProperty(""c"", STRING_TYPE, null);
+ JSType otherRecordType = builder.build();
+
+ assertTypeEquals(
+ registry.createUnionType(recordType, otherRecordType),
+ recordType.getLeastSupertype(otherRecordType));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void addMapping(
+ Node node,
+ FilePosition outputStartPosition,
+ FilePosition outputEndPosition) {
+ String sourceFile = node.getSourceFileName();
+
+ // If the node does not have an associated source file or
+ // its line number is -1, then the node does not have sufficient
+ // information for a mapping to be useful.
+ if (sourceFile == null || node.getLineno() < 0) {
+ return;
+ }
+
+ sourceFile = fixupSourceLocation(sourceFile);
+
+ String originalName = (String) node.getProp(Node.ORIGINALNAME_PROP);
+
+ // Strangely, Rhino source lines are one based but columns are
+ // zero based.
+ // We don't change this for the v1 or v2 source maps but for
+ // v3 we make them both 0 based.
+
+ generator.addMapping(
+ sourceFile, originalName,
+ new FilePosition(node.getLineno(), node.getCharno()),
+ outputStartPosition, outputEndPosition);
+ }
+
+// Test Case
+[/INST]
+ public void testParseSourceMetaMap() throws Exception {
+ final String INPUT1 = ""file1"";
+ final String INPUT2 = ""file2"";
+ LinkedHashMap inputs = Maps.newLinkedHashMap();
+ inputs.put(INPUT1, ""var __FOO__ = 1;"");
+ inputs.put(INPUT2, ""var __BAR__ = 2;"");
+ RunResult result1 = compile(inputs.get(INPUT1), INPUT1);
+ RunResult result2 = compile(inputs.get(INPUT2), INPUT2);
+
+ final String MAP1 = ""map1"";
+ final String MAP2 = ""map2"";
+ final LinkedHashMap maps = Maps.newLinkedHashMap();
+ maps.put(MAP1, result1.sourceMapFileContent);
+ maps.put(MAP2, result2.sourceMapFileContent);
+
+ List sections = Lists.newArrayList();
+
+ StringBuilder output = new StringBuilder();
+ FilePosition offset = appendAndCount(output, result1.generatedSource);
+ sections.add(SourceMapSection.forURL(MAP1, 0, 0));
+ output.append(result2.generatedSource);
+ sections.add(
+ SourceMapSection.forURL(MAP2, offset.getLine(), offset.getColumn()));
+
+ SourceMapGeneratorV3 generator = new SourceMapGeneratorV3();
+ StringBuilder mapContents = new StringBuilder();
+ generator.appendIndexMapTo(mapContents, ""out.js"", sections);
+
+ check(inputs, output.toString(), mapContents.toString(),
+ new SourceMapSupplier() {
+ @Override
+ public String getSourceMap(String url){
+ return maps.get(url);
+ }});
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private OriginalMapping getOriginalMappingForEntry(Entry entry) {
+ if (entry.getSourceFileId() == UNMAPPED) {
+ return null;
+ } else {
+ // Adjust the line/column here to be start at 1.
+ Builder x = OriginalMapping.newBuilder()
+ .setOriginalFile(sources[entry.getSourceFileId()])
+ .setLineNumber(entry.getSourceLine())
+ .setColumnPosition(entry.getSourceColumn());
+ if (entry.getNameId() != UNMAPPED) {
+ x.setIdentifier(names[entry.getNameId()]);
+ }
+ return x.build();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testParseSourceMetaMap() throws Exception {
+ final String INPUT1 = ""file1"";
+ final String INPUT2 = ""file2"";
+ LinkedHashMap inputs = Maps.newLinkedHashMap();
+ inputs.put(INPUT1, ""var __FOO__ = 1;"");
+ inputs.put(INPUT2, ""var __BAR__ = 2;"");
+ RunResult result1 = compile(inputs.get(INPUT1), INPUT1);
+ RunResult result2 = compile(inputs.get(INPUT2), INPUT2);
+
+ final String MAP1 = ""map1"";
+ final String MAP2 = ""map2"";
+ final LinkedHashMap maps = Maps.newLinkedHashMap();
+ maps.put(MAP1, result1.sourceMapFileContent);
+ maps.put(MAP2, result2.sourceMapFileContent);
+
+ List sections = Lists.newArrayList();
+
+ StringBuilder output = new StringBuilder();
+ FilePosition offset = appendAndCount(output, result1.generatedSource);
+ sections.add(SourceMapSection.forURL(MAP1, 0, 0));
+ output.append(result2.generatedSource);
+ sections.add(
+ SourceMapSection.forURL(MAP2, offset.getLine(), offset.getColumn()));
+
+ SourceMapGeneratorV3 generator = new SourceMapGeneratorV3();
+ StringBuilder mapContents = new StringBuilder();
+ generator.appendIndexMapTo(mapContents, ""out.js"", sections);
+
+ check(inputs, output.toString(), mapContents.toString(),
+ new SourceMapSupplier() {
+ @Override
+ public String getSourceMap(String url){
+ return maps.get(url);
+ }});
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info,
+ Node n, Node parent, Node rhsValue) {
+ Node ownerNode = n.getFirstChild();
+ String ownerName = ownerNode.getQualifiedName();
+ String qName = n.getQualifiedName();
+ String propName = n.getLastChild().getString();
+ Preconditions.checkArgument(qName != null && ownerName != null);
+
+ // Precedence of type information on GETPROPs:
+ // 1) @type annnotation / @enum annotation
+ // 2) ASSIGN to FUNCTION literal
+ // 3) @param/@return annotation (with no function literal)
+ // 4) ASSIGN to something marked @const
+ // 5) ASSIGN to anything else
+ //
+ // 1, 3, and 4 are declarations, 5 is inferred, and 2 is a declaration iff
+ // the function has jsdoc or has not been declared before.
+ //
+ // FUNCTION literals are special because TypedScopeCreator is very smart
+ // about getting as much type information as possible for them.
+
+ // Determining type for #1 + #2 + #3 + #4
+ JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue);
+ if (valueType == null && rhsValue != null) {
+ // Determining type for #5
+ valueType = rhsValue.getJSType();
+ }
+ // Function prototypes are special.
+ // It's a common JS idiom to do:
+ // F.prototype = { ... };
+ // So if F does not have an explicitly declared super type,
+ // allow F.prototype to be redefined arbitrarily.
+ if (""prototype"".equals(propName)) {
+ Var qVar = scope.getVar(qName);
+ if (qVar != null) {
+ // If the programmer has declared that F inherits from Super,
+ // and they assign F.prototype to an object literal,
+ // then they are responsible for making sure that the object literal's
+ // implicit prototype is set up appropriately. We just obey
+ // the @extends tag.
+ ObjectType qVarType = ObjectType.cast(qVar.getType());
+ if (qVarType != null &&
+ rhsValue != null &&
+ rhsValue.isObjectLit()) {
+ typeRegistry.resetImplicitPrototype(
+ rhsValue.getJSType(), qVarType.getImplicitPrototype());
+ } else if (!qVar.isTypeInferred()) {
+ // If the programmer has declared that F inherits from Super,
+ // and they assign F.prototype to some arbitrary expression,
+ // there's not much we can do. We just ignore the expression,
+ // and hope they've annotated their code in a way to tell us
+ // what props are going to be on that prototype.
+ return;
+ }
+ if (qVar.getScope() == scope) {
+ scope.undeclare(qVar);
+ }
+ }
+ }
+
+ if (valueType == null) {
+ if (parent.isExprResult()) {
+ stubDeclarations.add(new StubDeclaration(
+ n,
+ t.getInput() != null && t.getInput().isExtern(),
+ ownerName));
+ }
+
+ return;
+ }
+
+ // NOTE(nicksantos): Determining whether a property is declared or not
+ // is really really obnoxious.
+ //
+ // The problem is that there are two (equally valid) coding styles:
+ //
+ // (function() {
+ // /* The authoritative definition of goog.bar. */
+ // goog.bar = function() {};
+ // })();
+ //
+ // function f() {
+ // goog.bar();
+ // /* Reset goog.bar to a no-op. */
+ // goog.bar = function() {};
+ // }
+ //
+ // In a dynamic language with first-class functions, it's very difficult
+ // to know which one the user intended without looking at lots of
+ // contextual information (the second example demonstrates a small case
+ // of this, but there are some really pathological cases as well).
+ //
+ // The current algorithm checks if either the declaration has
+ // jsdoc type information, or @const with a known type,
+ // or a function literal with a name we haven't seen before.
+ boolean inferred = true;
+ if (info != null) {
+ // Determining declaration for #1 + #3 + #4
+ inferred = !(info.hasType()
+ || info.hasEnumParameterType()
+ || (info.isConstant() && valueType != null
+ && !valueType.isUnknownType())
+ || FunctionTypeBuilder.isFunctionTypeDeclaration(info));
+ }
+
+ if (inferred) {
+ // Determining declaration for #2
+ inferred = !(rhsValue != null &&
+ rhsValue.isFunction() &&
+ (info != null || !scope.isDeclared(qName, false)));
+ }
+
+ if (!inferred) {
+ ObjectType ownerType = getObjectSlot(ownerName);
+ if (ownerType != null) {
+ // Only declare this as an official property if it has not been
+ // declared yet.
+ boolean isExtern = t.getInput() != null && t.getInput().isExtern();
+ if ((!ownerType.hasOwnProperty(propName) ||
+ ownerType.isPropertyTypeInferred(propName)) &&
+ ((isExtern && !ownerType.isNativeObjectType()) ||
+ !ownerType.isInstanceType())) {
+ // If the property is undeclared or inferred, declare it now.
+ ownerType.defineDeclaredProperty(propName, valueType, n);
+ }
+ }
+
+ // If the property is already declared, the error will be
+ // caught when we try to declare it in the current scope.
+ defineSlot(n, parent, valueType, inferred);
+ } else if (rhsValue != null && rhsValue.isTrue()) {
+ // We declare these for delegate proxy method properties.
+ FunctionType ownerType =
+ JSType.toMaybeFunctionType(getObjectSlot(ownerName));
+ if (ownerType != null) {
+ JSType ownerTypeOfThis = ownerType.getTypeOfThis();
+ String delegateName = codingConvention.getDelegateSuperclassName();
+ JSType delegateType = delegateName == null ?
+ null : typeRegistry.getType(delegateName);
+ if (delegateType != null &&
+ ownerTypeOfThis.isSubtype(delegateType)) {
+ defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true);
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue586() throws Exception {
+ testTypes(
+ ""/** @constructor */"" +
+ ""var MyClass = function() {};"" +
+ ""/** @param {boolean} success */"" +
+ ""MyClass.prototype.fn = function(success) {};"" +
+ ""MyClass.prototype.test = function() {"" +
+ "" this.fn();"" +
+ "" this.fn = function() {};"" +
+ ""};"",
+ ""Function MyClass.prototype.fn: called with 0 argument(s). "" +
+ ""Function requires at least 1 argument(s) "" +
+ ""and no more than 1 argument(s)."");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void enterScope(NodeTraversal t) {
+ Node declarationRoot = t.getScopeRoot();
+ Renamer renamer;
+ if (nameStack.isEmpty()) {
+ // If the contextual renamer is being used the starting context can not
+ // be a function.
+ Preconditions.checkState(
+ declarationRoot.getType() != Token.FUNCTION ||
+ !(rootRenamer instanceof ContextualRenamer));
+ Preconditions.checkState(t.inGlobalScope());
+ renamer = rootRenamer;
+ } else {
+ renamer = nameStack.peek().forChildScope();
+ }
+
+ if (declarationRoot.getType() == Token.FUNCTION) {
+ for (Node c = declarationRoot.getFirstChild().getNext().getFirstChild(); c != null; c = c.getNext()) {
+ String name = c.getString();
+ renamer.addDeclaredName(name);
+ }
+ Node functionBody = declarationRoot.getLastChild();
+ findDeclaredNames(functionBody, null, renamer);
+ } else
+ if (declarationRoot.getType() != Token.FUNCTION) {
+ // Add the block declarations
+ findDeclaredNames(declarationRoot, null, renamer);
+ }
+ nameStack.push(renamer);
+ }
+
+// Test Case
+[/INST]
+ public void testInline19b() {
+ helperInlineReferenceToFunction(
+ ""var x = 1; var y = 2;"" +
+ ""function foo(a,b){y = a; x = b;}; "" +
+ ""function bar() { foo(x,y); }"",
+ ""var x = 1; var y = 2;"" +
+ ""function foo(a,b){y = a; x = b;}; "" +
+ ""function bar() {"" +
+ ""{var b$$inline_1=y;"" +
+ ""y = x;"" +
+ ""x = b$$inline_1;}"" +
+ ""}"",
+ ""foo"", INLINE_BLOCK);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
+
+ switch (n.getType()) {
+ case Token.FUNCTION:
+ {
+ // Add recursive function name, if needed.
+ // NOTE: ""enterScope"" is called after we need to pick up this name.
+ Renamer renamer = nameStack.peek().forChildScope();
+
+ // If needed, add the function recursive name.
+ String name = n.getFirstChild().getString();
+ if (name != null && !name.isEmpty() && parent != null
+ && !NodeUtil.isFunctionDeclaration(n)) {
+ renamer.addDeclaredName(name);
+ }
+
+
+
+ // Add the function parameters
+
+ // Add the function body declarations
+
+ nameStack.push(renamer);
+ }
+ break;
+
+ case Token.CATCH:
+ {
+ Renamer renamer = nameStack.peek().forChildScope();
+
+ String name = n.getFirstChild().getString();
+ renamer.addDeclaredName(name);
+
+ nameStack.push(renamer);
+ }
+ break;
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testInline19b() {
+ helperInlineReferenceToFunction(
+ ""var x = 1; var y = 2;"" +
+ ""function foo(a,b){y = a; x = b;}; "" +
+ ""function bar() { foo(x,y); }"",
+ ""var x = 1; var y = 2;"" +
+ ""function foo(a,b){y = a; x = b;}; "" +
+ ""function bar() {"" +
+ ""{var b$$inline_1=y;"" +
+ ""y = x;"" +
+ ""x = b$$inline_1;}"" +
+ ""}"",
+ ""foo"", INLINE_BLOCK);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ switch (n.getType()) {
+ case Token.NAME:
+ String newName = getReplacementName(n.getString());
+ if (newName != null) {
+ Renamer renamer = nameStack.peek();
+ if (renamer.stripConstIfReplaced()) {
+ // TODO(johnlenz): Do we need to do anything about the javadoc?
+ n.removeProp(Node.IS_CONSTANT_NAME);
+ }
+ n.setString(newName);
+ t.getCompiler().reportCodeChange();
+ }
+ break;
+
+ case Token.FUNCTION:
+ // Remove the function body scope
+ // Remove function recursive name (if any).
+ nameStack.pop();
+ break;
+
+ // Note: The parameters and function body variables live in the
+ // same scope, we introduce the scope when in the ""shouldTraverse""
+ // visit of LP, but remove it when when we exit the function above.
+
+ case Token.CATCH:
+ // Remove catch except name from the stack of names.
+ nameStack.pop();
+ break;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testInline19b() {
+ helperInlineReferenceToFunction(
+ ""var x = 1; var y = 2;"" +
+ ""function foo(a,b){y = a; x = b;}; "" +
+ ""function bar() { foo(x,y); }"",
+ ""var x = 1; var y = 2;"" +
+ ""function foo(a,b){y = a; x = b;}; "" +
+ ""function bar() {"" +
+ ""{var b$$inline_1=y;"" +
+ ""y = x;"" +
+ ""x = b$$inline_1;}"" +
+ ""}"",
+ ""foo"", INLINE_BLOCK);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isInlinableObject(List refs) {
+ boolean ret = false;
+ Set validProperties = Sets.newHashSet();
+ for (Reference ref : refs) {
+ Node name = ref.getNode();
+ Node parent = ref.getParent();
+ Node gramps = ref.getGrandparent();
+
+ // Ignore most indirect references, like x.y (but not x.y(),
+ // since the function referenced by y might reference 'this').
+ //
+ if (parent.isGetProp()) {
+ Preconditions.checkState(parent.getFirstChild() == name);
+ // A call target may be using the object as a 'this' value.
+ if (gramps.isCall()
+ && gramps.getFirstChild() == parent) {
+ return false;
+ }
+
+ // Deleting a property has different semantics from deleting
+ // a variable, so deleted properties should not be inlined.
+
+ // NOTE(nicksantos): This pass's object-splitting algorithm has
+ // a blind spot. It assumes that if a property isn't defined on an
+ // object, then the value is undefined. This is not true, because
+ // Object.prototype can have arbitrary properties on it.
+ //
+ // We short-circuit this problem by bailing out if we see a reference
+ // to a property that isn't defined on the object literal. This
+ // isn't a perfect algorithm, but it should catch most cases.
+ String propName = parent.getLastChild().getString();
+ if (!validProperties.contains(propName)) {
+ if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {
+ validProperties.add(propName);
+ } else {
+ return false;
+ }
+ }
+ continue;
+ }
+
+ // Only rewrite VAR declarations or simple assignment statements
+ if (!isVarOrAssignExprLhs(name)) {
+ return false;
+ }
+
+ Node val = ref.getAssignedValue();
+ if (val == null) {
+ // A var with no assignment.
+ continue;
+ }
+
+ // We're looking for object literal assignments only.
+ if (!val.isObjectLit()) {
+ return false;
+ }
+
+ // Make sure that the value is not self-referential. IOW,
+ // disallow things like x = {b: x.a}.
+ //
+ // TODO: Only exclude unorderable self-referential
+ // assignments. i.e. x = {a: x.b, b: x.a} is not orderable,
+ // but x = {a: 1, b: x.a} is.
+ //
+ // Also, ES5 getters/setters aren't handled by this pass.
+ for (Node child = val.getFirstChild(); child != null;
+ child = child.getNext()) {
+ if (child.isGetterDef() ||
+ child.isSetterDef()) {
+ // ES5 get/set not supported.
+ return false;
+ }
+
+ validProperties.add(child.getString());
+
+ Node childVal = child.getFirstChild();
+ // Check if childVal is the parent of any of the passed in
+ // references, as that is how self-referential assignments
+ // will happen.
+ for (Reference t : refs) {
+ Node refNode = t.getParent();
+ while (!NodeUtil.isStatementBlock(refNode)) {
+ if (refNode == childVal) {
+ // There's a self-referential assignment
+ return false;
+ }
+ refNode = refNode.getParent();
+ }
+ }
+ }
+
+
+ // We have found an acceptable object literal assignment. As
+ // long as there are no other assignments that mess things up,
+ // we can inline.
+ ret = true;
+ }
+ return ret;
+ }
+
+// Test Case
+[/INST]
+ public void testNoInlineDeletedProperties() {
+ testSameLocal(
+ ""var foo = {bar:1};"" +
+ ""delete foo.bar;"" +
+ ""return foo.bar;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryFoldArrayJoin(Node n) {
+ Node callTarget = n.getFirstChild();
+
+ if (callTarget == null || !NodeUtil.isGetProp(callTarget)) {
+ return n;
+ }
+
+ Node right = callTarget.getNext();
+ if (right != null) {
+ if (!NodeUtil.isImmutableValue(right)) {
+ return n;
+ }
+ }
+
+ Node arrayNode = callTarget.getFirstChild();
+ Node functionName = arrayNode.getNext();
+
+ if ((arrayNode.getType() != Token.ARRAYLIT) ||
+ !functionName.getString().equals(""join"")) {
+ return n;
+ }
+
+ // "","" is the default, it doesn't need to be explicit
+
+ String joinString = (right == null) ? "","" : NodeUtil.getStringValue(right);
+ List arrayFoldedChildren = Lists.newLinkedList();
+ StringBuilder sb = null;
+ int foldedSize = 0;
+ Node prev = null;
+ Node elem = arrayNode.getFirstChild();
+ // Merges adjacent String nodes.
+ while (elem != null) {
+ if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) {
+ if (sb == null) {
+ sb = new StringBuilder();
+ } else {
+ sb.append(joinString);
+ }
+ sb.append(NodeUtil.getArrayElementStringValue(elem));
+ } else {
+ if (sb != null) {
+ Preconditions.checkNotNull(prev);
+ // + 2 for the quotes.
+ foldedSize += sb.length() + 2;
+ arrayFoldedChildren.add(
+ Node.newString(sb.toString()).copyInformationFrom(prev));
+ sb = null;
+ }
+ foldedSize += InlineCostEstimator.getCost(elem);
+ arrayFoldedChildren.add(elem);
+ }
+ prev = elem;
+ elem = elem.getNext();
+ }
+
+ if (sb != null) {
+ Preconditions.checkNotNull(prev);
+ // + 2 for the quotes.
+ foldedSize += sb.length() + 2;
+ arrayFoldedChildren.add(
+ Node.newString(sb.toString()).copyInformationFrom(prev));
+ }
+ // one for each comma.
+ foldedSize += arrayFoldedChildren.size() - 1;
+
+ int originalSize = InlineCostEstimator.getCost(n);
+ switch (arrayFoldedChildren.size()) {
+ case 0:
+ Node emptyStringNode = Node.newString("""");
+ n.getParent().replaceChild(n, emptyStringNode);
+ reportCodeChange();
+ return emptyStringNode;
+ case 1:
+ Node foldedStringNode = arrayFoldedChildren.remove(0);
+ if (foldedSize > originalSize) {
+ return n;
+ }
+ 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("""").copyInformationFrom(n),
+ foldedStringNode);
+ foldedStringNode = replacement;
+ }
+ n.getParent().replaceChild(n, foldedStringNode);
+ reportCodeChange();
+ return foldedStringNode;
+ default:
+ // No folding could actually be performed.
+ if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {
+ return n;
+ }
+ int kJoinOverhead = ""[].join()"".length();
+ foldedSize += kJoinOverhead;
+ foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0;
+ if (foldedSize > originalSize) {
+ return n;
+ }
+ arrayNode.detachChildren();
+ for (Node node : arrayFoldedChildren) {
+ arrayNode.addChildToBack(node);
+ }
+ reportCodeChange();
+ break;
+ }
+
+ return n;
+ }
+
+// Test Case
+[/INST]
+ public void testStringJoinAddSparse() {
+ fold(""x = [,,'a'].join(',')"", ""x = ',,a'"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void addNumber(double x) {
+ // This is not pretty printing. This is to prevent misparsing of x- -4 as
+ // x--4 (which is a syntax error).
+ char prev = getLastChar();
+ if (x < 0 && prev == '-') {
+ add("" "");
+ }
+
+ if ((long) x == x) {
+ long value = (long) x;
+ long mantissa = value;
+ int exp = 0;
+ if (Math.abs(x) >= 100) {
+ while (mantissa / 10 * Math.pow(10, exp + 1) == value) {
+ mantissa /= 10;
+ exp++;
+ }
+ }
+ if (exp > 2) {
+ add(Long.toString(mantissa) + ""E"" + Integer.toString(exp));
+ } else {
+ add(Long.toString(value));
+ }
+ } else {
+ add(String.valueOf(x));
+ }
+
+ }
+
+// Test Case
+[/INST]
+ public void testIssue582() {
+ assertPrint(""var x = -0.0;"", ""var x=-0.0"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean isSimpleNumber(String s) {
+ int len = s.length();
+ for (int index = 0; index < len; index++) {
+ char c = s.charAt(index);
+ if (c < '0' || c > '9') {
+ return false;
+ }
+ }
+ return len > 0;
+ }
+
+// Test Case
+[/INST]
+ public void testNumericKeys() {
+ assertPrint(""var x = {010: 1};"", ""var x={8:1}"");
+ assertPrint(""var x = {'010': 1};"", ""var x={\""010\"":1}"");
+
+ assertPrint(""var x = {0x10: 1};"", ""var x={16:1}"");
+ assertPrint(""var x = {'0x10': 1};"", ""var x={\""0x10\"":1}"");
+
+ // I was surprised at this result too.
+ assertPrint(""var x = {.2: 1};"", ""var x={\""0.2\"":1}"");
+ assertPrint(""var x = {'.2': 1};"", ""var x={\"".2\"":1}"");
+
+ assertPrint(""var x = {0.2: 1};"", ""var x={\""0.2\"":1}"");
+ assertPrint(""var x = {'0.2': 1};"", ""var x={\""0.2\"":1}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void replaceAssignmentExpression(Var v, Reference ref,
+ Map varmap) {
+ // Compute all of the assignments necessary
+ List nodes = Lists.newArrayList();
+ Node val = ref.getAssignedValue();
+ blacklistVarReferencesInTree(val, v.scope);
+ Preconditions.checkState(val.getType() == Token.OBJECTLIT);
+ Set all = Sets.newLinkedHashSet(varmap.keySet());
+ for (Node key = val.getFirstChild(); key != null;
+ key = key.getNext()) {
+ String var = key.getString();
+ Node value = key.removeFirstChild();
+ // TODO(user): Copy type information.
+ nodes.add(
+ new Node(Token.ASSIGN,
+ Node.newString(Token.NAME, varmap.get(var)), value));
+ all.remove(var);
+ }
+
+ // TODO(user): Better source information.
+ for (String var : all) {
+ nodes.add(
+ new Node(Token.ASSIGN,
+ Node.newString(Token.NAME, varmap.get(var)),
+ NodeUtil.newUndefinedNode(null)));
+ }
+
+ Node replacement;
+ // All assignments evaluate to true, so make sure that the
+ // expr statement evaluates to true in case it matters.
+ nodes.add(new Node(Token.TRUE));
+
+ // Join these using COMMA. A COMMA node must have 2 children, so we
+ // create a tree. In the tree the first child be the COMMA to match
+ // the parser, otherwise tree equality tests fail.
+ nodes = Lists.reverse(nodes);
+ replacement = new Node(Token.COMMA);
+ Node cur = replacement;
+ int i;
+ for (i = 0; i < nodes.size() - 2; i++) {
+ cur.addChildToFront(nodes.get(i));
+ Node t = new Node(Token.COMMA);
+ cur.addChildToFront(t);
+ cur = t;
+ }
+ cur.addChildToFront(nodes.get(i));
+ cur.addChildToFront(nodes.get(i + 1));
+
+ Node replace = ref.getParent();
+ replacement.copyInformationFromForTree(replace);
+
+ if (replace.getType() == Token.VAR) {
+ replace.getParent().replaceChild(
+ replace, NodeUtil.newExpr(replacement));
+ } else {
+ replace.getParent().replaceChild(replace, replacement);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBug545() {
+ testLocal(""var a = {}"", """");
+ testLocal(""var a; a = {}"", ""true"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void setPrototypeBasedOn(ObjectType baseType) {
+ // This is a bit weird. We need to successfully handle these
+ // two cases:
+ // Foo.prototype = new Bar();
+ // and
+ // Foo.prototype = {baz: 3};
+ // In the first case, we do not want new properties to get
+ // added to Bar. In the second case, we do want new properties
+ // to get added to the type of the anonymous object.
+ //
+ // We handle this by breaking it into two cases:
+ //
+ // In the first case, we create a new PrototypeObjectType and set
+ // its implicit prototype to the type being assigned. This ensures
+ // that Bar will not get any properties of Foo.prototype, but properties
+ // later assigned to Bar will get inherited properly.
+ //
+ // In the second case, we just use the anonymous object as the prototype.
+ if (baseType.hasReferenceName() ||
+ baseType.isUnknownType() ||
+ isNativeObjectType() ||
+ baseType.isFunctionPrototypeType() ||
+ !(baseType instanceof PrototypeObjectType)) {
+
+ baseType = new PrototypeObjectType(
+ registry, this.getReferenceName() + "".prototype"", baseType);
+ }
+ setPrototype((PrototypeObjectType) baseType);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue537a() throws Exception {
+ testTypes(
+ ""/** @constructor */ function Foo() {}"" +
+ ""Foo.prototype = {method: function() {}};"" +
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" * @extends {Foo}\n"" +
+ "" */\n"" +
+ ""function Bar() {"" +
+ "" Foo.call(this);"" +
+ "" if (this.baz()) this.method(1);"" +
+ ""}"" +
+ ""Bar.prototype = {"" +
+ "" baz: function() {"" +
+ "" return true;"" +
+ "" }"" +
+ ""};"" +
+ ""Bar.prototype.__proto__ = Foo.prototype;"",
+ ""Function Foo.prototype.method: called with 1 argument(s). "" +
+ ""Function requires at least 0 argument(s) "" +
+ ""and no more than 0 argument(s)."");
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean setPrototype(PrototypeObjectType prototype) {
+ if (prototype == null) {
+ return false;
+ }
+ // getInstanceType fails if the function is not a constructor
+ if (isConstructor() && prototype == getInstanceType()) {
+ return false;
+ }
+
+ boolean replacedPrototype = prototype != null;
+
+ this.prototype = prototype;
+ this.prototypeSlot = new SimpleSlot(""prototype"", prototype, true);
+ this.prototype.setOwnerFunction(this);
+
+ // Disassociating the old prototype makes this easier to debug--
+ // we don't have to worry about two prototypes running around.
+
+ if (isConstructor() || isInterface()) {
+ FunctionType superClass = getSuperClassConstructor();
+ if (superClass != null) {
+ superClass.addSubType(this);
+ }
+
+ if (isInterface()) {
+ for (ObjectType interfaceType : getExtendedInterfaces()) {
+ if (interfaceType.getConstructor() != null) {
+ interfaceType.getConstructor().addSubType(this);
+ }
+ }
+ }
+ }
+
+ if (replacedPrototype) {
+ clearCachedValues();
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue537a() throws Exception {
+ testTypes(
+ ""/** @constructor */ function Foo() {}"" +
+ ""Foo.prototype = {method: function() {}};"" +
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" * @extends {Foo}\n"" +
+ "" */\n"" +
+ ""function Bar() {"" +
+ "" Foo.call(this);"" +
+ "" if (this.baz()) this.method(1);"" +
+ ""}"" +
+ ""Bar.prototype = {"" +
+ "" baz: function() {"" +
+ "" return true;"" +
+ "" }"" +
+ ""};"" +
+ ""Bar.prototype.__proto__ = Foo.prototype;"",
+ ""Function Foo.prototype.method: called with 1 argument(s). "" +
+ ""Function requires at least 0 argument(s) "" +
+ ""and no more than 0 argument(s)."");
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info,
+ Node n, Node parent, Node rhsValue) {
+ Node ownerNode = n.getFirstChild();
+ String ownerName = ownerNode.getQualifiedName();
+ String qName = n.getQualifiedName();
+ String propName = n.getLastChild().getString();
+ Preconditions.checkArgument(qName != null && ownerName != null);
+
+ // Precedence of type information on GETPROPs:
+ // 1) @type annnotation / @enum annotation
+ // 2) ASSIGN to FUNCTION literal
+ // 3) @param/@return annotation (with no function literal)
+ // 4) ASSIGN to something marked @const
+ // 5) ASSIGN to anything else
+ //
+ // 1, 3, and 4 are declarations, 5 is inferred, and 2 is a declaration iff
+ // the function has jsdoc or has not been declared before.
+ //
+ // FUNCTION literals are special because TypedScopeCreator is very smart
+ // about getting as much type information as possible for them.
+
+ // Determining type for #1 + #2 + #3 + #4
+ JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue);
+ if (valueType == null && rhsValue != null) {
+ // Determining type for #5
+ valueType = rhsValue.getJSType();
+ }
+ // Function prototypes are special.
+ // It's a common JS idiom to do:
+ // F.prototype = { ... };
+ // So if F does not have an explicitly declared super type,
+ // allow F.prototype to be redefined arbitrarily.
+ if (""prototype"".equals(propName)) {
+ Var qVar = scope.getVar(qName);
+ if (qVar != null) {
+ // If the programmer has declared that F inherits from Super,
+ // and they assign F.prototype to an object literal,
+ // then they are responsible for making sure that the object literal's
+ // implicit prototype is set up appropriately. We just obey
+ // the @extends tag.
+ if (!qVar.isTypeInferred()) {
+ // If the programmer has declared that F inherits from Super,
+ // and they assign F.prototype to some arbitrary expression,
+ // there's not much we can do. We just ignore the expression,
+ // and hope they've annotated their code in a way to tell us
+ // what props are going to be on that prototype.
+ return;
+ }
+ if (qVar.getScope() == scope) {
+ scope.undeclare(qVar);
+ }
+ }
+ }
+
+ if (valueType == null) {
+ if (parent.getType() == Token.EXPR_RESULT) {
+ stubDeclarations.add(new StubDeclaration(
+ n,
+ t.getInput() != null && t.getInput().isExtern(),
+ ownerName));
+ }
+
+ return;
+ }
+
+ boolean inferred = true;
+ if (info != null) {
+ // Determining declaration for #1 + #3 + #4
+ inferred = !(info.hasType()
+ || info.hasEnumParameterType()
+ || (info.isConstant() && valueType != null
+ && !valueType.isUnknownType())
+ || FunctionTypeBuilder.isFunctionTypeDeclaration(info));
+ }
+
+ if (inferred) {
+ // Determining declaration for #2
+ inferred = !(rhsValue != null &&
+ rhsValue.getType() == Token.FUNCTION &&
+ (info != null || !scope.isDeclared(qName, false)));
+ }
+
+ if (!inferred) {
+ ObjectType ownerType = getObjectSlot(ownerName);
+ if (ownerType != null) {
+ // Only declare this as an official property if it has not been
+ // declared yet.
+ boolean isExtern = t.getInput() != null && t.getInput().isExtern();
+ if ((!ownerType.hasOwnProperty(propName) ||
+ ownerType.isPropertyTypeInferred(propName)) &&
+ ((isExtern && !ownerType.isNativeObjectType()) ||
+ !ownerType.isInstanceType())) {
+ // If the property is undeclared or inferred, declare it now.
+ ownerType.defineDeclaredProperty(propName, valueType, n);
+ }
+ }
+
+ // If the property is already declared, the error will be
+ // caught when we try to declare it in the current scope.
+ defineSlot(n, parent, valueType, inferred);
+ } else if (rhsValue != null &&
+ rhsValue.getType() == Token.TRUE) {
+ // We declare these for delegate proxy method properties.
+ FunctionType ownerType =
+ JSType.toMaybeFunctionType(getObjectSlot(ownerName));
+ if (ownerType != null) {
+ JSType ownerTypeOfThis = ownerType.getTypeOfThis();
+ String delegateName = codingConvention.getDelegateSuperclassName();
+ JSType delegateType = delegateName == null ?
+ null : typeRegistry.getType(delegateName);
+ if (delegateType != null &&
+ ownerTypeOfThis.isSubtype(delegateType)) {
+ defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true);
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue537a() throws Exception {
+ testTypes(
+ ""/** @constructor */ function Foo() {}"" +
+ ""Foo.prototype = {method: function() {}};"" +
+ ""/**\n"" +
+ "" * @constructor\n"" +
+ "" * @extends {Foo}\n"" +
+ "" */\n"" +
+ ""function Bar() {"" +
+ "" Foo.call(this);"" +
+ "" if (this.baz()) this.method(1);"" +
+ ""}"" +
+ ""Bar.prototype = {"" +
+ "" baz: function() {"" +
+ "" return true;"" +
+ "" }"" +
+ ""};"" +
+ ""Bar.prototype.__proto__ = Foo.prototype;"",
+ ""Function Foo.prototype.method: called with 1 argument(s). "" +
+ ""Function requires at least 0 argument(s) "" +
+ ""and no more than 0 argument(s)."");
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static boolean isReduceableFunctionExpression(Node n) {
+ return NodeUtil.isFunctionExpression(n);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue538() {
+ checkCompilesToSame( ""/** @constructor */\n"" +
+ ""WebInspector.Setting = function() {}\n"" +
+ ""WebInspector.Setting.prototype = {\n"" +
+ "" get name0(){return this._name;},\n"" +
+ "" get name1(){return this._name;},\n"" +
+ "" get name2(){return this._name;},\n"" +
+ "" get name3(){return this._name;},\n"" +
+ "" get name4(){return this._name;},\n"" +
+ "" get name5(){return this._name;},\n"" +
+ "" get name6(){return this._name;},\n"" +
+ "" get name7(){return this._name;},\n"" +
+ "" get name8(){return this._name;},\n"" +
+ "" get name9(){return this._name;},\n"" +
+ ""}"", 1);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String getLine(int lineNumber) {
+ String js = """";
+ try {
+ // NOTE(nicksantos): Right now, this is optimized for few warnings.
+ // This is probably the right trade-off, but will be slow if there
+ // are lots of warnings in one file.
+ js = getCode();
+ } catch (IOException e) {
+ return null;
+ }
+
+ int pos = 0;
+ int startLine = 1;
+
+ // If we've saved a previous offset and it's for a line less than the
+ // one we're searching for, then start at that point.
+ if (lineNumber >= lastLine) {
+ pos = lastOffset;
+ startLine = lastLine;
+ }
+
+ for (int n = startLine; n < lineNumber; n++) {
+ int nextpos = js.indexOf('\n', pos);
+ if (nextpos == -1) {
+ return null;
+ }
+ pos = nextpos + 1;
+ }
+
+ // Remember this offset for the next search we do.
+ lastOffset = pos;
+ lastLine = lineNumber;
+
+ if (js.indexOf('\n', pos) == -1) {
+ // If next new line cannot be found, there are two cases
+ // 1. pos already reaches the end of file, then null should be returned
+ // 2. otherwise, return the contents between pos and the end of file.
+ return null;
+ } else {
+ return js.substring(pos, js.indexOf('\n', pos));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testExceptNoNewLine() throws Exception {
+ assertEquals(""foo2:first line"", provider.getSourceLine(""foo2"", 1));
+ assertEquals(""foo2:second line"", provider.getSourceLine(""foo2"", 2));
+ assertEquals(""foo2:third line"", provider.getSourceLine(""foo2"", 3));
+ assertEquals(null, provider.getSourceLine(""foo2"", 4));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static String extractClassNameIfGoog(Node node, Node parent,
+ String functionName){
+ String className = null;
+ if (NodeUtil.isExprCall(parent)) {
+ Node callee = node.getFirstChild();
+ if (callee != null && callee.getType() == Token.GETPROP) {
+ String qualifiedName = callee.getQualifiedName();
+ if (functionName.equals(qualifiedName)) {
+ Node target = callee.getNext();
+ if (target != null) {
+ className = target.getString();
+ }
+ }
+ }
+ }
+ return className;
+ }
+
+// Test Case
+[/INST]
+ public void testRequire() {
+ assertRequire(""goog.require('foo')"");
+ assertNotRequire(""goog.require(foo)"");
+ assertNotRequire(""goog.require()"");
+ assertNotRequire(""foo()"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void computeGenKill(Node n, BitSet gen, BitSet kill,
+ boolean conditional) {
+
+ switch (n.getType()) {
+ case Token.SCRIPT:
+ case Token.BLOCK:
+ case Token.FUNCTION:
+ return;
+
+ case Token.WHILE:
+ case Token.DO:
+ case Token.IF:
+ computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,
+ conditional);
+ return;
+
+ case Token.FOR:
+ if (!NodeUtil.isForIn(n)) {
+ computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,
+ conditional);
+ } else {
+ // for(x in y) {...}
+ Node lhs = n.getFirstChild();
+ Node rhs = lhs.getNext();
+ if (NodeUtil.isVar(lhs)) {
+ // for(var x in y) {...}
+ lhs = lhs.getLastChild();
+ }
+ addToSetIfLocal(lhs, kill);
+ addToSetIfLocal(lhs, gen);
+ computeGenKill(rhs, gen, kill, conditional);
+ }
+ return;
+
+ case Token.VAR:
+ for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
+ if (c.hasChildren()) {
+ computeGenKill(c.getFirstChild(), gen, kill, conditional);
+ if (!conditional) {
+ addToSetIfLocal(c, kill);
+ }
+ }
+ }
+ return;
+
+ case Token.AND:
+ case Token.OR:
+ computeGenKill(n.getFirstChild(), gen, kill, conditional);
+ // May short circuit.
+ computeGenKill(n.getLastChild(), gen, kill, true);
+ return;
+
+ case Token.HOOK:
+ computeGenKill(n.getFirstChild(), gen, kill, conditional);
+ // Assume both sides are conditional.
+ computeGenKill(n.getFirstChild().getNext(), gen, kill, true);
+ computeGenKill(n.getLastChild(), gen, kill, true);
+ return;
+
+ case Token.NAME:
+ if (isArgumentsName(n)) {
+ markAllParametersEscaped();
+ } else {
+ addToSetIfLocal(n, gen);
+ }
+ return;
+
+ default:
+ if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) {
+ Node lhs = n.getFirstChild();
+ if (!conditional) {
+ addToSetIfLocal(lhs, kill);
+ }
+ if (!NodeUtil.isAssign(n)) {
+ // assignments such as a += 1 reads a.
+ addToSetIfLocal(lhs, gen);
+ }
+ computeGenKill(lhs.getNext(), gen, kill, conditional);
+ } else {
+ for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
+ computeGenKill(c, gen, kill, conditional);
+ }
+ }
+ return;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testExpressionInForIn() {
+ assertLiveBeforeX(""var a = [0]; X:for (a[1] in foo) { }"", ""a"");
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void initOptions(CompilerOptions options) {
+ this.options = options;
+ if (errorManager == null) {
+ if (outStream == null) {
+ setErrorManager(
+ new LoggerErrorManager(createMessageFormatter(), logger));
+ } else {
+ PrintStreamErrorManager printer =
+ new PrintStreamErrorManager(createMessageFormatter(), outStream);
+ printer.setSummaryDetailLevel(options.summaryDetailLevel);
+ setErrorManager(printer);
+ }
+ }
+
+ // DiagnosticGroups override the plain checkTypes option.
+ if (options.enables(DiagnosticGroups.CHECK_TYPES)) {
+ options.checkTypes = true;
+ } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {
+ options.checkTypes = false;
+ } else if (!options.checkTypes) {
+ // If DiagnosticGroups did not override the plain checkTypes
+ // option, and checkTypes is enabled, then turn off the
+ // parser type warnings.
+ options.setWarningLevel(
+ DiagnosticGroup.forType(
+ RhinoErrorReporter.TYPE_PARSE_ERROR),
+ CheckLevel.OFF);
+ }
+
+ if (options.checkGlobalThisLevel.isOn()) {
+ options.setWarningLevel(
+ DiagnosticGroups.GLOBAL_THIS,
+ options.checkGlobalThisLevel);
+ }
+
+ if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) {
+ options.setWarningLevel(
+ DiagnosticGroups.ES5_STRICT,
+ CheckLevel.ERROR);
+ }
+
+ // Initialize the warnings guard.
+ List guards = Lists.newArrayList();
+ guards.add(
+ new SuppressDocWarningsGuard(
+ getDiagnosticGroups().getRegisteredGroups()));
+ guards.add(options.getWarningsGuard());
+
+ ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards);
+
+ // All passes must run the variable check. This synthesizes
+ // variables later so that the compiler doesn't crash. It also
+ // checks the externs file for validity. If you don't want to warn
+ // about missing variable declarations, we shut that specific
+ // error off.
+ if (!options.checkSymbols &&
+ !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) {
+ composedGuards.addGuard(new DiagnosticGroupWarningsGuard(
+ DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));
+ }
+
+ this.warningsGuard = composedGuards;
+ }
+
+// Test Case
+[/INST]
+ public void testCheckGlobalThisOffByDefault() {
+ testSame(""function f() { this.a = 3; }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean expectCanAssignToPropertyOf(NodeTraversal t, Node n, JSType rightType,
+ JSType leftType, Node owner, String propName) {
+ // The NoType check is a hack to make typedefs work OK.
+ if (!leftType.isNoType() && !rightType.canAssignTo(leftType)) {
+ if ((leftType.isConstructor() || leftType.isEnumType()) && (rightType.isConstructor() || rightType.isEnumType())) {
+ registerMismatch(rightType, leftType, null);
+ } else {
+ // Do not type-check interface methods, because we expect that
+ // they will have dummy implementations that do not match the type
+ // annotations.
+ JSType ownerType = getJSType(owner);
+ if (ownerType.isFunctionPrototypeType()) {
+ FunctionType ownerFn = ownerType.toObjectType().getOwnerFunction();
+ if (ownerFn.isInterface() &&
+ rightType.isFunctionType() && leftType.isFunctionType()) {
+ return true;
+ }
+ }
+
+ mismatch(t, n,
+ ""assignment to property "" + propName + "" of "" +
+ getReadableJSTypeName(owner, true),
+ rightType, leftType);
+ }
+ return false;
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeRedefinition() throws Exception {
+ testClosureTypesMultipleWarnings(
+ ""a={};/**@enum {string}*/ a.A = {ZOR:'b'};""
+ + ""/** @constructor */ a.A = function() {}"",
+ Lists.newArrayList(
+ ""variable a.A redefined with type function (new:a.A): undefined, "" +
+ ""original definition at [testcode]:1 with type enum{a.A}"",
+ ""assignment to property A of a\n"" +
+ ""found : function (new:a.A): undefined\n"" +
+ ""required: enum{a.A}""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean expectCanAssignTo(NodeTraversal t, Node n, JSType rightType,
+ JSType leftType, String msg) {
+ if (!rightType.canAssignTo(leftType)) {
+ if ((leftType.isConstructor() || leftType.isEnumType()) && (rightType.isConstructor() || rightType.isEnumType())) {
+ registerMismatch(rightType, leftType, null);
+ } else {
+ mismatch(t, n, msg, rightType, leftType);
+ }
+ return false;
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeRedefinition() throws Exception {
+ testClosureTypesMultipleWarnings(
+ ""a={};/**@enum {string}*/ a.A = {ZOR:'b'};""
+ + ""/** @constructor */ a.A = function() {}"",
+ Lists.newArrayList(
+ ""variable a.A redefined with type function (new:a.A): undefined, "" +
+ ""original definition at [testcode]:1 with type enum{a.A}"",
+ ""assignment to property A of a\n"" +
+ ""found : function (new:a.A): undefined\n"" +
+ ""required: enum{a.A}""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static TernaryValue getImpureBooleanValue(Node n) {
+ switch (n.getType()) {
+ case Token.ASSIGN:
+ case Token.COMMA:
+ // For ASSIGN and COMMA the value is the value of the RHS.
+ return getImpureBooleanValue(n.getLastChild());
+ case Token.NOT:
+ TernaryValue value = getImpureBooleanValue(n.getLastChild());
+ return value.not();
+ case Token.AND: {
+ TernaryValue lhs = getImpureBooleanValue(n.getFirstChild());
+ TernaryValue rhs = getImpureBooleanValue(n.getLastChild());
+ return lhs.and(rhs);
+ }
+ case Token.OR: {
+ TernaryValue lhs = getImpureBooleanValue(n.getFirstChild());
+ TernaryValue rhs = getImpureBooleanValue(n.getLastChild());
+ return lhs.or(rhs);
+ }
+ case Token.HOOK: {
+ TernaryValue trueValue = getImpureBooleanValue(
+ n.getFirstChild().getNext());
+ TernaryValue falseValue = getImpureBooleanValue(n.getLastChild());
+ if (trueValue.equals(falseValue)) {
+ return trueValue;
+ } else {
+ return TernaryValue.UNKNOWN;
+ }
+ }
+ case Token.ARRAYLIT:
+ case Token.OBJECTLIT:
+ // ignoring side-effects
+ return TernaryValue.TRUE;
+
+
+ default:
+ return getPureBooleanValue(n);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue504() {
+ args.add(""--compilation_level=ADVANCED_OPTIMIZATIONS"");
+ test(""void function() { alert('hi'); }();"",
+ ""alert('hi');"", CheckSideEffects.USELESS_CODE_ERROR);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static TernaryValue getPureBooleanValue(Node n) {
+ switch (n.getType()) {
+ case Token.STRING:
+ return TernaryValue.forBoolean(n.getString().length() > 0);
+
+ case Token.NUMBER:
+ return TernaryValue.forBoolean(n.getDouble() != 0);
+
+ case Token.NOT:
+ return getPureBooleanValue(n.getLastChild()).not();
+
+ case Token.NULL:
+ case Token.FALSE:
+ return TernaryValue.FALSE;
+
+ case Token.VOID:
+ return TernaryValue.FALSE;
+
+ case Token.NAME:
+ String name = n.getString();
+ if (""undefined"".equals(name)
+ || ""NaN"".equals(name)) {
+ // We assume here that programs don't change the value of the keyword
+ // undefined to something other than the value undefined.
+ return TernaryValue.FALSE;
+ } else if (""Infinity"".equals(name)) {
+ return TernaryValue.TRUE;
+ }
+ break;
+
+ case Token.TRUE:
+ case Token.REGEXP:
+ return TernaryValue.TRUE;
+
+ case Token.ARRAYLIT:
+ case Token.OBJECTLIT:
+ if (!mayHaveSideEffects(n)) {
+ return TernaryValue.TRUE;
+ }
+ break;
+ }
+
+ return TernaryValue.UNKNOWN;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue504() {
+ args.add(""--compilation_level=ADVANCED_OPTIMIZATIONS"");
+ test(""void function() { alert('hi'); }();"",
+ ""alert('hi');"", CheckSideEffects.USELESS_CODE_ERROR);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean functionCallHasSideEffects(
+ Node callNode, @Nullable AbstractCompiler compiler) {
+ if (callNode.getType() != Token.CALL) {
+ throw new IllegalStateException(
+ ""Expected CALL node, got "" + Token.name(callNode.getType()));
+ }
+
+ if (callNode.isNoSideEffectsCall()) {
+ return false;
+ }
+
+ Node nameNode = callNode.getFirstChild();
+
+ // Built-in functions with no side effects.
+ if (nameNode.getType() == Token.NAME) {
+ String name = nameNode.getString();
+ if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) {
+ return false;
+ }
+ } else if (nameNode.getType() == Token.GETPROP) {
+ if (callNode.hasOneChild()
+ && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains(
+ nameNode.getLastChild().getString())) {
+ return false;
+ }
+
+ if (callNode.isOnlyModifiesThisCall()
+ && evaluatesToLocalValue(nameNode.getFirstChild())) {
+ return false;
+ }
+
+ // Functions in the ""Math"" namespace have no side effects.
+
+ if (compiler != null && !compiler.hasRegExpGlobalReferences()) {
+ if (nameNode.getFirstChild().getType() == Token.REGEXP
+ && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) {
+ return false;
+ } else if (nameNode.getFirstChild().getType() == Token.STRING
+ && STRING_REGEXP_METHODS.contains(
+ nameNode.getLastChild().getString())) {
+ Node param = nameNode.getNext();
+ if (param != null &&
+ (param.getType() == Token.STRING
+ || param.getType() == Token.REGEXP))
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testCall1() {
+ test(""Math.sin(0);"", """");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private String format(JSError error, boolean warning) {
+ // extract source excerpt
+ SourceExcerptProvider source = getSource();
+ String sourceExcerpt = source == null ? null :
+ excerpt.get(
+ source, error.sourceName, error.lineNumber, excerptFormatter);
+
+ // formatting the message
+ StringBuilder b = new StringBuilder();
+ if (error.sourceName != null) {
+ b.append(error.sourceName);
+ if (error.lineNumber > 0) {
+ b.append(':');
+ b.append(error.lineNumber);
+ }
+ b.append("": "");
+ }
+
+ b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR));
+ b.append("" - "");
+
+ b.append(error.description);
+ b.append('\n');
+ if (sourceExcerpt != null) {
+ b.append(sourceExcerpt);
+ b.append('\n');
+ int charno = error.getCharno();
+
+ // padding equal to the excerpt and arrow at the end
+ // charno == sourceExpert.length() means something is missing
+ // at the end of the line
+ if (excerpt.equals(LINE)
+ && 0 <= charno && charno < sourceExcerpt.length()) {
+ for (int i = 0; i < charno; i++) {
+ char c = sourceExcerpt.charAt(i);
+ if (Character.isWhitespace(c)) {
+ b.append(c);
+ } else {
+ b.append(' ');
+ }
+ }
+ b.append(""^\n"");
+ }
+ }
+ return b.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testFormatErrorSpaceEndOfLine1() throws Exception {
+ JSError error = JSError.make(""javascript/complex.js"",
+ 1, 10, FOO_TYPE);
+ LightweightMessageFormatter formatter = formatter(""assert (1;"");
+ assertEquals(""javascript/complex.js:1: ERROR - error description here\n"" +
+ ""assert (1;\n"" +
+ "" ^\n"", formatter.formatError(error));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void toSource(final CodeBuilder cb,
+ final int inputSeqNum,
+ final Node root) {
+ runInCompilerThread(new Callable() {
+ public Void call() throws Exception {
+ if (options.printInputDelimiter) {
+ if ((cb.getLength() > 0) && !cb.endsWith(""\n"")) {
+ cb.append(""\n""); // Make sure that the label starts on a new line
+ }
+ Preconditions.checkState(root.getType() == Token.SCRIPT);
+
+ String delimiter = options.inputDelimiter;
+
+ String sourceName = (String)root.getProp(Node.SOURCENAME_PROP);
+ Preconditions.checkState(sourceName != null);
+ Preconditions.checkState(!sourceName.isEmpty());
+
+ delimiter = delimiter.replaceAll(""%name%"", sourceName)
+ .replaceAll(""%num%"", String.valueOf(inputSeqNum));
+
+ cb.append(delimiter)
+ .append(""\n"");
+ }
+ if (root.getJSDocInfo() != null &&
+ root.getJSDocInfo().getLicense() != null) {
+ cb.append(""/*\n"")
+ .append(root.getJSDocInfo().getLicense())
+ .append(""*/\n"");
+ }
+
+ // If there is a valid source map, then indicate to it that the current
+ // root node's mappings are offset by the given string builder buffer.
+ if (options.sourceMapOutputPath != null) {
+ sourceMap.setStartingPosition(
+ cb.getLineIndex(), cb.getColumnIndex());
+ }
+
+ // if LanguageMode is ECMASCRIPT5_STRICT, only print 'use strict'
+ // for the first input file
+ String code = toSource(root, sourceMap);
+ if (!code.isEmpty()) {
+ cb.append(code);
+
+ // In order to avoid parse ambiguity when files are concatenated
+ // together, all files should end in a semi-colon. Do a quick
+ // heuristic check if there's an obvious semi-colon already there.
+ int length = code.length();
+ char lastChar = code.charAt(length - 1);
+ char secondLastChar = length >= 2 ?
+ code.charAt(length - 2) : '\0';
+ boolean hasSemiColon = lastChar == ';' ||
+ (lastChar == '\n' && secondLastChar == ';');
+ if (!hasSemiColon) {
+ cb.append("";"");
+ }
+ }
+ return null;
+ }
+ });
+ }
+
+// Test Case
+[/INST]
+ public void testES5StrictUseStrictMultipleInputs() {
+ args.add(""--language_in=ECMASCRIPT5_STRICT"");
+ Compiler compiler = compile(new String[] {""var x = f.function"",
+ ""var y = f.function"", ""var z = f.function""});
+ String outputSource = compiler.toSource();
+ assertEquals(""'use strict'"", outputSource.substring(0, 12));
+ assertEquals(outputSource.substring(13).indexOf(""'use strict'""), -1);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ String toSource(Node n) {
+ initCompilerOptionsIfTesting();
+ return toSource(n, null);
+ }
+
+// Test Case
+[/INST]
+ public void testES5StrictUseStrictMultipleInputs() {
+ args.add(""--language_in=ECMASCRIPT5_STRICT"");
+ Compiler compiler = compile(new String[] {""var x = f.function"",
+ ""var y = f.function"", ""var z = f.function""});
+ String outputSource = compiler.toSource();
+ assertEquals(""'use strict'"", outputSource.substring(0, 12));
+ assertEquals(outputSource.substring(13).indexOf(""'use strict'""), -1);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private String toSource(Node n, SourceMap sourceMap) {
+ CodePrinter.Builder builder = new CodePrinter.Builder(n);
+ builder.setPrettyPrint(options.prettyPrint);
+ builder.setLineBreak(options.lineBreak);
+ builder.setSourceMap(sourceMap);
+ builder.setSourceMapDetailLevel(options.sourceMapDetailLevel);
+ builder.setTagAsStrict(
+ options.getLanguageOut() == LanguageMode.ECMASCRIPT5_STRICT);
+ builder.setLineLengthThreshold(options.lineLengthThreshold);
+
+ Charset charset = options.outputCharset != null ?
+ Charset.forName(options.outputCharset) : null;
+ builder.setOutputCharset(charset);
+
+ return builder.build();
+ }
+
+// Test Case
+[/INST]
+ public void testES5StrictUseStrictMultipleInputs() {
+ args.add(""--language_in=ECMASCRIPT5_STRICT"");
+ Compiler compiler = compile(new String[] {""var x = f.function"",
+ ""var y = f.function"", ""var z = f.function""});
+ String outputSource = compiler.toSource();
+ assertEquals(""'use strict'"", outputSource.substring(0, 12));
+ assertEquals(outputSource.substring(13).indexOf(""'use strict'""), -1);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static String strEscape(String s, char quote,
+ String doublequoteEscape,
+ String singlequoteEscape,
+ String backslashEscape,
+ CharsetEncoder outputCharsetEncoder) {
+ StringBuilder sb = new StringBuilder(s.length() + 2);
+ sb.append(quote);
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ switch (c) {
+ case '\0': sb.append(""\\0""); break;
+ case '\n': sb.append(""\\n""); break;
+ case '\r': sb.append(""\\r""); break;
+ case '\t': sb.append(""\\t""); break;
+ case '\\': sb.append(backslashEscape); break;
+ case '\""': sb.append(doublequoteEscape); break;
+ case '\'': sb.append(singlequoteEscape); break;
+ case '>': // Break --> into --\> or ]]> into ]]\>
+ if (i >= 2 &&
+ ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||
+ (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {
+ sb.append(""\\>"");
+ } else {
+ sb.append(c);
+ }
+ break;
+ case '<':
+ // Break 0x1f && c < 0x7f) {
+ sb.append(c);
+ } else {
+ // Other characters can be misinterpreted by some js parsers,
+ // or perhaps mangled by proxies along the way,
+ // so we play it safe and unicode escape them.
+ appendHexJavaScriptRepresentation(sb, c);
+ }
+ }
+ }
+ }
+ sb.append(quote);
+ return sb.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testZero() {
+ assertPrint(""var x ='\\0';"", ""var x=\""\\000\"""");
+ assertPrint(""var x ='\\x00';"", ""var x=\""\\000\"""");
+ assertPrint(""var x ='\\u0000';"", ""var x=\""\\000\"""");
+ assertPrint(""var x ='\\u00003';"", ""var x=\""\\0003\"""");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void visit(NodeTraversal t, Node n, Node parent) {
+ JSType childType;
+ JSType leftType, rightType;
+ Node left, right;
+ // To be explicitly set to false if the node is not typeable.
+ boolean typeable = true;
+
+ switch (n.getType()) {
+ case Token.NAME:
+ typeable = visitName(t, n, parent);
+ break;
+
+ case Token.LP:
+ // If this is under a FUNCTION node, it is a parameter list and can be
+ // ignored here.
+ if (parent.getType() != Token.FUNCTION) {
+ ensureTyped(t, n, getJSType(n.getFirstChild()));
+ } else {
+ typeable = false;
+ }
+ break;
+
+ case Token.COMMA:
+ ensureTyped(t, n, getJSType(n.getLastChild()));
+ break;
+
+ case Token.TRUE:
+ case Token.FALSE:
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+
+ case Token.THIS:
+ ensureTyped(t, n, t.getScope().getTypeOfThis());
+ break;
+
+ case Token.REF_SPECIAL:
+ ensureTyped(t, n);
+ break;
+
+ case Token.GET_REF:
+ ensureTyped(t, n, getJSType(n.getFirstChild()));
+ break;
+
+ case Token.NULL:
+ ensureTyped(t, n, NULL_TYPE);
+ break;
+
+ case Token.NUMBER:
+ ensureTyped(t, n, NUMBER_TYPE);
+ break;
+
+ case Token.STRING:
+ // Object literal keys are handled with OBJECTLIT
+ if (!NodeUtil.isObjectLitKey(n, n.getParent())) {
+ ensureTyped(t, n, STRING_TYPE);
+ // Object literal keys are not typeable
+ }
+ break;
+
+ case Token.GET:
+ case Token.SET:
+ // Object literal keys are handled with OBJECTLIT
+ break;
+
+ case Token.ARRAYLIT:
+ ensureTyped(t, n, ARRAY_TYPE);
+ break;
+
+ case Token.REGEXP:
+ ensureTyped(t, n, REGEXP_TYPE);
+ break;
+
+ case Token.GETPROP:
+ visitGetProp(t, n, parent);
+ typeable = !(parent.getType() == Token.ASSIGN &&
+ parent.getFirstChild() == n);
+ break;
+
+ case Token.GETELEM:
+ visitGetElem(t, n);
+ // The type of GETELEM is always unknown, so no point counting that.
+ // If that unknown leaks elsewhere (say by an assignment to another
+ // variable), then it will be counted.
+ typeable = false;
+ break;
+
+ case Token.VAR:
+ visitVar(t, n);
+ typeable = false;
+ break;
+
+ case Token.NEW:
+ visitNew(t, n);
+ typeable = true;
+ break;
+
+ case Token.CALL:
+ visitCall(t, n);
+ typeable = !NodeUtil.isExpressionNode(parent);
+ break;
+
+ case Token.RETURN:
+ visitReturn(t, n);
+ typeable = false;
+ break;
+
+ case Token.DEC:
+ case Token.INC:
+ left = n.getFirstChild();
+ validator.expectNumber(
+ t, left, getJSType(left), ""increment/decrement"");
+ ensureTyped(t, n, NUMBER_TYPE);
+ break;
+
+ case Token.NOT:
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+
+ case Token.VOID:
+ ensureTyped(t, n, VOID_TYPE);
+ break;
+
+ case Token.TYPEOF:
+ ensureTyped(t, n, STRING_TYPE);
+ break;
+
+ case Token.BITNOT:
+ childType = getJSType(n.getFirstChild());
+ if (!childType.matchesInt32Context()) {
+ report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()),
+ childType.toString());
+ }
+ ensureTyped(t, n, NUMBER_TYPE);
+ break;
+
+ case Token.POS:
+ case Token.NEG:
+ left = n.getFirstChild();
+ validator.expectNumber(t, left, getJSType(left), ""sign operator"");
+ ensureTyped(t, n, NUMBER_TYPE);
+ break;
+
+ case Token.EQ:
+ case Token.NE: {
+ leftType = getJSType(n.getFirstChild());
+ rightType = getJSType(n.getLastChild());
+
+ JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();
+ JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();
+ TernaryValue result =
+ leftTypeRestricted.testForEquality(rightTypeRestricted);
+ if (result != TernaryValue.UNKNOWN) {
+ if (n.getType() == Token.NE) {
+ result = result.not();
+ }
+ report(t, n, DETERMINISTIC_TEST, leftType.toString(),
+ rightType.toString(), result.toString());
+ }
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+ }
+
+ case Token.SHEQ:
+ case Token.SHNE: {
+ leftType = getJSType(n.getFirstChild());
+ rightType = getJSType(n.getLastChild());
+
+ JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();
+ JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();
+ if (!leftTypeRestricted.canTestForShallowEqualityWith(
+ rightTypeRestricted)) {
+ report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(),
+ rightType.toString());
+ }
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+ }
+
+ case Token.LT:
+ case Token.LE:
+ case Token.GT:
+ case Token.GE:
+ leftType = getJSType(n.getFirstChild());
+ rightType = getJSType(n.getLastChild());
+ if (rightType.isNumber()) {
+ validator.expectNumber(
+ t, n, leftType, ""left side of numeric comparison"");
+ } else if (leftType.isNumber()) {
+ validator.expectNumber(
+ t, n, rightType, ""right side of numeric comparison"");
+ } else if (leftType.matchesNumberContext() &&
+ rightType.matchesNumberContext()) {
+ // OK.
+ } else {
+ // Whether the comparison is numeric will be determined at runtime
+ // each time the expression is evaluated. Regardless, both operands
+ // should match a string context.
+ String message = ""left side of comparison"";
+ validator.expectString(t, n, leftType, message);
+ validator.expectNotNullOrUndefined(
+ t, n, leftType, message, getNativeType(STRING_TYPE));
+ message = ""right side of comparison"";
+ validator.expectString(t, n, rightType, message);
+ validator.expectNotNullOrUndefined(
+ t, n, rightType, message, getNativeType(STRING_TYPE));
+ }
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+
+ case Token.IN:
+ left = n.getFirstChild();
+ right = n.getLastChild();
+ leftType = getJSType(left);
+ rightType = getJSType(right);
+ validator.expectObject(t, n, rightType, ""'in' requires an object"");
+ validator.expectString(t, left, leftType, ""left side of 'in'"");
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+
+ case Token.INSTANCEOF:
+ left = n.getFirstChild();
+ right = n.getLastChild();
+ leftType = getJSType(left);
+ rightType = getJSType(right).restrictByNotNullOrUndefined();
+
+ validator.expectAnyObject(
+ t, left, leftType, ""deterministic instanceof yields false"");
+ validator.expectActualObject(
+ t, right, rightType, ""instanceof requires an object"");
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+
+ case Token.ASSIGN:
+ visitAssign(t, n);
+ typeable = false;
+ break;
+
+ case Token.ASSIGN_LSH:
+ case Token.ASSIGN_RSH:
+ case Token.ASSIGN_URSH:
+ case Token.ASSIGN_DIV:
+ case Token.ASSIGN_MOD:
+ case Token.ASSIGN_BITOR:
+ case Token.ASSIGN_BITXOR:
+ case Token.ASSIGN_BITAND:
+ case Token.ASSIGN_SUB:
+ case Token.ASSIGN_ADD:
+ case Token.ASSIGN_MUL:
+ case Token.LSH:
+ case Token.RSH:
+ case Token.URSH:
+ case Token.DIV:
+ case Token.MOD:
+ case Token.BITOR:
+ case Token.BITXOR:
+ case Token.BITAND:
+ case Token.SUB:
+ case Token.ADD:
+ case Token.MUL:
+ visitBinaryOperator(n.getType(), t, n);
+ break;
+
+ case Token.DELPROP:
+ if (!isReference(n.getFirstChild())) {
+ report(t, n, BAD_DELETE);
+ }
+ ensureTyped(t, n, BOOLEAN_TYPE);
+ break;
+
+ case Token.CASE:
+ JSType switchType = getJSType(parent.getFirstChild());
+ JSType caseType = getJSType(n.getFirstChild());
+ validator.expectSwitchMatchesCase(t, n, switchType, caseType);
+ typeable = false;
+ break;
+
+ case Token.WITH: {
+ Node child = n.getFirstChild();
+ childType = getJSType(child);
+ validator.expectObject(
+ t, child, childType, ""with requires an object"");
+ typeable = false;
+ break;
+ }
+
+ case Token.FUNCTION:
+ visitFunction(t, n);
+ break;
+
+ // These nodes have no interesting type behavior.
+ case Token.LABEL:
+ case Token.LABEL_NAME:
+ case Token.SWITCH:
+ case Token.BREAK:
+ case Token.CATCH:
+ case Token.TRY:
+ case Token.SCRIPT:
+ case Token.EXPR_RESULT:
+ case Token.BLOCK:
+ case Token.EMPTY:
+ case Token.DEFAULT:
+ case Token.CONTINUE:
+ case Token.DEBUGGER:
+ case Token.THROW:
+ typeable = false;
+ break;
+
+ // These nodes require data flow analysis.
+ case Token.DO:
+ case Token.FOR:
+ case Token.IF:
+ case Token.WHILE:
+ typeable = false;
+ break;
+
+ // These nodes are typed during the type inference.
+ case Token.AND:
+ case Token.HOOK:
+ case Token.OBJECTLIT:
+ case Token.OR:
+ if (n.getJSType() != null) { // If we didn't run type inference.
+ ensureTyped(t, n);
+ } else {
+ // If this is an enum, then give that type to the objectlit as well.
+ if ((n.getType() == Token.OBJECTLIT)
+ && (parent.getJSType() instanceof EnumType)) {
+ ensureTyped(t, n, parent.getJSType());
+ } else {
+ ensureTyped(t, n);
+ }
+ }
+ if (n.getType() == Token.OBJECTLIT) {
+ for (Node key : n.children()) {
+ visitObjLitKey(t, key, n);
+ }
+ }
+ break;
+
+ default:
+ report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType()));
+ ensureTyped(t, n);
+ break;
+ }
+
+ // Don't count externs since the user's code may not even use that part.
+ typeable = typeable && !inExterns;
+
+ if (typeable) {
+ doPercentTypedAccounting(t, n);
+ }
+
+ checkNoTypeCheckSection(n, false);
+ }
+
+// Test Case
+[/INST]
+ public void testGetTypedPercent5() throws Exception {
+ String js = ""/** @enum {number} */ keys = {A: 1,B: 2,C: 3};"";
+ assertEquals(100.0, getTypedPercent(js), 0.1);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isPrototypePropertyAssign(Node assign) {
+ Node n = assign.getFirstChild();
+ if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)
+ && n.getType() == Token.GETPROP
+ ) {
+ // We want to exclude the assignment itself from the usage list
+ boolean isChainedProperty =
+ n.getFirstChild().getType() == Token.GETPROP;
+
+ if (isChainedProperty) {
+ Node child = n.getFirstChild().getFirstChild().getNext();
+
+ if (child.getType() == Token.STRING &&
+ child.getString().equals(""prototype"")) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testAliasing7() {
+ // An exported alias must preserved any referenced values in the
+ // referenced function.
+ testSame(""function e(){}"" +
+ ""e.prototype['alias1'] = e.prototype.method1 = "" +
+ ""function(){this.method2()};"" +
+ ""e.prototype.method2 = function(){};"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean parse() {
+ int lineno;
+ int charno;
+
+ // JSTypes are represented as Rhino AST nodes, and then resolved later.
+ JSTypeExpression type;
+
+ state = State.SEARCHING_ANNOTATION;
+ skipEOLs();
+
+ JsDocToken token = next();
+
+ List extendedTypes = Lists.newArrayList();
+
+ // Always record that we have a comment.
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo blockInfo = extractBlockComment(token);
+ token = blockInfo.token;
+ if (!blockInfo.string.isEmpty()) {
+ jsdocBuilder.recordBlockDescription(blockInfo.string);
+ }
+ } else {
+ if (token != JsDocToken.ANNOTATION &&
+ token != JsDocToken.EOC) {
+ // Mark that there was a description, but don't bother marking
+ // what it was.
+ jsdocBuilder.recordBlockDescription("""");
+ }
+ }
+
+ // Parse the actual JsDoc.
+ retry: for (;;) {
+ switch (token) {
+ case ANNOTATION:
+ if (state == State.SEARCHING_ANNOTATION) {
+ state = State.SEARCHING_NEWLINE;
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+
+ String annotationName = stream.getString();
+ Annotation annotation = annotationNames.get(annotationName);
+ if (annotation == null) {
+ parser.addParserWarning(""msg.bad.jsdoc.tag"", annotationName,
+ stream.getLineno(), stream.getCharno());
+ } else {
+ // Mark the beginning of the annotation.
+ jsdocBuilder.markAnnotation(annotationName, lineno, charno);
+
+ switch (annotation) {
+ case AUTHOR:
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo authorInfo = extractSingleLineBlock();
+ String author = authorInfo.string;
+
+ if (author.length() == 0) {
+ parser.addParserWarning(""msg.jsdoc.authormissing"",
+ stream.getLineno(), stream.getCharno());
+ } else {
+ jsdocBuilder.addAuthor(author);
+ }
+ token = authorInfo.token;
+ } else {
+ token = eatTokensUntilEOL(token);
+ }
+ continue retry;
+
+ case CONSTANT:
+ if (!jsdocBuilder.recordConstancy()) {
+ parser.addParserWarning(""msg.jsdoc.const"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case CONSTRUCTOR:
+ if (!jsdocBuilder.recordConstructor()) {
+ if (jsdocBuilder.isInterfaceRecorded()) {
+ parser.addTypeWarning(""msg.jsdoc.interface.constructor"",
+ stream.getLineno(), stream.getCharno());
+ } else {
+ parser.addTypeWarning(""msg.jsdoc.incompat.type"",
+ stream.getLineno(), stream.getCharno());
+ }
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case DEPRECATED:
+ if (!jsdocBuilder.recordDeprecated()) {
+ parser.addParserWarning(""msg.jsdoc.deprecated"",
+ stream.getLineno(), stream.getCharno());
+ }
+
+ // Find the reason/description, if any.
+ ExtractionInfo reasonInfo =
+ extractMultilineTextualBlock(token);
+
+ String reason = reasonInfo.string;
+
+ if (reason.length() > 0) {
+ jsdocBuilder.recordDeprecationReason(reason);
+ }
+
+ token = reasonInfo.token;
+ continue retry;
+
+ case INTERFACE:
+ if (!jsdocBuilder.recordInterface()) {
+ if (jsdocBuilder.isConstructorRecorded()) {
+ parser.addTypeWarning(""msg.jsdoc.interface.constructor"",
+ stream.getLineno(), stream.getCharno());
+ } else {
+ parser.addTypeWarning(""msg.jsdoc.incompat.type"",
+ stream.getLineno(), stream.getCharno());
+ }
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case DESC:
+ if (jsdocBuilder.isDescriptionRecorded()) {
+ parser.addParserWarning(""msg.jsdoc.desc.extra"",
+ stream.getLineno(), stream.getCharno());
+ token = eatTokensUntilEOL();
+ continue retry;
+ } else {
+ ExtractionInfo descriptionInfo =
+ extractMultilineTextualBlock(token);
+
+ String description = descriptionInfo.string;
+
+ jsdocBuilder.recordDescription(description);
+ token = descriptionInfo.token;
+ continue retry;
+ }
+
+ case FILE_OVERVIEW:
+ String fileOverview = """";
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo fileOverviewInfo =
+ extractMultilineTextualBlock(token,
+ WhitespaceOption.TRIM);
+
+ fileOverview = fileOverviewInfo.string;
+
+ token = fileOverviewInfo.token;
+ } else {
+ token = eatTokensUntilEOL(token);
+ }
+
+ if (!jsdocBuilder.recordFileOverview(fileOverview) ||
+ fileOverviewJSDocInfo != null) {
+ parser.addParserWarning(""msg.jsdoc.fileoverview.extra"",
+ stream.getLineno(), stream.getCharno());
+ }
+ continue retry;
+
+ case LICENSE:
+ case PRESERVE:
+ ExtractionInfo preserveInfo =
+ extractMultilineTextualBlock(token,
+ WhitespaceOption.PRESERVE);
+
+ String preserve = preserveInfo.string;
+
+ if (preserve.length() > 0) {
+ if (fileLevelJsDocBuilder != null) {
+ fileLevelJsDocBuilder.append(preserve);
+ }
+ }
+
+ token = preserveInfo.token;
+ continue retry;
+
+ case ENUM:
+ token = next();
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+
+ type = null;
+ if (token != JsDocToken.EOL && token != JsDocToken.EOC) {
+ type = createJSTypeExpression(
+ parseAndRecordTypeNode(token));
+ }
+
+ if (type == null) {
+ type = createJSTypeExpression(newStringNode(""number""));
+ }
+ if (!jsdocBuilder.recordEnumParameterType(type)) {
+ parser.addTypeWarning(
+ ""msg.jsdoc.incompat.type"", lineno, charno);
+ }
+ token = eatTokensUntilEOL(token);
+ continue retry;
+
+ case EXPORT:
+ if (!jsdocBuilder.recordExport()) {
+ parser.addParserWarning(""msg.jsdoc.export"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case EXTERNS:
+ if (!jsdocBuilder.recordExterns()) {
+ parser.addParserWarning(""msg.jsdoc.externs"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case JAVA_DISPATCH:
+ if (!jsdocBuilder.recordJavaDispatch()) {
+ parser.addParserWarning(""msg.jsdoc.javadispatch"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case EXTENDS:
+ case IMPLEMENTS:
+ skipEOLs();
+ token = next();
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+ boolean matchingRc = false;
+
+ if (token == JsDocToken.LC) {
+ token = next();
+ matchingRc = true;
+ }
+
+ if (token == JsDocToken.STRING) {
+ Node typeNode = parseAndRecordTypeNameNode(
+ token, lineno, charno, matchingRc);
+
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+
+ typeNode = wrapNode(Token.BANG, typeNode);
+ if (typeNode != null && !matchingRc) {
+ typeNode.putBooleanProp(Node.BRACELESS_TYPE, true);
+ }
+ type = createJSTypeExpression(typeNode);
+
+ if (annotation == Annotation.EXTENDS) {
+ // record the extended type, check later
+ extendedTypes.add(new ExtendedTypeInfo(
+ type, stream.getLineno(), stream.getCharno()));
+ } else {
+ Preconditions.checkState(
+ annotation == Annotation.IMPLEMENTS);
+ if (!jsdocBuilder.recordImplementedInterface(type)) {
+ parser.addTypeWarning(""msg.jsdoc.implements.duplicate"",
+ lineno, charno);
+ }
+ }
+ token = next();
+ if (matchingRc) {
+ if (token != JsDocToken.RC) {
+ parser.addTypeWarning(""msg.jsdoc.missing.rc"",
+ stream.getLineno(), stream.getCharno());
+ }
+ } else if (token != JsDocToken.EOL &&
+ token != JsDocToken.EOF && token != JsDocToken.EOC) {
+ parser.addTypeWarning(""msg.end.annotation.expected"",
+ stream.getLineno(), stream.getCharno());
+ }
+ } else {
+ parser.addTypeWarning(""msg.no.type.name"", lineno, charno);
+ }
+ token = eatTokensUntilEOL(token);
+ continue retry;
+
+ case HIDDEN:
+ if (!jsdocBuilder.recordHiddenness()) {
+ parser.addParserWarning(""msg.jsdoc.hidden"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case LENDS:
+ skipEOLs();
+
+ matchingRc = false;
+ if (match(JsDocToken.LC)) {
+ token = next();
+ matchingRc = true;
+ }
+
+ if (match(JsDocToken.STRING)) {
+ token = next();
+ if (!jsdocBuilder.recordLends(stream.getString())) {
+ parser.addTypeWarning(""msg.jsdoc.lends.incompatible"",
+ stream.getLineno(), stream.getCharno());
+ }
+ } else {
+ parser.addTypeWarning(""msg.jsdoc.lends.missing"",
+ stream.getLineno(), stream.getCharno());
+ }
+
+ if (matchingRc && !match(JsDocToken.RC)) {
+ parser.addTypeWarning(""msg.jsdoc.missing.rc"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case MEANING:
+ ExtractionInfo meaningInfo =
+ extractMultilineTextualBlock(token);
+ String meaning = meaningInfo.string;
+ token = meaningInfo.token;
+ if (!jsdocBuilder.recordMeaning(meaning)) {
+ parser.addParserWarning(""msg.jsdoc.meaning.extra"",
+ stream.getLineno(), stream.getCharno());
+ }
+ continue retry;
+
+ case NO_ALIAS:
+ if (!jsdocBuilder.recordNoAlias()) {
+ parser.addParserWarning(""msg.jsdoc.noalias"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case NO_COMPILE:
+ if (!jsdocBuilder.recordNoCompile()) {
+ parser.addParserWarning(""msg.jsdoc.nocompile"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case NO_TYPE_CHECK:
+ if (!jsdocBuilder.recordNoTypeCheck()) {
+ parser.addParserWarning(""msg.jsdoc.nocheck"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case NOT_IMPLEMENTED:
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case INHERIT_DOC:
+ case OVERRIDE:
+ if (!jsdocBuilder.recordOverride()) {
+ parser.addTypeWarning(""msg.jsdoc.override"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case THROWS:
+ skipEOLs();
+ token = next();
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+ type = null;
+
+ if (token == JsDocToken.LC) {
+ type = createJSTypeExpression(
+ parseAndRecordTypeNode(token));
+
+ if (type == null) {
+ // parsing error reported during recursive descent
+ // recovering parsing
+ token = eatTokensUntilEOL();
+ continue retry;
+ }
+ }
+
+ // *Update* the token to that after the type annotation.
+ token = current();
+
+ // Save the throw type.
+ jsdocBuilder.recordThrowType(type);
+
+ // Find the throw's description (if applicable).
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo descriptionInfo =
+ extractMultilineTextualBlock(token);
+
+ String description = descriptionInfo.string;
+
+ if (description.length() > 0) {
+ jsdocBuilder.recordThrowDescription(type, description);
+ }
+
+ token = descriptionInfo.token;
+ } else {
+ token = eatTokensUntilEOL(token);
+ }
+ continue retry;
+
+ case PARAM:
+ skipEOLs();
+ token = next();
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+ type = null;
+
+ if (token == JsDocToken.LC) {
+ type = createJSTypeExpression(
+ parseAndRecordParamTypeNode(token));
+
+ if (type == null) {
+ // parsing error reported during recursive descent
+ // recovering parsing
+ token = eatTokensUntilEOL();
+ continue retry;
+ }
+ skipEOLs();
+ token = next();
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+ }
+
+ String name = null;
+ boolean isBracketedParam = JsDocToken.LB == token;
+ if (isBracketedParam) {
+ token = next();
+ }
+
+ if (JsDocToken.STRING != token) {
+ parser.addTypeWarning(""msg.missing.variable.name"",
+ lineno, charno);
+ } else {
+ name = stream.getString();
+
+ if (isBracketedParam) {
+ token = next();
+
+ // Throw out JsDocToolkit's ""default"" parameter
+ // annotation. It makes no sense under our type
+ // system.
+ if (JsDocToken.EQUALS == token) {
+ token = next();
+ if (JsDocToken.STRING == token) {
+ token = next();
+ }
+ }
+
+ if (JsDocToken.RB != token) {
+ reportTypeSyntaxWarning(""msg.jsdoc.missing.rb"");
+ } else if (type != null) {
+ // Make the type expression optional, if it isn't
+ // already.
+ type = JSTypeExpression.makeOptionalArg(type);
+ }
+ }
+
+ // If the param name has a DOT in it, just throw it out
+ // quietly. We do not handle the JsDocToolkit method
+ // for handling properties of params.
+ if (name.indexOf('.') > -1) {
+ name = null;
+ } else if (!jsdocBuilder.recordParameter(name, type)) {
+ if (jsdocBuilder.hasParameter(name)) {
+ parser.addTypeWarning(""msg.dup.variable.name"", name,
+ lineno, charno);
+ } else {
+ parser.addTypeWarning(""msg.jsdoc.incompat.type"", name,
+ lineno, charno);
+ }
+ }
+ }
+
+ if (name == null) {
+ token = eatTokensUntilEOL(token);
+ continue retry;
+ }
+
+ jsdocBuilder.markName(name, lineno, charno);
+
+ // Find the parameter's description (if applicable).
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo paramDescriptionInfo =
+ extractMultilineTextualBlock(token);
+
+ String paramDescription = paramDescriptionInfo.string;
+
+ if (paramDescription.length() > 0) {
+ jsdocBuilder.recordParameterDescription(name,
+ paramDescription);
+ }
+
+ token = paramDescriptionInfo.token;
+ } else {
+ token = eatTokensUntilEOL(token);
+ }
+ continue retry;
+
+ case PRESERVE_TRY:
+ if (!jsdocBuilder.recordPreserveTry()) {
+ parser.addParserWarning(""msg.jsdoc.preservertry"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case PRIVATE:
+ if (!jsdocBuilder.recordVisibility(Visibility.PRIVATE)) {
+ parser.addParserWarning(""msg.jsdoc.visibility.private"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case PROTECTED:
+ if (!jsdocBuilder.recordVisibility(Visibility.PROTECTED)) {
+ parser.addParserWarning(""msg.jsdoc.visibility.protected"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case PUBLIC:
+ if (!jsdocBuilder.recordVisibility(Visibility.PUBLIC)) {
+ parser.addParserWarning(""msg.jsdoc.visibility.public"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case NO_SHADOW:
+ if (!jsdocBuilder.recordNoShadow()) {
+ parser.addParserWarning(""msg.jsdoc.noshadow"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case NO_SIDE_EFFECTS:
+ if (!jsdocBuilder.recordNoSideEffects()) {
+ parser.addParserWarning(""msg.jsdoc.nosideeffects"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case MODIFIES:
+ token = parseModifiesTag(next());
+ continue retry;
+
+ case IMPLICIT_CAST:
+ if (!jsdocBuilder.recordImplicitCast()) {
+ parser.addTypeWarning(""msg.jsdoc.implicitcast"",
+ stream.getLineno(), stream.getCharno());
+ }
+ token = eatTokensUntilEOL();
+ continue retry;
+
+ case SEE:
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo referenceInfo = extractSingleLineBlock();
+ String reference = referenceInfo.string;
+
+ if (reference.length() == 0) {
+ parser.addParserWarning(""msg.jsdoc.seemissing"",
+ stream.getLineno(), stream.getCharno());
+ } else {
+ jsdocBuilder.addReference(reference);
+ }
+
+ token = referenceInfo.token;
+ } else {
+ token = eatTokensUntilEOL(token);
+ }
+ continue retry;
+
+ case SUPPRESS:
+ token = parseSuppressTag(next());
+ continue retry;
+
+ case TEMPLATE:
+ ExtractionInfo templateInfo = extractSingleLineBlock();
+ String templateTypeName = templateInfo.string;
+
+ if (templateTypeName.length() == 0) {
+ parser.addTypeWarning(""msg.jsdoc.templatemissing"",
+ stream.getLineno(), stream.getCharno());
+ } else if (!jsdocBuilder.recordTemplateTypeName(
+ templateTypeName)) {
+ parser.addTypeWarning(""msg.jsdoc.template.at.most.once"",
+ stream.getLineno(), stream.getCharno());
+ }
+
+ token = templateInfo.token;
+ continue retry;
+
+ case VERSION:
+ ExtractionInfo versionInfo = extractSingleLineBlock();
+ String version = versionInfo.string;
+
+ if (version.length() == 0) {
+ parser.addParserWarning(""msg.jsdoc.versionmissing"",
+ stream.getLineno(), stream.getCharno());
+ } else {
+ if (!jsdocBuilder.recordVersion(version)) {
+ parser.addParserWarning(""msg.jsdoc.extraversion"",
+ stream.getLineno(), stream.getCharno());
+ }
+ }
+
+ token = versionInfo.token;
+ continue retry;
+
+ case DEFINE:
+ case RETURN:
+ case THIS:
+ case TYPE:
+ case TYPEDEF:
+ lineno = stream.getLineno();
+ charno = stream.getCharno();
+
+ Node typeNode = null;
+ if (!lookAheadForTypeAnnotation() &&
+ annotation == Annotation.RETURN) {
+ // If RETURN doesn't have a type annotation, record
+ // it as the unknown type.
+ typeNode = newNode(Token.QMARK);
+ } else {
+ skipEOLs();
+ token = next();
+ typeNode = parseAndRecordTypeNode(token, lineno, charno);
+ }
+
+ if (annotation == Annotation.THIS) {
+ typeNode = wrapNode(Token.BANG, typeNode);
+ if (typeNode != null && token != JsDocToken.LC) {
+ typeNode.putBooleanProp(Node.BRACELESS_TYPE, true);
+ }
+ }
+ type = createJSTypeExpression(typeNode);
+
+ if (type == null) {
+ // error reported during recursive descent
+ // recovering parsing
+ } else {
+ switch (annotation) {
+ case DEFINE:
+ if (!jsdocBuilder.recordDefineType(type)) {
+ parser.addParserWarning(""msg.jsdoc.define"",
+ lineno, charno);
+ }
+ break;
+
+ case RETURN:
+ if (!jsdocBuilder.recordReturnType(type)) {
+ parser.addTypeWarning(
+ ""msg.jsdoc.incompat.type"", lineno, charno);
+ break;
+ }
+
+ // Find the return's description (if applicable).
+ if (jsdocBuilder.shouldParseDocumentation()) {
+ ExtractionInfo returnDescriptionInfo =
+ extractMultilineTextualBlock(token);
+
+ String returnDescription =
+ returnDescriptionInfo.string;
+
+ if (returnDescription.length() > 0) {
+ jsdocBuilder.recordReturnDescription(
+ returnDescription);
+ }
+
+ token = returnDescriptionInfo.token;
+ } else {
+ token = eatTokensUntilEOL(token);
+ }
+ continue retry;
+
+ case THIS:
+ if (!jsdocBuilder.recordThisType(type)) {
+ parser.addTypeWarning(
+ ""msg.jsdoc.incompat.type"", lineno, charno);
+ }
+ break;
+
+ case TYPE:
+ if (!jsdocBuilder.recordType(type)) {
+ parser.addTypeWarning(
+ ""msg.jsdoc.incompat.type"", lineno, charno);
+ }
+ break;
+
+ case TYPEDEF:
+ if (!jsdocBuilder.recordTypedef(type)) {
+ parser.addTypeWarning(
+ ""msg.jsdoc.incompat.type"", lineno, charno);
+ }
+ break;
+ }
+
+ token = eatTokensUntilEOL();
+ }
+ continue retry;
+ }
+ }
+ }
+ break;
+
+ case EOC:
+ if (hasParsedFileOverviewDocInfo()) {
+ fileOverviewJSDocInfo = retrieveAndResetParsedJSDocInfo();
+ }
+ checkExtendedTypes(extendedTypes);
+ return true;
+
+ case EOF:
+ // discard any accumulated information
+ jsdocBuilder.build(null);
+ parser.addParserWarning(""msg.unexpected.eof"",
+ stream.getLineno(), stream.getCharno());
+ checkExtendedTypes(extendedTypes);
+ return false;
+
+ case EOL:
+ if (state == State.SEARCHING_NEWLINE) {
+ state = State.SEARCHING_ANNOTATION;
+ }
+ token = next();
+ continue retry;
+
+ default:
+ if (token == JsDocToken.STAR && state == State.SEARCHING_ANNOTATION) {
+ token = next();
+ continue retry;
+ } else {
+ state = State.SEARCHING_NEWLINE;
+ token = eatTokensUntilEOL();
+ continue retry;
+ }
+ }
+
+ // next token
+ token = next();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue477() throws Exception {
+ parse(""@type function */"",
+ ""Bad type annotation. missing opening ("");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node parseBasicTypeExpression(JsDocToken token) {
+ if (token == JsDocToken.STAR) {
+ return newNode(Token.STAR);
+ } else if (token == JsDocToken.LB) {
+ skipEOLs();
+ return parseArrayType(next());
+ } else if (token == JsDocToken.LC) {
+ skipEOLs();
+ return parseRecordType(next());
+ } else if (token == JsDocToken.LP) {
+ skipEOLs();
+ return parseUnionType(next());
+ } else if (token == JsDocToken.STRING) {
+ String string = stream.getString();
+ if (""function"".equals(string)) {
+ skipEOLs();
+ return parseFunctionType(next());
+ } else if (""null"".equals(string) || ""undefined"".equals(string)) {
+ return newStringNode(string);
+ } else {
+ return parseTypeName(token);
+ }
+ }
+
+ return reportGenericTypeSyntaxWarning();
+ }
+
+// Test Case
+[/INST]
+ public void testIssue477() throws Exception {
+ parse(""@type function */"",
+ ""Bad type annotation. missing opening ("");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node parseFunctionType(JsDocToken token) {
+ // NOTE(nicksantos): We're not implementing generics at the moment, so
+ // just throw out TypeParameters.
+ if (token != JsDocToken.LP) {
+ return reportTypeSyntaxWarning(""msg.jsdoc.missing.lp"");
+ }
+
+ Node functionType = newNode(Token.FUNCTION);
+ Node parameters = null;
+ skipEOLs();
+ if (!match(JsDocToken.RP)) {
+ token = next();
+
+ boolean hasParams = true;
+ if (token == JsDocToken.STRING) {
+ String tokenStr = stream.getString();
+ boolean isThis = ""this"".equals(tokenStr);
+ boolean isNew = ""new"".equals(tokenStr);
+ if (isThis || isNew) {
+ if (match(JsDocToken.COLON)) {
+ next();
+ skipEOLs();
+ Node contextType = wrapNode(
+ isThis ? Token.THIS : Token.NEW,
+ parseTypeName(next()));
+ if (contextType == null) {
+ return null;
+ }
+
+ functionType.addChildToFront(contextType);
+ } else {
+ return reportTypeSyntaxWarning(""msg.jsdoc.missing.colon"");
+ }
+
+ if (match(JsDocToken.COMMA)) {
+ next();
+ skipEOLs();
+ token = next();
+ } else {
+ hasParams = false;
+ }
+ }
+ }
+
+ if (hasParams) {
+ parameters = parseParametersType(token);
+ if (parameters == null) {
+ return null;
+ }
+ }
+ }
+
+ if (parameters != null) {
+ functionType.addChildToBack(parameters);
+ }
+
+ skipEOLs();
+ if (!match(JsDocToken.RP)) {
+ return reportTypeSyntaxWarning(""msg.jsdoc.missing.rp"");
+ }
+
+ skipEOLs();
+ Node resultType = parseResultType(next());
+ if (resultType == null) {
+ return null;
+ } else {
+ functionType.addChildToBack(resultType);
+ }
+ return functionType;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue477() throws Exception {
+ parse(""@type function */"",
+ ""Bad type annotation. missing opening ("");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitCall(NodeTraversal t, Node n) {
+ Node child = n.getFirstChild();
+ JSType childType = getJSType(child).restrictByNotNullOrUndefined();
+
+ if (!childType.canBeCalled()) {
+ report(t, n, NOT_CALLABLE, childType.toString());
+ ensureTyped(t, n);
+ return;
+ }
+
+ // A couple of types can be called as if they were functions.
+ // If it is a function type, then validate parameters.
+ if (childType instanceof FunctionType) {
+ FunctionType functionType = (FunctionType) childType;
+
+ boolean isExtern = false;
+ JSDocInfo functionJSDocInfo = functionType.getJSDocInfo();
+ if(functionJSDocInfo != null) {
+ String sourceName = functionJSDocInfo.getSourceName();
+ CompilerInput functionSource = compiler.getInput(sourceName);
+ isExtern = functionSource.isExtern();
+ }
+
+ // Non-native constructors should not be called directly
+ // unless they specify a return type and are defined
+ // in an extern.
+ if (functionType.isConstructor() &&
+ !functionType.isNativeObjectType() &&
+ (functionType.getReturnType().isUnknownType() ||
+ functionType.getReturnType().isVoidType() ||
+ !isExtern)) {
+ report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString());
+ }
+
+ // Functions with explcit 'this' types must be called in a GETPROP
+ // or GETELEM.
+
+ visitParameterList(t, n, functionType);
+ ensureTyped(t, n, functionType.getReturnType());
+ } else {
+ ensureTyped(t, n);
+ }
+
+ // TODO: Add something to check for calls of RegExp objects, which is not
+ // supported by IE. Either say something about the return type or warn
+ // about the non-portability of the call or both.
+ }
+
+// Test Case
+[/INST]
+ public void testThisTypeOfFunction2() throws Exception {
+ testTypes(
+ ""/** @constructor */ function F() {}"" +
+ ""/** @type {function(this:F)} */ function f() {}"" +
+ ""f();"",
+ ""\""function (this:F): ?\"" must be called with a \""this\"" type"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JSType caseObjectType(ObjectType type) {
+ if (value.equals(""function"")) {
+ JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);
+ return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null;
+ // Objects are restricted to ""Function"", subtypes are left
+ // Only filter out subtypes of ""function""
+ }
+ return matchesExpectation(""object"") ? type : null;
+ }
+
+// Test Case
+[/INST]
+ public void testGoogIsFunction2() throws Exception {
+ testClosureFunction(""goog.isFunction"",
+ OBJECT_NUMBER_STRING_BOOLEAN,
+ U2U_CONSTRUCTOR_TYPE,
+ OBJECT_NUMBER_STRING_BOOLEAN);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void declareArguments(Node functionNode) {
+ Node astParameters = functionNode.getFirstChild().getNext();
+ Node body = astParameters.getNext();
+ FunctionType functionType = (FunctionType) functionNode.getJSType();
+ if (functionType != null) {
+ Node jsDocParameters = functionType.getParametersNode();
+ if (jsDocParameters != null) {
+ Node jsDocParameter = jsDocParameters.getFirstChild();
+ for (Node astParameter : astParameters.children()) {
+ if (jsDocParameter != null) {
+ defineSlot(astParameter, functionNode,
+ jsDocParameter.getJSType(), true);
+ jsDocParameter = jsDocParameter.getNext();
+ } else {
+ defineSlot(astParameter, functionNode, null, true);
+ }
+ }
+ }
+ }
+ } // end declareArguments
+
+// Test Case
+[/INST]
+ public void testDuplicateLocalVarDecl() throws Exception {
+ testClosureTypesMultipleWarnings(
+ ""/** @param {number} x */\n"" +
+ ""function f(x) { /** @type {string} */ var x = ''; }"",
+ Lists.newArrayList(
+ ""variable x redefined with type string, original definition"" +
+ "" at [testcode] :2 with type number"",
+ ""initializing variable\n"" +
+ ""found : string\n"" +
+ ""required: number""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void checkPropertyVisibility(NodeTraversal t,
+ Node getprop, Node parent) {
+ ObjectType objectType =
+ ObjectType.cast(dereference(getprop.getFirstChild().getJSType()));
+ String propertyName = getprop.getLastChild().getString();
+
+ if (objectType != null) {
+ // Is this a normal property access, or are we trying to override
+ // an existing property?
+ boolean isOverride = t.inGlobalScope() &&
+ parent.getType() == Token.ASSIGN &&
+ parent.getFirstChild() == getprop;
+
+ // Find the lowest property defined on a class with visibility
+ // information.
+ if (isOverride) {
+ objectType = objectType.getImplicitPrototype();
+ }
+ JSDocInfo docInfo = null;
+ for (; objectType != null;
+ objectType = objectType.getImplicitPrototype()) {
+ docInfo = objectType.getOwnPropertyJSDocInfo(propertyName);
+ if (docInfo != null &&
+ docInfo.getVisibility() != Visibility.INHERITED) {
+ break;
+ }
+ }
+
+ if (objectType == null) {
+ // We couldn't find a visibility modifier; assume it's public.
+ return;
+ }
+
+ boolean sameInput =
+ t.getInput().getName().equals(docInfo.getSourceName());
+ Visibility visibility = docInfo.getVisibility();
+ JSType ownerType = normalizeClassType(objectType);
+ if (isOverride) {
+ // Check an ASSIGN statement that's trying to override a property
+ // on a superclass.
+ JSDocInfo overridingInfo = parent.getJSDocInfo();
+ Visibility overridingVisibility = overridingInfo == null ?
+ Visibility.INHERITED : overridingInfo.getVisibility();
+
+ // Check that (a) the property *can* be overridden, and
+ // (b) that the visibility of the override is the same as the
+ // visibility of the original property.
+ if (visibility == Visibility.PRIVATE && !sameInput) {
+ compiler.report(
+ t.makeError(getprop, PRIVATE_OVERRIDE,
+ objectType.toString()));
+ } else if (overridingVisibility != Visibility.INHERITED &&
+ overridingVisibility != visibility) {
+ compiler.report(
+ t.makeError(getprop, VISIBILITY_MISMATCH,
+ visibility.name(), objectType.toString(),
+ overridingVisibility.name()));
+ }
+ } else {
+ if (sameInput) {
+ // private access is always allowed in the same file.
+ return;
+ } else if (visibility == Visibility.PRIVATE &&
+ (currentClass == null || ownerType.differsFrom(currentClass))) {
+ if (docInfo.isConstructor() &&
+ isValidPrivateConstructorAccess(parent)) {
+ return;
+ }
+
+ // private access is not allowed outside the file from a different
+ // enclosing class.
+ compiler.report(
+ t.makeError(getprop,
+ BAD_PRIVATE_PROPERTY_ACCESS,
+ propertyName,
+ validator.getReadableJSTypeName(
+ getprop.getFirstChild(), true)));
+ } else if (visibility == Visibility.PROTECTED) {
+ // There are 3 types of legal accesses of a protected property:
+ // 1) Accesses in the same file
+ // 2) Overriding the property in a subclass
+ // 3) Accessing the property from inside a subclass
+ // The first two have already been checked for.
+ if (currentClass == null || !currentClass.isSubtype(ownerType)) {
+ compiler.report(
+ t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS,
+ propertyName,
+ validator.getReadableJSTypeName(
+ getprop.getFirstChild(), true)));
+ }
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNoPrivateAccessForProperties6() {
+ // Overriding a private property with a non-private property
+ // in a different file causes problems.
+ test(new String[] {
+ ""/** @constructor */ function Foo() {} "" +
+ ""/** @private */ Foo.prototype.bar_ = function() {};"",
+ ""/** @constructor \n * @extends {Foo} */ "" +
+ ""function SubFoo() {};"" +
+ ""SubFoo.prototype.bar_ = function() {};""
+ }, null, BAD_PRIVATE_PROPERTY_ACCESS);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void makeLocalNamesUnique(Node fnNode, boolean isCallInLoop) {
+ Supplier idSupplier = compiler.getUniqueNameIdSupplier();
+ // Make variable names unique to this instance.
+ NodeTraversal.traverse(
+ compiler, fnNode, new MakeDeclaredNamesUnique(
+ new InlineRenamer(
+ idSupplier,
+ ""inline_"",
+ isCallInLoop)));
+ // Make label names unique to this instance.
+ }
+
+// Test Case
+[/INST]
+ public void testInlineFunctions31() {
+ // Don't introduce a duplicate label in the same scope
+ test(""function foo(){ lab:{4;} }"" +
+ ""lab:{foo();}"",
+ ""lab:{{JSCompiler_inline_label_0:{4}}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitLabel(Node node, Node parent) {
+ Node nameNode = node.getFirstChild();
+ Preconditions.checkState(nameNode != null);
+ String name = nameNode.getString();
+ LabelInfo li = getLabelInfo(name);
+ // This is a label...
+ if (li.referenced) {
+ String newName = getNameForId(li.id);
+ if (!name.equals(newName)) {
+ // ... and it is used, give it the short name.
+ nameNode.setString(newName);
+ compiler.reportCodeChange();
+ }
+ } else {
+ // ... and it is not referenced, just remove it.
+ Node newChild = node.getLastChild();
+ node.removeChild(newChild);
+ parent.replaceChild(node, newChild);
+ if (newChild.getType() == Token.BLOCK) {
+ NodeUtil.tryMergeBlock(newChild);
+ }
+ compiler.reportCodeChange();
+ }
+
+ // Remove the label from the current stack of labels.
+ namespaceStack.peek().renameMap.remove(name);
+ }
+
+// Test Case
+[/INST]
+ public void testInlineFunctions31() {
+ // Don't introduce a duplicate label in the same scope
+ test(""function foo(){ lab:{4;} }"" +
+ ""lab:{foo();}"",
+ ""lab:{{JSCompiler_inline_label_0:{4}}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static String strEscape(String s, char quote,
+ String doublequoteEscape,
+ String singlequoteEscape,
+ String backslashEscape,
+ CharsetEncoder outputCharsetEncoder) {
+ StringBuilder sb = new StringBuilder(s.length() + 2);
+ sb.append(quote);
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ switch (c) {
+ case '\0': sb.append(""\\0""); break;
+ case '\n': sb.append(""\\n""); break;
+ case '\r': sb.append(""\\r""); break;
+ case '\t': sb.append(""\\t""); break;
+ case '\\': sb.append(backslashEscape); break;
+ case '\""': sb.append(doublequoteEscape); break;
+ case '\'': sb.append(singlequoteEscape); break;
+ case '>': // Break --> into --\> or ]]> into ]]\>
+ if (i >= 2 &&
+ ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||
+ (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {
+ sb.append(""\\>"");
+ } else {
+ sb.append(c);
+ }
+ break;
+ case '<':
+ // Break 0x1f && c <= 0x7f) {
+ sb.append(c);
+ } else {
+ // Other characters can be misinterpreted by some js parsers,
+ // or perhaps mangled by proxies along the way,
+ // so we play it safe and unicode escape them.
+ appendHexJavaScriptRepresentation(sb, c);
+ }
+ }
+ }
+ }
+ sb.append(quote);
+ return sb.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testUnicode() {
+ assertPrint(""var x ='\\x0f';"", ""var x=\""\\u000f\"""");
+ assertPrint(""var x ='\\x68';"", ""var x=\""h\"""");
+ assertPrint(""var x ='\\x7f';"", ""var x=\""\\u007f\"""");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""fallthrough"")
+ private Node tryFoldComparison(Node n, Node left, Node right) {
+ if (!NodeUtil.isLiteralValue(left, false) ||
+ !NodeUtil.isLiteralValue(right, false)) {
+ // We only handle non-literal operands for LT and GT.
+ if (n.getType() != Token.GT && n.getType() != Token.LT) {
+ return n;
+ }
+ }
+
+ int op = n.getType();
+ boolean result;
+
+ // TODO(johnlenz): Use the JSType to compare nodes of different types.
+
+ boolean rightLiteral = NodeUtil.isLiteralValue(right, false);
+ boolean undefinedRight = ((Token.NAME == right.getType()
+ && right.getString().equals(""undefined""))
+ || (Token.VOID == right.getType()
+ && NodeUtil.isLiteralValue(right.getFirstChild(), false)));
+ int lhType = left.getType();
+ int rhType = right.getType();
+ switch (lhType) {
+ case Token.VOID:
+ if (!NodeUtil.isLiteralValue(left.getFirstChild(), false)) {
+ return n;
+ } else if (!rightLiteral) {
+ return n;
+ } else {
+ result = compareToUndefined(right, op);
+ }
+ break;
+
+ case Token.NULL:
+ case Token.TRUE:
+ case Token.FALSE:
+ if (undefinedRight) {
+ result = compareToUndefined(left, op);
+ break;
+ }
+ if (rhType != Token.TRUE &&
+ rhType != Token.FALSE &&
+ rhType != Token.NULL) {
+ return n;
+ }
+ switch (op) {
+ case Token.SHEQ:
+ case Token.EQ:
+ result = lhType == rhType;
+ break;
+
+ case Token.SHNE:
+ case Token.NE:
+ result = lhType != rhType;
+ break;
+
+ case Token.GE:
+ case Token.LE:
+ case Token.GT:
+ case Token.LT:
+ Boolean compareResult = compareAsNumbers(op, left, right);
+ if (compareResult != null) {
+ result = compareResult;
+ } else {
+ return n;
+ }
+ break;
+
+ default:
+ return n; // we only handle == and != here
+ }
+ break;
+
+ case Token.THIS:
+ if (right.getType() != Token.THIS) {
+ return n;
+ }
+ switch (op) {
+ case Token.SHEQ:
+ case Token.EQ:
+ result = true;
+ break;
+
+ case Token.SHNE:
+ case Token.NE:
+ result = false;
+ break;
+
+ // We can only handle == and != here.
+ // GT, LT, GE, LE depend on the type of ""this"" and how it will
+ // be converted to number. The results are different depending on
+ // whether it is a string, NaN or other number value.
+ default:
+ return n;
+ }
+ break;
+
+ case Token.STRING:
+ if (undefinedRight) {
+ result = compareToUndefined(left, op);
+ break;
+ }
+ if (Token.STRING != right.getType()) {
+ return n; // Only eval if they are the same type
+ }
+ switch (op) {
+ case Token.SHEQ:
+ case Token.EQ:
+ result = left.getString().equals(right.getString());
+ break;
+
+ case Token.SHNE:
+ case Token.NE:
+ result = !left.getString().equals(right.getString());
+ break;
+
+ default:
+ return n; // we only handle == and != here
+ }
+ break;
+
+ case Token.NUMBER:
+ if (undefinedRight) {
+ result = compareToUndefined(left, op);
+ break;
+ }
+ if (Token.NUMBER != right.getType()) {
+ return n; // Only eval if they are the same type
+ }
+ Boolean compareResult = compareAsNumbers(op, left, right);
+ if (compareResult != null) {
+ result = compareResult;
+ } else {
+ return null;
+ }
+ break;
+
+ case Token.NAME:
+ if (undefinedRight) {
+ result = compareToUndefined(left, op);
+ break;
+ }
+
+ if (rightLiteral) {
+ boolean undefinedLeft = (left.getString().equals(""undefined""));
+ if (undefinedLeft) {
+ result = compareToUndefined(right, op);
+ break;
+ }
+ }
+
+ if (Token.NAME != right.getType()) {
+ return n; // Only eval if they are the same type
+ }
+ String ln = left.getString();
+ String rn = right.getString();
+ if (!ln.equals(rn)) {
+ return n; // Not the same value name.
+ }
+
+ switch (op) {
+ // If we knew the named value wouldn't be NaN, it would be nice
+ // to handle EQ,NE,LE,GE,SHEQ, and SHNE.
+ case Token.LT:
+ case Token.GT:
+ result = false;
+ break;
+ default:
+ return n; // don't handle that op
+ }
+ break;
+
+ default:
+ // assert, this should cover all consts
+ return n;
+ }
+
+ Node newNode = new Node(result ? Token.TRUE : Token.FALSE);
+ n.getParent().replaceChild(n, newNode);
+ reportCodeChange();
+
+ return newNode;
+ }
+
+// Test Case
+[/INST]
+ public void testFoldComparison3() {
+ fold(""x = !1 == !0"", ""x = false"");
+
+ fold(""x = !0 == !0"", ""x = true"");
+ fold(""x = !1 == !1"", ""x = true"");
+ fold(""x = !1 == null"", ""x = false"");
+ fold(""x = !1 == !0"", ""x = false"");
+ fold(""x = !0 == null"", ""x = false"");
+
+ fold(""!0 == !0"", ""true"");
+ fold(""!1 == null"", ""false"");
+ fold(""!1 == !0"", ""false"");
+ fold(""!0 == null"", ""false"");
+
+ fold(""x = !0 === !0"", ""x = true"");
+ fold(""x = !1 === !1"", ""x = true"");
+ fold(""x = !1 === null"", ""x = false"");
+ fold(""x = !1 === !0"", ""x = false"");
+ fold(""x = !0 === null"", ""x = false"");
+
+ fold(""!0 === !0"", ""true"");
+ fold(""!1 === null"", ""false"");
+ fold(""!1 === !0"", ""false"");
+ fold(""!0 === null"", ""false"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static Double getStringNumberValue(String rawJsString) {
+ // vertical tab is not always whitespace
+
+ String s = trimJsWhiteSpace(rawJsString);
+ // return ScriptRuntime.toNumber(s);
+ if (s.length() == 0) {
+ return 0.0;
+ }
+
+ if (s.length() > 2
+ && s.charAt(0) == '0'
+ && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
+ // Attempt to convert hex numbers.
+ try {
+ return Double.valueOf(Integer.parseInt(s.substring(2), 16));
+ } catch (NumberFormatException e) {
+ return Double.NaN;
+ }
+ }
+
+ if (s.length() > 3
+ && (s.charAt(0) == '-' || s.charAt(0) == '+')
+ && s.charAt(1) == '0'
+ && (s.charAt(2) == 'x' || s.charAt(2) == 'X')) {
+ // hex numbers with explicit signs vary between browsers.
+ return null;
+ }
+
+ // FireFox and IE treat the ""Infinity"" differently. FireFox is case
+ // insensitive, but IE treats ""infinity"" as NaN. So leave it alone.
+ if (s.equals(""infinity"")
+ || s.equals(""-infinity"")
+ || s.equals(""+infinity"")) {
+ return null;
+ }
+
+ try {
+ return Double.parseDouble(s);
+ } catch (NumberFormatException e) {
+ return Double.NaN;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIEString() {
+ testSame(""!+'\\v1'"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static TernaryValue isStrWhiteSpaceChar(int c) {
+ switch (c) {
+ case '\u000B': //
+ return TernaryValue.TRUE;
+ case ' ': //
+ case '\n': //
+ case '\r': //
+ case '\t': //
+ case '\u00A0': //
+ case '\u000C': //
+ case '\u2028': //
+ case '\u2029': //
+ case '\uFEFF': //
+ return TernaryValue.TRUE;
+ default:
+ return (Character.getType(c) == Character.SPACE_SEPARATOR)
+ ? TernaryValue.TRUE : TernaryValue.FALSE;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIEString() {
+ testSame(""!+'\\v1'"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isVariableStillLiveWithinExpression(
+ Node n, Node exprRoot, String variable) {
+ while (n != exprRoot) {
+ VariableLiveness state = VariableLiveness.MAYBE_LIVE;
+ switch (n.getParent().getType()) {
+ case Token.OR:
+ case Token.AND:
+ // If the currently node is the first child of
+ // AND/OR, be conservative only consider the READs
+ // of the second operand.
+
+ case Token.HOOK:
+ // If current node is the condition, check each following
+ // branch, otherwise it is a conditional branch and the
+ // other branch can be ignored.
+
+ default:
+ for(Node sibling = n.getNext(); sibling != null;
+ sibling = sibling.getNext()) {
+ if (!ControlFlowGraph.isEnteringNewCfgNode(sibling)) {
+ state = isVariableReadBeforeKill(sibling, variable);
+
+ // If we see a READ or KILL there is no need to continue.
+ if (state == VariableLiveness.READ) {
+ return true;
+ } else if (state == VariableLiveness.KILL) {
+ return false;
+ }
+ }
+ }
+ }
+ n = n.getParent();
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testInExpression2() {
+ // This can be improved. ""a = 1"" is dead but ""a"" is read in the following
+ // expression.
+ inFunction(
+ ""var a; a = 1; if ((a = 2) || (a = 3) || (a)) {}"",
+ ""var a; a = 1; if (( 2) || (a = 3) || (a)) {}"");
+
+ inFunction(
+ ""var a; (a = 1) || (a = 2)"",
+ ""var a; 1 || 2"");
+
+ inFunction(""var a; (a = 1) || (a = 2); return a"");
+
+ inFunction(
+ ""var a; a = 1; a ? a = 2 : a;"",
+ ""var a; a = 1; a ? 2 : a;"");
+
+ inFunction(""var a; a = 1; a ? a = 2 : a; return a"");
+
+ inFunction(
+ ""var a; a = 1; a ? a : a = 2;"",
+ ""var a; a = 1; a ? a : 2;"");
+
+ inFunction(""var a; a = 1; a ? a : a =2; return a"");
+
+ inFunction(
+ ""var a; (a = 1) ? a = 2 : a = 3;"",
+ ""var a; 1 ? 2 : 3;"");
+
+ // This can be improved. ""a = 1"" is dead but ""a"" is read in the following
+ // expression.
+ inFunction(""var a; (a = 1) ? a = 2 : a = 3; return a"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private VariableLiveness isVariableReadBeforeKill(
+ Node n, String variable) {
+
+ if (NodeUtil.isName(n) && variable.equals(n.getString())) {
+ if (NodeUtil.isLhs(n, n.getParent())) {
+ Preconditions.checkState(n.getParent().getType() == Token.ASSIGN);
+ // The expression to which the assignment is made is evaluated before
+ // the RHS is evaluated (normal left to right evaluation) but the KILL
+ // occurs after the RHS is evaluated.
+ Node rhs = n.getNext();
+ VariableLiveness state = isVariableReadBeforeKill(rhs, variable);
+ if (state == VariableLiveness.READ) {
+ return state;
+ }
+ return VariableLiveness.KILL;
+ } else {
+ return VariableLiveness.READ;
+ }
+ }
+
+ switch (n.getType()) {
+ // Conditionals
+ case Token.OR:
+ case Token.AND:
+ // With a AND/OR the first branch always runs, but the second is
+ // may not.
+ case Token.HOOK:
+ return checkHookBranchReadBeforeKill(
+ n.getFirstChild().getNext(), n.getLastChild(), variable);
+
+ default:
+ // Expressions are evaluated left-right, depth first.
+ for (Node child = n.getFirstChild();
+ child != null; child = child.getNext()) {
+ if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION
+ VariableLiveness state = isVariableReadBeforeKill(child, variable);
+ if (state != VariableLiveness.MAYBE_LIVE) {
+ return state;
+ }
+ }
+ }
+ }
+
+ return VariableLiveness.MAYBE_LIVE;
+ }
+
+// Test Case
+[/INST]
+ public void testInExpression2() {
+ // This can be improved. ""a = 1"" is dead but ""a"" is read in the following
+ // expression.
+ inFunction(
+ ""var a; a = 1; if ((a = 2) || (a = 3) || (a)) {}"",
+ ""var a; a = 1; if (( 2) || (a = 3) || (a)) {}"");
+
+ inFunction(
+ ""var a; (a = 1) || (a = 2)"",
+ ""var a; 1 || 2"");
+
+ inFunction(""var a; (a = 1) || (a = 2); return a"");
+
+ inFunction(
+ ""var a; a = 1; a ? a = 2 : a;"",
+ ""var a; a = 1; a ? 2 : a;"");
+
+ inFunction(""var a; a = 1; a ? a = 2 : a; return a"");
+
+ inFunction(
+ ""var a; a = 1; a ? a : a = 2;"",
+ ""var a; a = 1; a ? a : 2;"");
+
+ inFunction(""var a; a = 1; a ? a : a =2; return a"");
+
+ inFunction(
+ ""var a; (a = 1) ? a = 2 : a = 3;"",
+ ""var a; 1 ? 2 : 3;"");
+
+ // This can be improved. ""a = 1"" is dead but ""a"" is read in the following
+ // expression.
+ inFunction(""var a; (a = 1) ? a = 2 : a = 3; return a"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static String strEscape(String s, char quote,
+ String doublequoteEscape,
+ String singlequoteEscape,
+ String backslashEscape,
+ CharsetEncoder outputCharsetEncoder) {
+ StringBuilder sb = new StringBuilder(s.length() + 2);
+ sb.append(quote);
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ switch (c) {
+ case '\n': sb.append(""\\n""); break;
+ case '\r': sb.append(""\\r""); break;
+ case '\t': sb.append(""\\t""); break;
+ case '\\': sb.append(backslashEscape); break;
+ case '\""': sb.append(doublequoteEscape); break;
+ case '\'': sb.append(singlequoteEscape); break;
+ case '>': // Break --> into --\> or ]]> into ]]\>
+ if (i >= 2 &&
+ ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||
+ (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {
+ sb.append(""\\>"");
+ } else {
+ sb.append(c);
+ }
+ break;
+ case '<':
+ // Break 0x1f && c <= 0x7f) {
+ sb.append(c);
+ } else {
+ // Other characters can be misinterpreted by some js parsers,
+ // or perhaps mangled by proxies along the way,
+ // so we play it safe and unicode escape them.
+ appendHexJavaScriptRepresentation(sb, c);
+ }
+ }
+ }
+ }
+ sb.append(quote);
+ return sb.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testZero() {
+ assertPrint(""var x ='\\0';"", ""var x=\""\\0\"""");
+ assertPrint(""var x ='\\x00';"", ""var x=\""\\0\"""");
+ assertPrint(""var x ='\\u0000';"", ""var x=\""\\0\"""");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node performArithmeticOp(int opType, Node left, Node right) {
+ // Unlike other operations, ADD operands are not always converted
+ // to Number.
+ if (opType == Token.ADD
+ && (NodeUtil.mayBeString(left, false)
+ || NodeUtil.mayBeString(right, false))) {
+ return null;
+ }
+
+ double result;
+
+ // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN
+ // to zero so this is a little akward here.
+
+ Double lValObj = NodeUtil.getNumberValue(left);
+ if (lValObj == null) {
+ return null;
+ }
+ Double rValObj = NodeUtil.getNumberValue(right);
+ if (rValObj == null) {
+ return null;
+ }
+
+ double lval = lValObj;
+ double rval = rValObj;
+
+ switch (opType) {
+ case Token.BITAND:
+ result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval);
+ break;
+ case Token.BITOR:
+ result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval);
+ break;
+ case Token.BITXOR:
+ result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval);
+ break;
+ case Token.ADD:
+ result = lval + rval;
+ break;
+ case Token.SUB:
+ result = lval - rval;
+ break;
+ case Token.MUL:
+ result = lval * rval;
+ break;
+ case Token.MOD:
+ if (rval == 0) {
+ error(DiagnosticType.error(""JSC_DIVIDE_BY_0_ERROR"", ""Divide by 0""), right);
+ return null;
+ }
+ result = lval % rval;
+ break;
+ case Token.DIV:
+ if (rval == 0) {
+ error(DiagnosticType.error(""JSC_DIVIDE_BY_0_ERROR"", ""Divide by 0""), right);
+ return null;
+ }
+ result = lval / rval;
+ break;
+ default:
+ throw new Error(""Unexpected arithmetic operator"");
+ }
+
+ // TODO(johnlenz): consider removing the result length check.
+ // length of the left and right value plus 1 byte for the operator.
+ if (String.valueOf(result).length() <=
+ String.valueOf(lval).length() + String.valueOf(rval).length() + 1 &&
+
+ // Do not try to fold arithmetic for numbers > 2^53. After that
+ // point, fixed-point math starts to break down and become inaccurate.
+ Math.abs(result) <= MAX_FOLD_NUMBER) {
+ Node newNumber = Node.newNumber(result);
+ return newNumber;
+ } else if (Double.isNaN(result)) {
+ return Node.newString(Token.NAME, ""NaN"");
+ } else if (result == Double.POSITIVE_INFINITY) {
+ return Node.newString(Token.NAME, ""Infinity"");
+ } else if (result == Double.NEGATIVE_INFINITY) {
+ return new Node(Token.NEG, Node.newString(Token.NAME, ""Infinity""));
+ }
+
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testFoldArithmetic() {
+ fold(""x = 10 + 20"", ""x = 30"");
+ fold(""x = 2 / 4"", ""x = 0.5"");
+ fold(""x = 2.25 * 3"", ""x = 6.75"");
+ fold(""z = x * y"", ""z = x * y"");
+ fold(""x = y * 5"", ""x = y * 5"");
+ fold(""x = 1 / 0"", ""x = 1 / 0"");
+ fold(""x = 3 % 2"", ""x = 1"");
+ fold(""x = 3 % -2"", ""x = 1"");
+ fold(""x = -1 % 3"", ""x = -1"");
+ fold(""x = 1 % 0"", ""x = 1 % 0"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void process(Node externs, Node root) {
+ new NodeTraversal(
+ compiler, new NormalizeStatements(compiler, assertOnChange))
+ .traverse(root);
+ if (MAKE_LOCAL_NAMES_UNIQUE) {
+ MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
+ NodeTraversal t = new NodeTraversal(compiler, renamer);
+ t.traverseRoots(externs, root);
+ }
+ // It is important that removeDuplicateDeclarations runs after
+ // MakeDeclaredNamesUnique in order for catch block exception names to be
+ // handled properly. Specifically, catch block exception names are
+ // only valid within the catch block, but our currect Scope logic
+ // has no concept of this and includes it in the containing function
+ // (or global scope). MakeDeclaredNamesUnique makes the catch exception
+ // names unique so that removeDuplicateDeclarations() will properly handle
+ // cases where a function scope variable conflict with a exception name:
+ // function f() {
+ // try {throw 0;} catch(e) {e; /* catch scope 'e'*/}
+ // var e = 1; // f scope 'e'
+ // }
+ // otherwise 'var e = 1' would be rewritten as 'e = 1'.
+ // TODO(johnlenz): Introduce a seperate scope for catch nodes.
+ removeDuplicateDeclarations(externs, root);
+ new PropagateConstantAnnotationsOverVars(compiler, assertOnChange)
+ .process(externs, root);
+
+ if (!compiler.getLifeCycleStage().isNormalized()) {
+ compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue166a() {
+ test(""try { throw 1 } catch(e) { /** @suppress {duplicate} */ var e=2 }"",
+ ""try { throw 1 } catch(e) { var e=2 }"",
+ Normalize.CATCH_BLOCK_VAR_ERROR);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void createSynthesizedExternVar(String varName) {
+ Node nameNode = Node.newString(Token.NAME, varName);
+
+ // Mark the variable as constant if it matches the coding convention
+ // for constant vars.
+ // NOTE(nicksantos): honestly, i'm not sure how much this matters.
+ // AFAIK, all people who use the CONST coding convention also
+ // compile with undeclaredVars as errors. We have some test
+ // cases for this configuration though, and it makes them happier.
+ if (compiler.getCodingConvention().isConstant(varName)) {
+ nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
+ }
+
+ getSynthesizedExternsRoot().addChildToBack(
+ new Node(Token.VAR, nameNode));
+ varsToDeclareInExterns.remove(varName);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue166a() {
+ test(""try { throw 1 } catch(e) { /** @suppress {duplicate} */ var e=2 }"",
+ ""try { throw 1 } catch(e) { var e=2 }"",
+ Normalize.CATCH_BLOCK_VAR_ERROR);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean canBeRedeclared(Node n, Scope s) {
+ if (!NodeUtil.isExprAssign(n)) {
+ return false;
+ }
+ Node assign = n.getFirstChild();
+ Node lhs = assign.getFirstChild();
+
+ if (!lhs.isName()) {
+ return false;
+ }
+
+ Var var = s.getVar(lhs.getString());
+ return var != null
+ && var.getScope() == s
+ && !blacklistedVars.contains(var);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue820() throws Exception {
+ // Don't redeclare function parameters, this is incompatible with
+ // strict mode.
+ testSame(""function f(a){ var b=1; a=2; var c; }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean isBooleanResultHelper(Node n) {
+ switch (n.getType()) {
+ // Primitives
+ case Token.TRUE:
+ case Token.FALSE:
+ // Comparisons
+ case Token.EQ:
+ case Token.NE:
+ case Token.SHEQ:
+ case Token.SHNE:
+ case Token.LT:
+ case Token.GT:
+ case Token.LE:
+ case Token.GE:
+ // Queryies
+ case Token.IN:
+ case Token.INSTANCEOF:
+ // Inversion
+ case Token.NOT:
+ // delete operator returns a boolean.
+ return true;
+ default:
+ return false;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIsBooleanResult() {
+ assertFalse(NodeUtil.isBooleanResult(getNode(""1"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""true"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""+true"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""+1"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""-1"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""-Infinity"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""Infinity"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""NaN"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""undefined"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""void 0"")));
+
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a << b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a >> b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a >>> b"")));
+
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a == b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a != b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a === b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a !== b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a < b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a > b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a <= b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a >= b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a in b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a instanceof b"")));
+
+ assertFalse(NodeUtil.isBooleanResult(getNode(""'a'"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""'a'+b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a+'b'"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a+b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a()"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""''.a"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a.b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a.b()"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a().b()"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""new a()"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""delete a"")));
+
+ // Definitely not boolean
+ assertFalse(NodeUtil.isBooleanResult(getNode(""([true,false])"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""({a:true})"")));
+
+ // These are boolean but aren't handled yet, ""false"" here means ""unknown"".
+ assertTrue(NodeUtil.isBooleanResult(getNode(""true && false"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""true || false"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a ? true : false"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a,true"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a=true"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a=1"")));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean evaluatesToLocalValue(Node value, Predicate locals) {
+ switch (value.getType()) {
+ case Token.ASSIGN:
+ // A result that is aliased by a non-local name, is the effectively the
+ // same as returning a non-local name, but this doesn't matter if the
+ // value is immutable.
+ return NodeUtil.isImmutableValue(value.getLastChild())
+ || (locals.apply(value)
+ && evaluatesToLocalValue(value.getLastChild(), locals));
+ case Token.COMMA:
+ return evaluatesToLocalValue(value.getLastChild(), locals);
+ case Token.AND:
+ case Token.OR:
+ return evaluatesToLocalValue(value.getFirstChild(), locals)
+ && evaluatesToLocalValue(value.getLastChild(), locals);
+ case Token.HOOK:
+ return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)
+ && evaluatesToLocalValue(value.getLastChild(), locals);
+ case Token.INC:
+ case Token.DEC:
+ if (value.getBooleanProp(Node.INCRDECR_PROP)) {
+ return evaluatesToLocalValue(value.getFirstChild(), locals);
+ } else {
+ return true;
+ }
+ case Token.THIS:
+ return locals.apply(value);
+ case Token.NAME:
+ return isImmutableValue(value) || locals.apply(value);
+ case Token.GETELEM:
+ case Token.GETPROP:
+ // There is no information about the locality of object properties.
+ return locals.apply(value);
+ case Token.CALL:
+ return callHasLocalResult(value)
+ || isToStringMethodCall(value)
+ || locals.apply(value);
+ case Token.NEW:
+ return newHasLocalResult(value)
+ || locals.apply(value);
+ case Token.FUNCTION:
+ case Token.REGEXP:
+ case Token.ARRAYLIT:
+ case Token.OBJECTLIT:
+ // Literals objects with non-literal children are allowed.
+ return true;
+ case Token.IN:
+ // TODO(johnlenz): should IN operator be included in #isSimpleOperator?
+ return true;
+ default:
+ // Other op force a local value:
+ // x = '' + g (x is now an local string)
+ // x -= g (x is now an local number)
+ if (isAssignmentOp(value)
+ || isSimpleOperator(value)
+ || isImmutableValue(value)) {
+ return true;
+ }
+
+ throw new IllegalStateException(
+ ""Unexpected expression node"" + value +
+ ""\n parent:"" + value.getParent());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIsBooleanResult() {
+ assertFalse(NodeUtil.isBooleanResult(getNode(""1"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""true"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""+true"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""+1"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""-1"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""-Infinity"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""Infinity"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""NaN"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""undefined"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""void 0"")));
+
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a << b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a >> b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a >>> b"")));
+
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a == b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a != b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a === b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a !== b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a < b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a > b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a <= b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a >= b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a in b"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a instanceof b"")));
+
+ assertFalse(NodeUtil.isBooleanResult(getNode(""'a'"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""'a'+b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a+'b'"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a+b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a()"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""''.a"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a.b"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a.b()"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a().b()"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""new a()"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""delete a"")));
+
+ // Definitely not boolean
+ assertFalse(NodeUtil.isBooleanResult(getNode(""([true,false])"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""({a:true})"")));
+
+ // These are boolean but aren't handled yet, ""false"" here means ""unknown"".
+ assertTrue(NodeUtil.isBooleanResult(getNode(""true && false"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""true || false"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a ? true : false"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a,true"")));
+ assertTrue(NodeUtil.isBooleanResult(getNode(""a=true"")));
+ assertFalse(NodeUtil.isBooleanResult(getNode(""a=1"")));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Node processFunctionNode(FunctionNode functionNode) {
+ Name name = functionNode.getFunctionName();
+ Boolean isUnnamedFunction = false;
+ if (name == null) {
+ name = new Name();
+ name.setIdentifier("""");
+ isUnnamedFunction = true;
+ }
+ Node node = newNode(Token.FUNCTION);
+ Node newName = transform(name);
+ if (isUnnamedFunction) {
+ // Old Rhino tagged the empty name node with the line number of the
+ // declaration.
+ newName.setLineno(functionNode.getLineno());
+ // TODO(bowdidge) Mark line number of paren correctly.
+ // Same problem as below - the left paren might not be on the
+ // same line as the function keyword.
+ int lpColumn = functionNode.getAbsolutePosition() +
+ functionNode.getLp();
+ newName.setCharno(position2charno(lpColumn));
+ }
+
+ node.addChildToBack(newName);
+ Node lp = newNode(Token.LP);
+ // The left paren's complicated because it's not represented by an
+ // AstNode, so there's nothing that has the actual line number that it
+ // appeared on. We know the paren has to appear on the same line as the
+ // function name (or else a semicolon will be inserted.) If there's no
+ // function name, assume the paren was on the same line as the function.
+ // TODO(bowdidge): Mark line number of paren correctly.
+ Name fnName = functionNode.getFunctionName();
+ if (fnName != null) {
+ lp.setLineno(fnName.getLineno());
+ } else {
+ lp.setLineno(functionNode.getLineno());
+ }
+ int lparenCharno = functionNode.getLp() +
+ functionNode.getAbsolutePosition();
+
+ lp.setCharno(position2charno(lparenCharno));
+ for (AstNode param : functionNode.getParams()) {
+ lp.addChildToBack(transform(param));
+ }
+ node.addChildToBack(lp);
+
+ Node bodyNode = transform(functionNode.getBody());
+ parseDirectives(bodyNode);
+ node.addChildToBack(bodyNode);
+ return node;
+ }
+
+// Test Case
+[/INST]
+ public void testUnnamedFunctionStatement() {
+ // Statements
+ parseError(""function() {};"", ""unnamed function statement"");
+ parseError(""if (true) { function() {}; }"", ""unnamed function statement"");
+ parse(""function f() {};"");
+ // Expressions
+ parse(""(function f() {});"");
+ parse(""(function () {});"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final boolean isEmptyType() {
+ return isNoType() || isNoObjectType() || isNoResolvedType();
+ }
+
+// Test Case
+[/INST]
+ public void testIssue301() throws Exception {
+ testTypes(
+ ""Array.indexOf = function() {};"" +
+ ""var s = 'hello';"" +
+ ""alert(s.toLowerCase.indexOf('1'));"",
+ ""Property indexOf never defined on String.prototype.toLowerCase"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int parseArguments(Parameters params) throws CmdLineException {
+ String param = params.getParameter(0);
+
+ if (param == null) {
+ setter.addValue(true);
+ return 0;
+ } else {
+ String lowerParam = param.toLowerCase();
+ if (TRUES.contains(lowerParam)) {
+ setter.addValue(true);
+ } else if (FALSES.contains(lowerParam)) {
+ setter.addValue(false);
+ } else {
+ setter.addValue(true);
+ return 0;
+ }
+ return 1;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testVersionFlag2() {
+ lastArg = ""--version"";
+ testSame("""");
+ assertEquals(
+ 0,
+ new String(errReader.toByteArray()).indexOf(
+ ""Closure Compiler (http://code.google.com/closure/compiler)\n"" +
+ ""Version: ""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ Node processAssignment(Assignment assignmentNode) {
+ Node assign = processInfixExpression(assignmentNode);
+ return assign;
+ }
+
+// Test Case
+[/INST]
+ public void testDestructuringAssignForbidden4() {
+ parseError(""[x, y] = foo();"",
+ ""destructuring assignment forbidden"",
+ ""invalid assignment target"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ Node processUnaryExpression(UnaryExpression exprNode) {
+ int type = transformTokenType(exprNode.getType());
+ Node operand = transform(exprNode.getOperand());
+ if (type == Token.NEG && operand.getType() == Token.NUMBER) {
+ operand.setDouble(-operand.getDouble());
+ return operand;
+ } else {
+
+ Node node = newNode(type, operand);
+ if (exprNode.isPostfix()) {
+ node.putBooleanProp(Node.INCRDECR_PROP, true);
+ }
+ return node;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDestructuringAssignForbidden4() {
+ parseError(""[x, y] = foo();"",
+ ""destructuring assignment forbidden"",
+ ""invalid assignment target"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""fallthrough"")
+ private Node tryRemoveUnconditionalBranching(Node n) {
+ /*
+ * For each of the unconditional branching control flow node, check to see
+ * if the ControlFlowAnalysis.computeFollowNode of that node is same as
+ * the branching target. If it is, the branch node is safe to be removed.
+ *
+ * This is not as clever as MinimizeExitPoints because it doesn't do any
+ * if-else conversion but it handles more complicated switch statements
+ * much nicer.
+ */
+
+ // If n is null the target is the end of the function, nothing to do.
+ if (n == null) {
+ return n;
+ }
+
+ DiGraphNode gNode = curCfg.getDirectedGraphNode(n);
+
+ if (gNode == null) {
+ return n;
+ }
+
+ if (n.getParent() == null) {
+ List> outEdges = gNode.getOutEdges();
+ if (outEdges.size() == 1) {
+ return tryRemoveUnconditionalBranching(outEdges.get(0).getDestination().getValue());
+ }
+ }
+ switch (n.getType()) {
+ case Token.BLOCK:
+ if (n.hasChildren()) {
+ Node first = n.getFirstChild();
+ return tryRemoveUnconditionalBranching(first);
+ } else {
+ return tryRemoveUnconditionalBranching(ControlFlowAnalysis.computeFollowNode(n));
+ }
+ case Token.RETURN:
+ if (n.hasChildren()) {
+ break;
+ }
+ case Token.BREAK:
+ case Token.CONTINUE:
+
+ // We are looking for a control flow changing statement that always
+ // branches to the same node. If removing it the control flow still
+ // branches to that same node. It is safe to remove it.
+ List> outEdges = gNode.getOutEdges();
+ if (outEdges.size() == 1 &&
+ // If there is a next node, there is no chance this jump is useless.
+ (n.getNext() == null || n.getNext().getType() == Token.FUNCTION)) {
+
+ Preconditions.checkState(outEdges.get(0).getValue() == Branch.UNCOND);
+ Node fallThrough = tryRemoveUnconditionalBranching(computeFollowing(n));
+ Node nextCfgNode = outEdges.get(0).getDestination().getValue();
+ if (nextCfgNode == fallThrough) {
+ removeDeadExprStatementSafely(n);
+ return fallThrough;
+ }
+ }
+ }
+ return n;
+ }
+
+// Test Case
+[/INST]
+ public void testCascadedRemovalOfUnlessUnconditonalJumps() {
+ test(""switch (a) { case 'a': break; case 'b': break; case 'c': break }"",
+ ""switch (a) { case 'a': break; case 'b': case 'c': }"");
+ // Only one break removed per pass.
+ test(""switch (a) { case 'a': break; case 'b': case 'c': }"",
+ ""switch (a) { case 'a': case 'b': case 'c': }"");
+
+ test(""function foo() {"" +
+ "" switch (a) { case 'a':return; case 'b':return; case 'c':return }}"",
+ ""function foo() { switch (a) { case 'a':return; case 'b': case 'c': }}"");
+ test(""function foo() {"" +
+ "" switch (a) { case 'a':return; case 'b': case 'c': }}"",
+ ""function foo() { switch (a) { case 'a': case 'b': case 'c': }}"");
+
+ testSame(""function foo() {"" +
+ ""switch (a) { case 'a':return 2; case 'b':return 1}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node computeFollowing(Node n) {
+ Node next = ControlFlowAnalysis.computeFollowNode(n);
+ return next;
+ }
+
+// Test Case
+[/INST]
+ public void testCascadedRemovalOfUnlessUnconditonalJumps() {
+ test(""switch (a) { case 'a': break; case 'b': break; case 'c': break }"",
+ ""switch (a) { case 'a': break; case 'b': case 'c': }"");
+ // Only one break removed per pass.
+ test(""switch (a) { case 'a': break; case 'b': case 'c': }"",
+ ""switch (a) { case 'a': case 'b': case 'c': }"");
+
+ test(""function foo() {"" +
+ "" switch (a) { case 'a':return; case 'b':return; case 'c':return }}"",
+ ""function foo() { switch (a) { case 'a':return; case 'b': case 'c': }}"");
+ test(""function foo() {"" +
+ "" switch (a) { case 'a':return; case 'b': case 'c': }}"",
+ ""function foo() { switch (a) { case 'a': case 'b': case 'c': }}"");
+
+ testSame(""function foo() {"" +
+ ""switch (a) { case 'a':return 2; case 'b':return 1}}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean evaluatesToLocalValue(Node value, Predicate locals) {
+ switch (value.getType()) {
+ case Token.ASSIGN:
+ // A result that is aliased by a non-local name, is the effectively the
+ // same as returning a non-local name, but this doesn't matter if the
+ // value is immutable.
+ return NodeUtil.isImmutableValue(value.getLastChild())
+ || (locals.apply(value)
+ && evaluatesToLocalValue(value.getLastChild(), locals));
+ case Token.COMMA:
+ return evaluatesToLocalValue(value.getLastChild(), locals);
+ case Token.AND:
+ case Token.OR:
+ return evaluatesToLocalValue(value.getFirstChild(), locals)
+ && evaluatesToLocalValue(value.getLastChild(), locals);
+ case Token.HOOK:
+ return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)
+ && evaluatesToLocalValue(value.getLastChild(), locals);
+ case Token.INC:
+ case Token.DEC:
+ if (value.getBooleanProp(Node.INCRDECR_PROP)) {
+ return evaluatesToLocalValue(value.getFirstChild(), locals);
+ } else {
+ return true;
+ }
+ case Token.THIS:
+ return locals.apply(value);
+ case Token.NAME:
+ return isImmutableValue(value) || locals.apply(value);
+ case Token.GETELEM:
+ case Token.GETPROP:
+ // There is no information about the locality of object properties.
+ return locals.apply(value);
+ case Token.CALL:
+ return callHasLocalResult(value)
+ || isToStringMethodCall(value)
+ || locals.apply(value);
+ case Token.NEW:
+ // TODO(nicksantos): This needs to be changed so that it
+ // returns true iff we're sure the value was never aliased from inside
+ // the constructor (similar to callHasLocalResult)
+ return true;
+ case Token.FUNCTION:
+ case Token.REGEXP:
+ case Token.ARRAYLIT:
+ case Token.OBJECTLIT:
+ // Literals objects with non-literal children are allowed.
+ return true;
+ case Token.IN:
+ // TODO(johnlenz): should IN operator be included in #isSimpleOperator?
+ return true;
+ default:
+ // Other op force a local value:
+ // x = '' + g (x is now an local string)
+ // x -= g (x is now an local number)
+ if (isAssignmentOp(value)
+ || isSimpleOperator(value)
+ || isImmutableValue(value)) {
+ return true;
+ }
+
+ throw new IllegalStateException(
+ ""Unexpected expression node"" + value +
+ ""\n parent:"" + value.getParent());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLocalValue1() throws Exception {
+ // Names are not known to be local.
+ assertFalse(testLocalValue(""x""));
+ assertFalse(testLocalValue(""x()""));
+ assertFalse(testLocalValue(""this""));
+ assertFalse(testLocalValue(""arguments""));
+
+ // We can't know if new objects are local unless we know
+ // that they don't alias themselves.
+ assertFalse(testLocalValue(""new x()""));
+
+ // property references are assume to be non-local
+ assertFalse(testLocalValue(""(new x()).y""));
+ assertFalse(testLocalValue(""(new x())['y']""));
+
+ // Primitive values are local
+ assertTrue(testLocalValue(""null""));
+ assertTrue(testLocalValue(""undefined""));
+ assertTrue(testLocalValue(""Infinity""));
+ assertTrue(testLocalValue(""NaN""));
+ assertTrue(testLocalValue(""1""));
+ assertTrue(testLocalValue(""'a'""));
+ assertTrue(testLocalValue(""true""));
+ assertTrue(testLocalValue(""false""));
+ assertTrue(testLocalValue(""[]""));
+ assertTrue(testLocalValue(""{}""));
+
+ // The contents of arrays and objects don't matter
+ assertTrue(testLocalValue(""[x]""));
+ assertTrue(testLocalValue(""{'a':x}""));
+
+ // Pre-increment results in primitive number
+ assertTrue(testLocalValue(""++x""));
+ assertTrue(testLocalValue(""--x""));
+
+ // Post-increment, the previous value matters.
+ assertFalse(testLocalValue(""x++""));
+ assertFalse(testLocalValue(""x--""));
+
+ // The left side of an only assign matters if it is an alias or mutable.
+ assertTrue(testLocalValue(""x=1""));
+ assertFalse(testLocalValue(""x=[]""));
+ assertFalse(testLocalValue(""x=y""));
+ // The right hand side of assignment opts don't matter, as they force
+ // a local result.
+ assertTrue(testLocalValue(""x+=y""));
+ assertTrue(testLocalValue(""x*=y""));
+ // Comparisons always result in locals, as they force a local boolean
+ // result.
+ assertTrue(testLocalValue(""x==y""));
+ assertTrue(testLocalValue(""x!=y""));
+ assertTrue(testLocalValue(""x>y""));
+ // Only the right side of a comma matters
+ assertTrue(testLocalValue(""(1,2)""));
+ assertTrue(testLocalValue(""(x,1)""));
+ assertFalse(testLocalValue(""(x,y)""));
+
+ // Both the operands of OR matter
+ assertTrue(testLocalValue(""1||2""));
+ assertFalse(testLocalValue(""x||1""));
+ assertFalse(testLocalValue(""x||y""));
+ assertFalse(testLocalValue(""1||y""));
+
+ // Both the operands of AND matter
+ assertTrue(testLocalValue(""1&&2""));
+ assertFalse(testLocalValue(""x&&1""));
+ assertFalse(testLocalValue(""x&&y""));
+ assertFalse(testLocalValue(""1&&y""));
+
+ // Only the results of HOOK matter
+ assertTrue(testLocalValue(""x?1:2""));
+ assertFalse(testLocalValue(""x?x:2""));
+ assertFalse(testLocalValue(""x?1:x""));
+ assertFalse(testLocalValue(""x?x:y""));
+
+ // Results of ops are local values
+ assertTrue(testLocalValue(""!y""));
+ assertTrue(testLocalValue(""~y""));
+ assertTrue(testLocalValue(""y + 1""));
+ assertTrue(testLocalValue(""y + z""));
+ assertTrue(testLocalValue(""y * z""));
+
+ assertTrue(testLocalValue(""'a' in x""));
+ assertTrue(testLocalValue(""typeof x""));
+ assertTrue(testLocalValue(""x instanceof y""));
+
+ assertTrue(testLocalValue(""void x""));
+ assertTrue(testLocalValue(""void 0""));
+
+ assertFalse(testLocalValue(""{}.x""));
+
+ assertTrue(testLocalValue(""{}.toString()""));
+ assertTrue(testLocalValue(""o.toString()""));
+
+ assertFalse(testLocalValue(""o.valueOf()""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean isFoldableExpressBlock(Node n) {
+ if (n.getType() == Token.BLOCK) {
+ if (n.hasOneChild()) {
+ Node maybeExpr = n.getFirstChild();
+ // IE has a bug where event handlers behave differently when
+ // their return value is used vs. when their return value is in
+ // an EXPR_RESULT. It's pretty freaking weird. See:
+ // http://code.google.com/p/closure-compiler/issues/detail?id=291
+ // We try to detect this case, and not fold EXPR_RESULTs
+ // into other expressions.
+
+ // We only have to worry about methods with an implicit 'this'
+ // param, or this doesn't happen.
+
+ return NodeUtil.isExpressionNode(maybeExpr);
+ }
+ }
+
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue291() {
+ fold(""if (true) { f.onchange(); }"", ""if (1) f.onchange();"");
+ foldSame(""if (f) { f.onchange(); }"");
+ foldSame(""if (f) { f.bar(); } else { f.onchange(); }"");
+ fold(""if (f) { f.bonchange(); }"", ""f && f.bonchange();"");
+ foldSame(""if (f) { f['x'](); }"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private VariableLiveness isVariableReadBeforeKill(
+ Node n, String variable) {
+ if (NodeUtil.isName(n) && variable.equals(n.getString())) {
+ if (NodeUtil.isLhs(n, n.getParent())) {
+ // The expression to which the assignment is made is evaluated before
+ // the RHS is evaluated (normal left to right evaluation) but the KILL
+ // occurs after the RHS is evaluated.
+ return VariableLiveness.KILL;
+ } else {
+ return VariableLiveness.READ;
+ }
+ }
+
+ // Expressions are evaluated left-right, depth first.
+ for (Node child = n.getFirstChild();
+ child != null; child = child.getNext()) {
+ if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION
+ VariableLiveness state = isVariableReadBeforeKill(child, variable);
+ if (state != VariableLiveness.MAYBE_LIVE) {
+ return state;
+ }
+ }
+ }
+ return VariableLiveness.MAYBE_LIVE;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue297() {
+ args.add(""--compilation_level=SIMPLE_OPTIMIZATIONS"");
+ test(""function f(p) {"" +
+ "" var x;"" +
+ "" return ((x=p.id) && (x=parseInt(x.substr(1))) && x>0);"" +
+ ""}"",
+ ""function f(b) {"" +
+ "" var a;"" +
+ "" return ((a=b.id) && (a=parseInt(a.substr(1))) && a>0);"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void updateSimpleDeclaration(String alias, Name refName, Ref ref) {
+ Node rvalue = ref.node.getNext();
+ Node parent = ref.node.getParent();
+ Node gramps = parent.getParent();
+ Node greatGramps = gramps.getParent();
+ Node greatGreatGramps = greatGramps.getParent();
+
+
+ // Create the new alias node.
+ Node nameNode = NodeUtil.newName(
+ compiler.getCodingConvention(), alias, gramps.getFirstChild(),
+ refName.fullName());
+ NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode);
+
+ if (gramps.getType() == Token.EXPR_RESULT) {
+ // BEFORE: a.b.c = ...;
+ // exprstmt
+ // assign
+ // getprop
+ // getprop
+ // name a
+ // string b
+ // string c
+ // NODE
+ // AFTER: var a$b$c = ...;
+ // var
+ // name a$b$c
+ // NODE
+
+ // Remove the rvalue (NODE).
+ parent.removeChild(rvalue);
+ nameNode.addChildToFront(rvalue);
+
+ Node varNode = new Node(Token.VAR, nameNode);
+ greatGramps.replaceChild(gramps, varNode);
+ } else {
+ // This must be a complex assignment.
+ Preconditions.checkNotNull(ref.getTwin());
+
+ // BEFORE:
+ // ... (x.y = 3);
+ //
+ // AFTER:
+ // var x$y;
+ // ... (x$y = 3);
+
+ Node current = gramps;
+ Node currentParent = gramps.getParent();
+ for (; currentParent.getType() != Token.SCRIPT &&
+ currentParent.getType() != Token.BLOCK;
+ current = currentParent,
+ currentParent = currentParent.getParent()) {}
+
+ // Create a stub variable declaration right
+ // before the current statement.
+ Node stubVar = new Node(Token.VAR, nameNode.cloneTree())
+ .copyInformationFrom(nameNode);
+ currentParent.addChildBefore(stubVar, current);
+
+ parent.replaceChild(ref.node, nameNode);
+ }
+
+ compiler.reportCodeChange();
+ }
+
+// Test Case
+[/INST]
+ public void testAddPropertyToChildOfUncollapsibleFunctionInLocalScope() {
+ testSame(
+ ""function a() {} a.b = {x: 0}; var c = a;"" +
+ ""(function() {a.b.y = 0;})(); a.b.y;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean canCollapseUnannotatedChildNames() {
+ if (type == Type.OTHER || globalSets != 1 || localSets != 0) {
+ return false;
+ }
+
+ // Don't try to collapse if the one global set is a twin reference.
+ // We could theoretically handle this case in CollapseProperties, but
+ // it's probably not worth the effort.
+ Preconditions.checkNotNull(declaration);
+ if (declaration.getTwin() != null) {
+ return false;
+ }
+
+ if (isClassOrEnum) {
+ return true;
+ }
+
+ // If this is a key of an aliased object literal, then it will be aliased
+ // later. So we won't be able to collapse its properties.
+ if (parent != null && parent.shouldKeepKeys()) {
+ return false;
+ }
+
+ // If this is aliased, then its properties can't be collapsed either.
+ if (type != Type.FUNCTION && aliasingGets > 0) {
+ return false;
+ }
+
+ return (parent == null || parent.canCollapseUnannotatedChildNames());
+ }
+
+// Test Case
+[/INST]
+ public void testAddPropertyToChildOfUncollapsibleFunctionInLocalScope() {
+ testSame(
+ ""function a() {} a.b = {x: 0}; var c = a;"" +
+ ""(function() {a.b.y = 0;})(); a.b.y;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private String normalizeSourceName(String filename) {
+ // The DOS command shell will normalize ""/"" to ""\"", so we have to
+ // wrestle it back.
+
+ if (filename.indexOf(filenamePrefix) == 0) {
+ filename = filename.substring(filenamePrefix.length());
+ }
+
+ return filename;
+ }
+
+// Test Case
+[/INST]
+ public void testGuessModuleName() {
+ ProcessCommonJSModules pass = new ProcessCommonJSModules(null, ""foo"");
+ assertEquals(""module$baz"",
+ pass.guessCJSModuleName(""foo/baz.js""));
+ assertEquals(""module$baz"",
+ pass.guessCJSModuleName(""foo\\baz.js""));
+ assertEquals(""module$bar$baz"",
+ pass.guessCJSModuleName(""foo\\bar\\baz.js""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitScript(NodeTraversal t, Node script) {
+ Preconditions.checkArgument(scriptNodeCount == 1,
+ ""ProcessCommonJSModules supports only one invocation per "" +
+ ""CompilerInput / script node"");
+ String moduleName = guessCJSModuleName(normalizeSourceName(script.getSourceFileName()));
+ script.addChildToFront(IR.var(IR.name(moduleName), IR.objectlit())
+ .copyInformationFromForTree(script));
+ if (reportDependencies) {
+ CompilerInput ci = t.getInput();
+ ci.addProvide(moduleName);
+ JSModule m = new JSModule(moduleName);
+ m.addAndOverrideModule(ci);
+ module = m;
+ }
+ script.addChildToFront(IR.exprResult(
+ IR.call(IR.getprop(IR.name(""goog""), IR.string(""provide"")),
+ IR.string(moduleName))).copyInformationFromForTree(script));
+
+ emitOptionalModuleExportsOverride(script, moduleName);
+
+ // Rename vars to not conflict in global scope.
+ NodeTraversal.traverse(compiler, script, new SuffixVarsCallback(
+ moduleName));
+
+ compiler.reportCodeChange();
+ }
+
+// Test Case
+[/INST]
+ public void testGuessModuleName() {
+ ProcessCommonJSModules pass = new ProcessCommonJSModules(null, ""foo"");
+ assertEquals(""module$baz"",
+ pass.guessCJSModuleName(""foo/baz.js""));
+ assertEquals(""module$baz"",
+ pass.guessCJSModuleName(""foo\\baz.js""));
+ assertEquals(""module$bar$baz"",
+ pass.guessCJSModuleName(""foo\\bar\\baz.js""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean apply(JSType type) {
+ // TODO(user): Doing an instanceof check here is too
+ // restrictive as (Date,Error) is, for instance, an object type
+ // even though its implementation is a UnionType. Would need to
+ // create interfaces JSType, ObjectType, FunctionType etc and have
+ // separate implementation instead of the class hierarchy, so that
+ // union types can also be object types, etc.
+ if (!type.isSubtype(
+ typeRegistry.getNativeType(OBJECT_TYPE))) {
+ reportWarning(THIS_TYPE_NON_OBJECT, type.toString());
+ return false;
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testBackwardsTypedefUse8() throws Exception {
+ // Tehnically, this isn't quite right, because the JS runtime
+ // will coerce null -> the global object. But we'll punt on that for now.
+ testTypes(
+ ""/** @param {!Array} x */ function g(x) {}"" +
+ ""/** @this {goog.MyTypedef} */ function f() { g(this); }"" +
+ ""var goog = {};"" +
+ ""/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ JSType resolveInternal(ErrorReporter t, StaticScope scope) {
+ setResolvedTypeInternal(this);
+
+ call = (ArrowType) safeResolve(call, t, scope);
+ prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope);
+
+ // Warning about typeOfThis if it doesn't resolve to an ObjectType
+ // is handled further upstream.
+ //
+ // TODO(nicksantos): Handle this correctly if we have a UnionType.
+ //
+ // TODO(nicksantos): In ES3, the runtime coerces ""null"" to the global
+ // activation object. In ES5, it leaves it as null. Just punt on this
+ // issue for now by coercing out null. This is complicated by the
+ // fact that when most people write @this {Foo}, they really don't
+ // mean ""nullable Foo"". For certain tags (like @extends) we de-nullify
+ // the name for them.
+ JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope);
+ if (maybeTypeOfThis instanceof ObjectType) {
+ typeOfThis = (ObjectType) maybeTypeOfThis;
+ }
+
+ boolean changed = false;
+ ImmutableList.Builder resolvedInterfaces =
+ ImmutableList.builder();
+ for (ObjectType iface : implementedInterfaces) {
+ ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope);
+ resolvedInterfaces.add(resolvedIface);
+ changed |= (resolvedIface != iface);
+ }
+ if (changed) {
+ implementedInterfaces = resolvedInterfaces.build();
+ }
+
+ if (subTypes != null) {
+ for (int i = 0; i < subTypes.size(); i++) {
+ subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope));
+ }
+ }
+
+ return super.resolveInternal(t, scope);
+ }
+
+// Test Case
+[/INST]
+ public void testBackwardsTypedefUse8() throws Exception {
+ // Tehnically, this isn't quite right, because the JS runtime
+ // will coerce null -> the global object. But we'll punt on that for now.
+ testTypes(
+ ""/** @param {!Array} x */ function g(x) {}"" +
+ ""/** @this {goog.MyTypedef} */ function f() { g(this); }"" +
+ ""var goog = {};"" +
+ ""/** @typedef {(Array|null|undefined)} */ goog.MyTypedef;"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
+
+ if (n.getType() == Token.FUNCTION) {
+ // Don't traverse functions that are constructors or have the @this
+ // or @override annotation.
+ JSDocInfo jsDoc = getFunctionJsDocInfo(n);
+ if (jsDoc != null &&
+ (jsDoc.isConstructor() ||
+ jsDoc.isInterface() ||
+ jsDoc.hasThisType() ||
+ jsDoc.isOverride())) {
+ return false;
+ }
+
+ // Don't traverse functions unless they would normally
+ // be able to have a @this annotation associated with them. e.g.,
+ // var a = function() { }; // or
+ // function a() {} // or
+ // a.x = function() {}; // or
+ // var a = {x: function() {}};
+ int pType = parent.getType();
+ if (!(pType == Token.BLOCK ||
+ pType == Token.SCRIPT ||
+ pType == Token.NAME ||
+ pType == Token.ASSIGN ||
+
+ // object literal keys
+ pType == Token.STRING ||
+ pType == Token.NUMBER)) {
+ return false;
+ }
+
+ // Don't traverse functions that are getting lent to a prototype.
+ }
+
+ if (parent != null && parent.getType() == Token.ASSIGN) {
+ Node lhs = parent.getFirstChild();
+ Node rhs = lhs.getNext();
+
+ if (n == lhs) {
+ // Always traverse the left side of the assignment. To handle
+ // nested assignments properly (e.g., (a = this).property = c;),
+ // assignLhsChild should not be overridden.
+ if (assignLhsChild == null) {
+ assignLhsChild = lhs;
+ }
+ } else {
+ // Only traverse the right side if it's not an assignment to a prototype
+ // property or subproperty.
+ if (NodeUtil.isGet(lhs)) {
+ if (lhs.getType() == Token.GETPROP &&
+ lhs.getLastChild().getString().equals(""prototype"")) {
+ return false;
+ }
+ Node llhs = lhs.getFirstChild();
+ if (llhs.getType() == Token.GETPROP &&
+ llhs.getLastChild().getString().equals(""prototype"")) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testLendsAnnotation3() {
+ testSame(""/** @constructor */ function F() {}"" +
+ ""dojo.declare(F, /** @lends {F.prototype} */ ("" +
+ "" {foo: function() { return this.foo; }}));"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void replace() {
+ if (firstNode == null) {
+ // Don't touch the base case ('goog').
+ replacementNode = candidateDefinition;
+ return;
+ }
+
+ // Handle the case where there is a duplicate definition for an explicitly
+ // provided symbol.
+ if (candidateDefinition != null && explicitNode != null) {
+ explicitNode.detachFromParent();
+ compiler.reportCodeChange();
+
+ // Does this need a VAR keyword?
+ replacementNode = candidateDefinition;
+ if (NodeUtil.isExpressionNode(candidateDefinition)) {
+ candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true);
+ Node assignNode = candidateDefinition.getFirstChild();
+ Node nameNode = assignNode.getFirstChild();
+ if (nameNode.getType() == Token.NAME) {
+ // Need to convert this assign to a var declaration.
+ Node valueNode = nameNode.getNext();
+ assignNode.removeChild(nameNode);
+ assignNode.removeChild(valueNode);
+ nameNode.addChildToFront(valueNode);
+ Node varNode = new Node(Token.VAR, nameNode);
+ varNode.copyInformationFrom(candidateDefinition);
+ candidateDefinition.getParent().replaceChild(
+ candidateDefinition, varNode);
+ nameNode.setJSDocInfo(assignNode.getJSDocInfo());
+ compiler.reportCodeChange();
+ replacementNode = varNode;
+ }
+ }
+ } else {
+ // Handle the case where there's not a duplicate definition.
+ replacementNode = createDeclarationNode();
+ if (firstModule == minimumModule) {
+ firstNode.getParent().addChildBefore(replacementNode, firstNode);
+ } else {
+ // In this case, the name was implicitly provided by two independent
+ // modules. We need to move this code up to a common module.
+ int indexOfDot = namespace.indexOf('.');
+ if (indexOfDot == -1) {
+ // Any old place is fine.
+ compiler.getNodeForCodeInsertion(minimumModule)
+ .addChildToBack(replacementNode);
+ } else {
+ // Add it after the parent namespace.
+ ProvidedName parentName =
+ providedNames.get(namespace.substring(0, indexOfDot));
+ Preconditions.checkNotNull(parentName);
+ Preconditions.checkNotNull(parentName.replacementNode);
+ parentName.replacementNode.getParent().addChildAfter(
+ replacementNode, parentName.replacementNode);
+ }
+ }
+ if (explicitNode != null) {
+ explicitNode.detachFromParent();
+ }
+ compiler.reportCodeChange();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testProvideInIndependentModules4() {
+ // Regression test for bug 261:
+ // http://code.google.com/p/closure-compiler/issues/detail?id=261
+ test(
+ createModuleStar(
+ ""goog.provide('apps');"",
+ ""goog.provide('apps.foo.bar.B');"",
+ ""goog.provide('apps.foo.bar.C');""),
+ new String[] {
+ ""var apps = {};apps.foo = {};apps.foo.bar = {}"",
+ ""apps.foo.bar.B = {};"",
+ ""apps.foo.bar.C = {};"",
+ });
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static boolean isValidDefineValue(Node val, Set defines) {
+ switch (val.getType()) {
+ case Token.STRING:
+ case Token.NUMBER:
+ case Token.TRUE:
+ case Token.FALSE:
+ return true;
+
+ // Binary operators are only valid if both children are valid.
+ case Token.BITAND:
+ case Token.BITNOT:
+ case Token.BITOR:
+ case Token.BITXOR:
+
+ // Uniary operators are valid if the child is valid.
+ case Token.NOT:
+ case Token.NEG:
+ return isValidDefineValue(val.getFirstChild(), defines);
+
+ // Names are valid if and only if they are defines themselves.
+ case Token.NAME:
+ case Token.GETPROP:
+ if (val.isQualifiedName()) {
+ return defines.contains(val.getQualifiedName());
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testValidDefine() {
+ assertTrue(testValidDefineValue(""1""));
+ assertTrue(testValidDefineValue(""-3""));
+ assertTrue(testValidDefineValue(""true""));
+ assertTrue(testValidDefineValue(""false""));
+ assertTrue(testValidDefineValue(""'foo'""));
+
+ assertFalse(testValidDefineValue(""x""));
+ assertFalse(testValidDefineValue(""null""));
+ assertFalse(testValidDefineValue(""undefined""));
+ assertFalse(testValidDefineValue(""NaN""));
+
+ assertTrue(testValidDefineValue(""!true""));
+ assertTrue(testValidDefineValue(""-true""));
+ assertTrue(testValidDefineValue(""1 & 8""));
+ assertTrue(testValidDefineValue(""1 + 8""));
+ assertTrue(testValidDefineValue(""'a' + 'b'""));
+
+ assertFalse(testValidDefineValue(""1 & foo""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void defineSlot(Node n, Node parent, JSType type, boolean inferred) {
+ Preconditions.checkArgument(inferred || type != null);
+
+ // Only allow declarations of NAMEs and qualfied names.
+ boolean shouldDeclareOnGlobalThis = false;
+ if (n.getType() == Token.NAME) {
+ Preconditions.checkArgument(
+ parent.getType() == Token.FUNCTION ||
+ parent.getType() == Token.VAR ||
+ parent.getType() == Token.LP ||
+ parent.getType() == Token.CATCH);
+ shouldDeclareOnGlobalThis = scope.isGlobal() &&
+ (parent.getType() == Token.VAR ||
+ parent.getType() == Token.FUNCTION);
+ } else {
+ Preconditions.checkArgument(
+ n.getType() == Token.GETPROP &&
+ (parent.getType() == Token.ASSIGN ||
+ parent.getType() == Token.EXPR_RESULT));
+ }
+ String variableName = n.getQualifiedName();
+ Preconditions.checkArgument(!variableName.isEmpty());
+
+ // If n is a property, then we should really declare it in the
+ // scope where the root object appears. This helps out people
+ // who declare ""global"" names in an anonymous namespace.
+ Scope scopeToDeclareIn = scope;
+
+ // don't try to declare in the global scope if there's
+ // already a symbol there with this name.
+
+ // declared in closest scope?
+ if (scopeToDeclareIn.isDeclared(variableName, false)) {
+ Var oldVar = scopeToDeclareIn.getVar(variableName);
+ validator.expectUndeclaredVariable(
+ sourceName, n, parent, oldVar, variableName, type);
+ } else {
+ if (!inferred) {
+ setDeferredType(n, type);
+ }
+ CompilerInput input = compiler.getInput(sourceName);
+ scopeToDeclareIn.declare(variableName, n, type, input, inferred);
+
+ if (shouldDeclareOnGlobalThis) {
+ ObjectType globalThis =
+ typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS);
+ boolean isExtern = input.isExtern();
+ if (inferred) {
+ globalThis.defineInferredProperty(variableName,
+ type == null ?
+ getNativeType(JSTypeNative.NO_TYPE) :
+ type,
+ isExtern);
+ } else {
+ globalThis.defineDeclaredProperty(variableName, type, isExtern);
+ }
+ }
+
+ // If we're in the global scope, also declare var.prototype
+ // in the scope chain.
+ if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) {
+ FunctionType fnType = (FunctionType) type;
+ if (fnType.isConstructor() || fnType.isInterface()) {
+ FunctionType superClassCtor = fnType.getSuperClassConstructor();
+ scopeToDeclareIn.declare(variableName + "".prototype"", n,
+ fnType.getPrototype(), compiler.getInput(sourceName),
+ /* declared iff there's an explicit supertype */
+ superClassCtor == null ||
+ superClassCtor.getInstanceType().equals(
+ getNativeType(OBJECT_TYPE)));
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testQualifiedNameInference5() throws Exception {
+ testTypes(
+ ""var ns = {}; "" +
+ ""(function() { "" +
+ "" /** @param {number} x */ ns.foo = function(x) {}; })();"" +
+ ""(function() { ns.foo(true); })();"",
+ ""actual parameter 1 of ns.foo does not match formal parameter\n"" +
+ ""found : boolean\n"" +
+ ""required: number"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void visitParameterList(NodeTraversal t, Node call,
+ FunctionType functionType) {
+ Iterator arguments = call.children().iterator();
+ arguments.next(); // skip the function name
+
+ Iterator parameters = functionType.getParameters().iterator();
+ int ordinal = 0;
+ Node parameter = null;
+ Node argument = null;
+ while (arguments.hasNext() &&
+ parameters.hasNext()) {
+ // If there are no parameters left in the list, then the while loop
+ // above implies that this must be a var_args function.
+ parameter = parameters.next();
+ argument = arguments.next();
+ ordinal++;
+
+ validator.expectArgumentMatchesParameter(t, argument,
+ getJSType(argument), getJSType(parameter), call, ordinal);
+ }
+
+ int numArgs = call.getChildCount() - 1;
+ int minArgs = functionType.getMinArguments();
+ int maxArgs = functionType.getMaxArguments();
+ if (minArgs > numArgs || maxArgs < numArgs) {
+ report(t, call, WRONG_ARGUMENT_COUNT,
+ validator.getReadableJSTypeName(call.getFirstChild(), false),
+ String.valueOf(numArgs), String.valueOf(minArgs),
+ maxArgs != Integer.MAX_VALUE ?
+ "" and no more than "" + maxArgs + "" argument(s)"" : """");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testFunctionArguments16() throws Exception {
+ testTypes(
+ ""/** @param {...number} var_args */"" +
+ ""function g(var_args) {} g(1, true);"",
+ ""actual parameter 2 of g does not match formal parameter\n"" +
+ ""found : boolean\n"" +
+ ""required: (number|undefined)"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Node tryFoldShift(Node n, Node left, Node right) {
+ if (left.getType() == Token.NUMBER &&
+ right.getType() == Token.NUMBER) {
+
+ double result;
+ double lval = left.getDouble();
+ double rval = right.getDouble();
+
+ // check ranges. We do not do anything that would clip the double to
+ // a 32-bit range, since the user likely does not intend that.
+ if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {
+ error(BITWISE_OPERAND_OUT_OF_RANGE, left);
+ return n;
+ }
+
+ // only the lower 5 bits are used when shifting, so don't do anything
+ // if the shift amount is outside [0,32)
+ if (!(rval >= 0 && rval < 32)) {
+ error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);
+ return n;
+ }
+
+ // Convert the numbers to ints
+ int lvalInt = (int) lval;
+ if (lvalInt != lval) {
+ error(FRACTIONAL_BITWISE_OPERAND, left);
+ return n;
+ }
+
+ int rvalInt = (int) rval;
+ if (rvalInt != rval) {
+ error(FRACTIONAL_BITWISE_OPERAND, right);
+ return n;
+ }
+
+ switch (n.getType()) {
+ case Token.LSH:
+ result = lvalInt << rvalInt;
+ break;
+ case Token.RSH:
+ result = lvalInt >> rvalInt;
+ break;
+ case Token.URSH:
+ // JavaScript handles zero shifts on signed numbers differently than
+ // Java as an Java int can not represent the unsigned 32-bit number
+ // where JavaScript can so use a long here.
+ result = lvalInt >>> rvalInt;
+ break;
+ default:
+ throw new AssertionError(""Unknown shift operator: "" +
+ Node.tokenToName(n.getType()));
+ }
+
+ Node newNumber = Node.newNumber(result);
+ n.getParent().replaceChild(n, newNumber);
+ reportCodeChange();
+
+ return newNumber;
+ }
+
+ return n;
+ }
+
+// Test Case
+[/INST]
+ public void testFoldBitShifts() {
+ fold(""x = 1 << 0"", ""x = 1"");
+ fold(""x = -1 << 0"", ""x = -1"");
+ fold(""x = 1 << 1"", ""x = 2"");
+ fold(""x = 3 << 1"", ""x = 6"");
+ fold(""x = 1 << 8"", ""x = 256"");
+
+ fold(""x = 1 >> 0"", ""x = 1"");
+ fold(""x = -1 >> 0"", ""x = -1"");
+ fold(""x = 1 >> 1"", ""x = 0"");
+ fold(""x = 2 >> 1"", ""x = 1"");
+ fold(""x = 5 >> 1"", ""x = 2"");
+ fold(""x = 127 >> 3"", ""x = 15"");
+ fold(""x = 3 >> 1"", ""x = 1"");
+ fold(""x = 3 >> 2"", ""x = 0"");
+ fold(""x = 10 >> 1"", ""x = 5"");
+ fold(""x = 10 >> 2"", ""x = 2"");
+ fold(""x = 10 >> 5"", ""x = 0"");
+
+ fold(""x = 10 >>> 1"", ""x = 5"");
+ fold(""x = 10 >>> 2"", ""x = 2"");
+ fold(""x = 10 >>> 5"", ""x = 0"");
+ fold(""x = -1 >>> 1"", ""x = 2147483647""); // 0x7fffffff
+ fold(""x = -1 >>> 0"", ""x = 4294967295""); // 0xffffffff
+ fold(""x = -2 >>> 0"", ""x = 4294967294""); // 0xfffffffe
+
+ fold(""3000000000 << 1"", ""3000000000<<1"",
+ PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
+ fold(""1 << 32"", ""1<<32"",
+ PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
+ fold(""1 << -1"", ""1<<32"",
+ PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
+ fold(""3000000000 >> 1"", ""3000000000>>1"",
+ PeepholeFoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
+ fold(""1 >> 32"", ""1>>32"",
+ PeepholeFoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
+ fold(""1.5 << 0"", ""1.5<<0"",
+ PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
+ fold(""1 << .5"", ""1.5<<0"",
+ PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
+ fold(""1.5 >>> 0"", ""1.5>>>0"",
+ PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
+ fold(""1 >>> .5"", ""1.5>>>0"",
+ PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
+ fold(""1.5 >> 0"", ""1.5>>0"",
+ PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
+ fold(""1 >> .5"", ""1.5>>0"",
+ PeepholeFoldConstants.FRACTIONAL_BITWISE_OPERAND);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ boolean isAssignedOnceInLifetime() {
+ Reference ref = getOneAndOnlyAssignment();
+ if (ref == null) {
+ return false;
+ }
+
+ // Make sure this assignment is not in a loop.
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testNoInlineAliasesInLoop() {
+ testSame(
+ ""function f() { "" +
+ "" for (var i = 0; i < 5; i++) {"" +
+ "" var x = extern();"" +
+ "" (function() {"" +
+ "" var y = x; window.setTimeout(function() { extern(y); }, 0);"" +
+ "" })();"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ BasicBlock(BasicBlock parent, Node root) {
+ this.parent = parent;
+
+ // only named functions may be hoisted.
+ this.isHoisted = NodeUtil.isHoistedFunctionDeclaration(root);
+
+
+ }
+
+// Test Case
+[/INST]
+ public void testNoInlineAliasesInLoop() {
+ testSame(
+ ""function f() { "" +
+ "" for (var i = 0; i < 5; i++) {"" +
+ "" var x = extern();"" +
+ "" (function() {"" +
+ "" var y = x; window.setTimeout(function() { extern(y); }, 0);"" +
+ "" })();"" +
+ "" }"" +
+ ""}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
+
+ if (n.getType() == Token.FUNCTION) {
+ // Don't traverse functions that are constructors or have the @this
+ // or @override annotation.
+ JSDocInfo jsDoc = getFunctionJsDocInfo(n);
+ if (jsDoc != null &&
+ (jsDoc.isConstructor() ||
+ jsDoc.hasThisType() ||
+ jsDoc.isOverride())) {
+ return false;
+ }
+
+ // Don't traverse functions unless they would normally
+ // be able to have a @this annotation associated with them. e.g.,
+ // var a = function() { }; // or
+ // function a() {} // or
+ // a.x = function() {};
+ int pType = parent.getType();
+ if (!(pType == Token.BLOCK ||
+ pType == Token.SCRIPT ||
+ pType == Token.NAME ||
+ pType == Token.ASSIGN)) {
+ return false;
+ }
+ }
+
+ if (parent != null && parent.getType() == Token.ASSIGN) {
+ Node lhs = parent.getFirstChild();
+ Node rhs = lhs.getNext();
+
+ if (n == lhs) {
+ // Always traverse the left side of the assignment. To handle
+ // nested assignments properly (e.g., (a = this).property = c;),
+ // assignLhsChild should not be overridden.
+ if (assignLhsChild == null) {
+ assignLhsChild = lhs;
+ }
+ } else {
+ // Only traverse the right side if it's not an assignment to a prototype
+ // property or subproperty.
+ if (lhs.getType() == Token.GETPROP &&
+ lhs.getLastChild().getString().equals(""prototype"")) {
+ return false;
+ }
+ if (lhs.getQualifiedName() != null && lhs.getQualifiedName().contains("".prototype."")) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testPropertyOfMethod() {
+ testFailure(""a.protoype.b = {}; "" +
+ ""a.prototype.b.c = function() { this.foo = 3; };"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static String clean(String str) {
+ if (str == null || str.length() == 0) {
+ return str;
+ }
+ int len = str.length();
+ char[] chars = new char[len];
+ int count = 0;
+ for (int i = 0; i < len; i++) {
+ if (Character.isLetter(str.charAt(i))) {
+ chars[count++] = str.charAt(i);
+ }
+ }
+ if (count == len) {
+ return str.toUpperCase();
+ }
+ return new String(chars, 0, count).toUpperCase(java.util.Locale.ENGLISH);
+ }
+
+// Test Case
+[/INST]
+ public void testLocaleIndependence() throws Exception {
+ StringEncoder encoder = makeEncoder();
+
+ String[] data = { ""I"", ""i"", };
+
+ Locale orig = Locale.getDefault();
+ Locale[] locales = { Locale.ENGLISH, new Locale(""tr""), Locale.getDefault() };
+
+ try {
+ for (int i = 0; i < data.length; i++) {
+ String ref = null;
+ for (int j = 0; j < locales.length; j++) {
+ Locale.setDefault(locales[j]);
+ if (j <= 0) {
+ ref = encoder.encode(data[i]);
+ } else {
+ String cur = null;
+ try {
+ cur = encoder.encode(data[i]);
+ } catch (Exception e) {
+ fail(Locale.getDefault().toString() + "": "" + e.getMessage());
+ }
+ assertEquals(Locale.getDefault().toString() + "": "", ref, cur);
+ }
+ }
+ }
+ } finally {
+ Locale.setDefault(orig);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String caverphone(String txt) {
+ // NOTE: Version 1.0 of Caverphone is easily derivable from this code
+ // by commenting out the 2.0 lines and adding in the 1.0 lines
+
+ if( txt == null || txt.length() == 0 ) {
+ return ""1111111111"";
+ }
+
+ // 1. Convert to lowercase
+ txt = txt.toLowerCase();
+
+ // 2. Remove anything not A-Z
+ txt = txt.replaceAll(""[^a-z]"", """");
+
+ // 2.5. Remove final e
+ txt = txt.replaceAll(""e$"", """"); // 2.0 only
+
+ // 3. Handle various start options
+ txt = txt.replaceAll(""^cough"", ""cou2f"");
+ txt = txt.replaceAll(""^rough"", ""rou2f"");
+ txt = txt.replaceAll(""^tough"", ""tou2f"");
+ txt = txt.replaceAll(""^enough"", ""enou2f""); // 2.0 only
+ txt = txt.replaceAll(""^trough"", ""trou2f""); // 2.0 only - note the spec says ^enough here again, c+p error I assume
+ txt = txt.replaceAll(""^gn"", ""2n"");
+ txt = txt.replaceAll(""^mb"", ""m2"");
+
+ // 4. Handle replacements
+ txt = txt.replaceAll(""cq"", ""2q"");
+ txt = txt.replaceAll(""ci"", ""si"");
+ txt = txt.replaceAll(""ce"", ""se"");
+ txt = txt.replaceAll(""cy"", ""sy"");
+ txt = txt.replaceAll(""tch"", ""2ch"");
+ txt = txt.replaceAll(""c"", ""k"");
+ txt = txt.replaceAll(""q"", ""k"");
+ txt = txt.replaceAll(""x"", ""k"");
+ txt = txt.replaceAll(""v"", ""f"");
+ txt = txt.replaceAll(""dg"", ""2g"");
+ txt = txt.replaceAll(""tio"", ""sio"");
+ txt = txt.replaceAll(""tia"", ""sia"");
+ txt = txt.replaceAll(""d"", ""t"");
+ txt = txt.replaceAll(""ph"", ""fh"");
+ txt = txt.replaceAll(""b"", ""p"");
+ txt = txt.replaceAll(""sh"", ""s2"");
+ txt = txt.replaceAll(""z"", ""s"");
+ txt = txt.replaceAll(""^[aeiou]"", ""A"");
+ txt = txt.replaceAll(""[aeiou]"", ""3"");
+ txt = txt.replaceAll(""j"", ""y""); // 2.0 only
+ txt = txt.replaceAll(""^y3"", ""Y3""); // 2.0 only
+ txt = txt.replaceAll(""^y"", ""A""); // 2.0 only
+ txt = txt.replaceAll(""y"", ""3""); // 2.0 only
+ txt = txt.replaceAll(""3gh3"", ""3kh3"");
+ txt = txt.replaceAll(""gh"", ""22"");
+ txt = txt.replaceAll(""g"", ""k"");
+ txt = txt.replaceAll(""s+"", ""S"");
+ txt = txt.replaceAll(""t+"", ""T"");
+ txt = txt.replaceAll(""p+"", ""P"");
+ txt = txt.replaceAll(""k+"", ""K"");
+ txt = txt.replaceAll(""f+"", ""F"");
+ txt = txt.replaceAll(""m+"", ""M"");
+ txt = txt.replaceAll(""n+"", ""N"");
+ txt = txt.replaceAll(""w3"", ""W3"");
+ //txt = txt.replaceAll(""wy"", ""Wy""); // 1.0 only
+ txt = txt.replaceAll(""wh3"", ""Wh3"");
+ txt = txt.replaceAll(""w$"", ""3""); // 2.0 only
+ //txt = txt.replaceAll(""why"", ""Why""); // 1.0 only
+ txt = txt.replaceAll(""w"", ""2"");
+ txt = txt.replaceAll(""^h"", ""A"");
+ txt = txt.replaceAll(""h"", ""2"");
+ txt = txt.replaceAll(""r3"", ""R3"");
+ txt = txt.replaceAll(""r$"", ""3""); // 2.0 only
+ //txt = txt.replaceAll(""ry"", ""Ry""); // 1.0 only
+ txt = txt.replaceAll(""r"", ""2"");
+ txt = txt.replaceAll(""l3"", ""L3"");
+ txt = txt.replaceAll(""l$"", ""3""); // 2.0 only
+ //txt = txt.replaceAll(""ly"", ""Ly""); // 1.0 only
+ txt = txt.replaceAll(""l"", ""2"");
+ //txt = txt.replaceAll(""j"", ""y""); // 1.0 only
+ //txt = txt.replaceAll(""y3"", ""Y3""); // 1.0 only
+ //txt = txt.replaceAll(""y"", ""2""); // 1.0 only
+
+ // 5. Handle removals
+ txt = txt.replaceAll(""2"", """");
+ txt = txt.replaceAll(""3$"", ""A""); // 2.0 only
+ txt = txt.replaceAll(""3"", """");
+
+ // 6. put ten 1s on the end
+ txt = txt + ""111111"" + ""1111""; // 1.0 only has 6 1s
+
+ // 7. take the first six characters as the code
+ return txt.substring(0, 10); // 1.0 truncates to 6
+ }
+
+// Test Case
+[/INST]
+ public void testLocaleIndependence() throws Exception {
+ StringEncoder encoder = makeEncoder();
+
+ String[] data = { ""I"", ""i"", };
+
+ Locale orig = Locale.getDefault();
+ Locale[] locales = { Locale.ENGLISH, new Locale(""tr""), Locale.getDefault() };
+
+ try {
+ for (int i = 0; i < data.length; i++) {
+ String ref = null;
+ for (int j = 0; j < locales.length; j++) {
+ Locale.setDefault(locales[j]);
+ if (j <= 0) {
+ ref = encoder.encode(data[i]);
+ } else {
+ String cur = null;
+ try {
+ cur = encoder.encode(data[i]);
+ } catch (Exception e) {
+ fail(Locale.getDefault().toString() + "": "" + e.getMessage());
+ }
+ assertEquals(Locale.getDefault().toString() + "": "", ref, cur);
+ }
+ }
+ }
+ } finally {
+ Locale.setDefault(orig);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String metaphone(String txt) {
+ boolean hard = false ;
+ if ((txt == null) || (txt.length() == 0)) {
+ return """" ;
+ }
+ // single character is itself
+ if (txt.length() == 1) {
+ return txt.toUpperCase() ;
+ }
+
+ char[] inwd = txt.toUpperCase(java.util.Locale.ENGLISH).toCharArray() ;
+
+ StringBuffer local = new StringBuffer(40); // manipulate
+ StringBuffer code = new StringBuffer(10) ; // output
+ // handle initial 2 characters exceptions
+ switch(inwd[0]) {
+ case 'K' :
+ case 'G' :
+ case 'P' : /* looking for KN, etc*/
+ if (inwd[1] == 'N') {
+ local.append(inwd, 1, inwd.length - 1);
+ } else {
+ local.append(inwd);
+ }
+ break;
+ case 'A': /* looking for AE */
+ if (inwd[1] == 'E') {
+ local.append(inwd, 1, inwd.length - 1);
+ } else {
+ local.append(inwd);
+ }
+ break;
+ case 'W' : /* looking for WR or WH */
+ if (inwd[1] == 'R') { // WR -> R
+ local.append(inwd, 1, inwd.length - 1);
+ break ;
+ }
+ if (inwd[1] == 'H') {
+ local.append(inwd, 1, inwd.length - 1);
+ local.setCharAt(0, 'W'); // WH -> W
+ } else {
+ local.append(inwd);
+ }
+ break;
+ case 'X' : /* initial X becomes S */
+ inwd[0] = 'S';
+ local.append(inwd);
+ break ;
+ default :
+ local.append(inwd);
+ } // now local has working string with initials fixed
+
+ int wdsz = local.length();
+ int n = 0 ;
+
+ while ((code.length() < this.getMaxCodeLen()) &&
+ (n < wdsz) ) { // max code size of 4 works well
+ char symb = local.charAt(n) ;
+ // remove duplicate letters except C
+ if ((symb != 'C') && (isPreviousChar( local, n, symb )) ) {
+ n++ ;
+ } else { // not dup
+ switch(symb) {
+ case 'A' : case 'E' : case 'I' : case 'O' : case 'U' :
+ if (n == 0) {
+ code.append(symb);
+ }
+ break ; // only use vowel if leading char
+ case 'B' :
+ if ( isPreviousChar(local, n, 'M') &&
+ isLastChar(wdsz, n) ) { // B is silent if word ends in MB
+ break;
+ }
+ code.append(symb);
+ break;
+ case 'C' : // lots of C special cases
+ /* discard if SCI, SCE or SCY */
+ if ( isPreviousChar(local, n, 'S') &&
+ !isLastChar(wdsz, n) &&
+ (FRONTV.indexOf(local.charAt(n + 1)) >= 0) ) {
+ break;
+ }
+ if (regionMatch(local, n, ""CIA"")) { // ""CIA"" -> X
+ code.append('X');
+ break;
+ }
+ if (!isLastChar(wdsz, n) &&
+ (FRONTV.indexOf(local.charAt(n + 1)) >= 0)) {
+ code.append('S');
+ break; // CI,CE,CY -> S
+ }
+ if (isPreviousChar(local, n, 'S') &&
+ isNextChar(local, n, 'H') ) { // SCH->sk
+ code.append('K') ;
+ break ;
+ }
+ if (isNextChar(local, n, 'H')) { // detect CH
+ if ((n == 0) &&
+ (wdsz >= 3) &&
+ isVowel(local,2) ) { // CH consonant -> K consonant
+ code.append('K');
+ } else {
+ code.append('X'); // CHvowel -> X
+ }
+ } else {
+ code.append('K');
+ }
+ break ;
+ case 'D' :
+ if (!isLastChar(wdsz, n + 1) &&
+ isNextChar(local, n, 'G') &&
+ (FRONTV.indexOf(local.charAt(n + 2)) >= 0)) { // DGE DGI DGY -> J
+ code.append('J'); n += 2 ;
+ } else {
+ code.append('T');
+ }
+ break ;
+ case 'G' : // GH silent at end or before consonant
+ if (isLastChar(wdsz, n + 1) &&
+ isNextChar(local, n, 'H')) {
+ break;
+ }
+ if (!isLastChar(wdsz, n + 1) &&
+ isNextChar(local,n,'H') &&
+ !isVowel(local,n+2)) {
+ break;
+ }
+ if ((n > 0) &&
+ ( regionMatch(local, n, ""GN"") ||
+ regionMatch(local, n, ""GNED"") ) ) {
+ break; // silent G
+ }
+ if (isPreviousChar(local, n, 'G')) {
+ hard = true ;
+ } else {
+ hard = false ;
+ }
+ if (!isLastChar(wdsz, n) &&
+ (FRONTV.indexOf(local.charAt(n + 1)) >= 0) &&
+ (!hard)) {
+ code.append('J');
+ } else {
+ code.append('K');
+ }
+ break ;
+ case 'H':
+ if (isLastChar(wdsz, n)) {
+ break ; // terminal H
+ }
+ if ((n > 0) &&
+ (VARSON.indexOf(local.charAt(n - 1)) >= 0)) {
+ break;
+ }
+ if (isVowel(local,n+1)) {
+ code.append('H'); // Hvowel
+ }
+ break;
+ case 'F':
+ case 'J' :
+ case 'L' :
+ case 'M':
+ case 'N' :
+ case 'R' :
+ code.append(symb);
+ break;
+ case 'K' :
+ if (n > 0) { // not initial
+ if (!isPreviousChar(local, n, 'C')) {
+ code.append(symb);
+ }
+ } else {
+ code.append(symb); // initial K
+ }
+ break ;
+ case 'P' :
+ if (isNextChar(local,n,'H')) {
+ // PH -> F
+ code.append('F');
+ } else {
+ code.append(symb);
+ }
+ break ;
+ case 'Q' :
+ code.append('K');
+ break;
+ case 'S' :
+ if (regionMatch(local,n,""SH"") ||
+ regionMatch(local,n,""SIO"") ||
+ regionMatch(local,n,""SIA"")) {
+ code.append('X');
+ } else {
+ code.append('S');
+ }
+ break;
+ case 'T' :
+ if (regionMatch(local,n,""TIA"") ||
+ regionMatch(local,n,""TIO"")) {
+ code.append('X');
+ break;
+ }
+ if (regionMatch(local,n,""TCH"")) {
+ // Silent if in ""TCH""
+ break;
+ }
+ // substitute numeral 0 for TH (resembles theta after all)
+ if (regionMatch(local,n,""TH"")) {
+ code.append('0');
+ } else {
+ code.append('T');
+ }
+ break ;
+ case 'V' :
+ code.append('F'); break ;
+ case 'W' : case 'Y' : // silent if not followed by vowel
+ if (!isLastChar(wdsz,n) &&
+ isVowel(local,n+1)) {
+ code.append(symb);
+ }
+ break ;
+ case 'X' :
+ code.append('K'); code.append('S');
+ break ;
+ case 'Z' :
+ code.append('S'); break ;
+ } // end switch
+ n++ ;
+ } // end else from symb != 'C'
+ if (code.length() > this.getMaxCodeLen()) {
+ code.setLength(this.getMaxCodeLen());
+ }
+ }
+ return code.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testLocaleIndependence() throws Exception {
+ StringEncoder encoder = makeEncoder();
+
+ String[] data = { ""I"", ""i"", };
+
+ Locale orig = Locale.getDefault();
+ Locale[] locales = { Locale.ENGLISH, new Locale(""tr""), Locale.getDefault() };
+
+ try {
+ for (int i = 0; i < data.length; i++) {
+ String ref = null;
+ for (int j = 0; j < locales.length; j++) {
+ Locale.setDefault(locales[j]);
+ if (j <= 0) {
+ ref = encoder.encode(data[i]);
+ } else {
+ String cur = null;
+ try {
+ cur = encoder.encode(data[i]);
+ } catch (Exception e) {
+ fail(Locale.getDefault().toString() + "": "" + e.getMessage());
+ }
+ assertEquals(Locale.getDefault().toString() + "": "", ref, cur);
+ }
+ }
+ }
+ } finally {
+ Locale.setDefault(orig);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String caverphone(String txt) {
+ // NOTE: Version 1.0 of Caverphone is easily derivable from this code
+ // by commenting out the 2.0 lines and adding in the 1.0 lines
+
+ if( txt == null || txt.length() == 0 ) {
+ return ""1111111111"";
+ }
+
+ // 1. Convert to lowercase
+ txt = txt.toLowerCase(java.util.Locale.ENGLISH);
+
+ // 2. Remove anything not A-Z
+ txt = txt.replaceAll(""[^a-z]"", """");
+
+ // 2.5. Remove final e
+ txt = txt.replaceAll(""e$"", """"); // 2.0 only
+
+ // 3. Handle various start options
+ txt = txt.replaceAll(""^cough"", ""cou2f"");
+ txt = txt.replaceAll(""^rough"", ""rou2f"");
+ txt = txt.replaceAll(""^tough"", ""tou2f"");
+ txt = txt.replaceAll(""^enough"", ""enou2f""); // 2.0 only
+ txt = txt.replaceAll(""^trough"", ""trou2f""); // 2.0 only - note the spec says ^enough here again, c+p error I assume
+ txt = txt.replaceAll(""^gn"", ""2n"");
+
+ // End
+ txt = txt.replaceAll(""^mb"", ""m2"");
+
+ // 4. Handle replacements
+ txt = txt.replaceAll(""cq"", ""2q"");
+ txt = txt.replaceAll(""ci"", ""si"");
+ txt = txt.replaceAll(""ce"", ""se"");
+ txt = txt.replaceAll(""cy"", ""sy"");
+ txt = txt.replaceAll(""tch"", ""2ch"");
+ txt = txt.replaceAll(""c"", ""k"");
+ txt = txt.replaceAll(""q"", ""k"");
+ txt = txt.replaceAll(""x"", ""k"");
+ txt = txt.replaceAll(""v"", ""f"");
+ txt = txt.replaceAll(""dg"", ""2g"");
+ txt = txt.replaceAll(""tio"", ""sio"");
+ txt = txt.replaceAll(""tia"", ""sia"");
+ txt = txt.replaceAll(""d"", ""t"");
+ txt = txt.replaceAll(""ph"", ""fh"");
+ txt = txt.replaceAll(""b"", ""p"");
+ txt = txt.replaceAll(""sh"", ""s2"");
+ txt = txt.replaceAll(""z"", ""s"");
+ txt = txt.replaceAll(""^[aeiou]"", ""A"");
+ txt = txt.replaceAll(""[aeiou]"", ""3"");
+ txt = txt.replaceAll(""j"", ""y""); // 2.0 only
+ txt = txt.replaceAll(""^y3"", ""Y3""); // 2.0 only
+ txt = txt.replaceAll(""^y"", ""A""); // 2.0 only
+ txt = txt.replaceAll(""y"", ""3""); // 2.0 only
+ txt = txt.replaceAll(""3gh3"", ""3kh3"");
+ txt = txt.replaceAll(""gh"", ""22"");
+ txt = txt.replaceAll(""g"", ""k"");
+ txt = txt.replaceAll(""s+"", ""S"");
+ txt = txt.replaceAll(""t+"", ""T"");
+ txt = txt.replaceAll(""p+"", ""P"");
+ txt = txt.replaceAll(""k+"", ""K"");
+ txt = txt.replaceAll(""f+"", ""F"");
+ txt = txt.replaceAll(""m+"", ""M"");
+ txt = txt.replaceAll(""n+"", ""N"");
+ txt = txt.replaceAll(""w3"", ""W3"");
+ //txt = txt.replaceAll(""wy"", ""Wy""); // 1.0 only
+ txt = txt.replaceAll(""wh3"", ""Wh3"");
+ txt = txt.replaceAll(""w$"", ""3""); // 2.0 only
+ //txt = txt.replaceAll(""why"", ""Why""); // 1.0 only
+ txt = txt.replaceAll(""w"", ""2"");
+ txt = txt.replaceAll(""^h"", ""A"");
+ txt = txt.replaceAll(""h"", ""2"");
+ txt = txt.replaceAll(""r3"", ""R3"");
+ txt = txt.replaceAll(""r$"", ""3""); // 2.0 only
+ //txt = txt.replaceAll(""ry"", ""Ry""); // 1.0 only
+ txt = txt.replaceAll(""r"", ""2"");
+ txt = txt.replaceAll(""l3"", ""L3"");
+ txt = txt.replaceAll(""l$"", ""3""); // 2.0 only
+ //txt = txt.replaceAll(""ly"", ""Ly""); // 1.0 only
+ txt = txt.replaceAll(""l"", ""2"");
+ //txt = txt.replaceAll(""j"", ""y""); // 1.0 only
+ //txt = txt.replaceAll(""y3"", ""Y3""); // 1.0 only
+ //txt = txt.replaceAll(""y"", ""2""); // 1.0 only
+
+ // 5. Handle removals
+ txt = txt.replaceAll(""2"", """");
+ txt = txt.replaceAll(""3$"", ""A""); // 2.0 only
+ txt = txt.replaceAll(""3"", """");
+
+ // 6. put ten 1s on the end
+ txt = txt + ""111111"" + ""1111""; // 1.0 only has 6 1s
+
+ // 7. take the first six characters as the code
+ return txt.substring(0, 10); // 1.0 truncates to 6
+ }
+
+// Test Case
+[/INST]
+ public void testEndMb() throws EncoderException {
+ String[][] data = {{""mb"", ""M111111111""}, {""mbmb"", ""MPM1111111""}};
+ this.checkEncodings(data);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static final void encodeQuotedPrintable(int b, ByteArrayOutputStream buffer) {
+ buffer.write(ESCAPE_CHAR);
+ char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
+ char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
+ buffer.write(hex1);
+ buffer.write(hex2);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testSkipNotEncodedCRLF() throws Exception {
+ String qpdata = ""CRLF in an\n encoded text should be=20=\r\n\rskipped in the\r decoding."";
+ String expected = ""CRLF in an encoded text should be skipped in the decoding."";
+
+ QuotedPrintableCodec qpcodec = new QuotedPrintableCodec();
+ assertEquals(expected, qpcodec.decode(qpdata));
+
+ String encoded = qpcodec.encode(expected);
+ assertEquals(expected, qpcodec.decode(encoded));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static final byte[] encodeQuotedPrintable(BitSet printable, byte[] bytes) {
+ if (bytes == null) {
+ return null;
+ }
+ if (printable == null) {
+ printable = PRINTABLE_CHARS;
+ }
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ // encode up to buffer.length - 3, the last three octets will be treated
+ // separately for simplification of note #3
+ // up to this length it is safe to add any byte, encoded or not
+ for (byte c : bytes) {
+ int b = c;
+ if (b < 0) {
+ b = 256 + b;
+ }
+ if (printable.get(b)) {
+ buffer.write(b);
+ } else {
+ // rule #3: whitespace at the end of a line *must* be encoded
+
+ // rule #5: soft line break
+ encodeQuotedPrintable(b, buffer);
+ }
+ }
+
+ // rule #3: whitespace at the end of a line *must* be encoded
+ // if we would do a soft break line after this octet, encode whitespace
+
+ // note #3: '=' *must not* be the ultimate or penultimate character
+ // simplification: if < 6 bytes left, do a soft line break as we may need
+ // exactly 6 bytes space for the last 2 bytes
+ // rule #3: trailing whitespace shall be encoded
+
+ return buffer.toByteArray();
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testSkipNotEncodedCRLF() throws Exception {
+ String qpdata = ""CRLF in an\n encoded text should be=20=\r\n\rskipped in the\r decoding."";
+ String expected = ""CRLF in an encoded text should be skipped in the decoding."";
+
+ QuotedPrintableCodec qpcodec = new QuotedPrintableCodec();
+ assertEquals(expected, qpcodec.decode(qpdata));
+
+ String encoded = qpcodec.encode(expected);
+ assertEquals(expected, qpcodec.decode(encoded));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testSkipToEnd() throws Throwable {
+ InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_FOO));
+ Base32InputStream b32stream = new Base32InputStream(ins);
+ // due to CODEC-130, skip now skips correctly decoded characters rather than encoded
+ assertEquals(3, b32stream.skip(3));
+ // End of stream reached
+ assertEquals(-1, b32stream.read());
+ assertEquals(-1, b32stream.read());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean isDoubleMetaphoneEqual(final String value1, final String value2, final boolean alternate) {
+ return doubleMetaphone(value1, alternate).equals(doubleMetaphone(value2, alternate));
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testIsDoubleMetaphoneEqualBasic() {
+ final String[][] testFixture = new String[][] { {
+ """", """" }, {
+ ""Case"", ""case"" }, {
+ ""CASE"", ""Case"" }, {
+ ""caSe"", ""cAsE"" }, {
+ ""cookie"", ""quick"" }, {
+ ""quick"", ""cookie"" }, {
+ ""Brian"", ""Bryan"" }, {
+ ""Auto"", ""Otto"" }, {
+ ""Steven"", ""Stefan"" }, {
+ ""Philipowitz"", ""Filipowicz"" }
+ };
+ doubleMetaphoneEqualTest(testFixture, false);
+ doubleMetaphoneEqualTest(testFixture, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testIsDoubleMetaphoneEqualBasic() {
+ final String[][] testFixture = new String[][] { {
+ """", """" }, {
+ ""Case"", ""case"" }, {
+ ""CASE"", ""Case"" }, {
+ ""caSe"", ""cAsE"" }, {
+ ""cookie"", ""quick"" }, {
+ ""quick"", ""cookie"" }, {
+ ""Brian"", ""Bryan"" }, {
+ ""Auto"", ""Otto"" }, {
+ ""Steven"", ""Stefan"" }, {
+ ""Philipowitz"", ""Filipowicz"" }
+ };
+ doubleMetaphoneEqualTest(testFixture, false);
+ doubleMetaphoneEqualTest(testFixture, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testIsDoubleMetaphoneEqualBasic() {
+ final String[][] testFixture = new String[][] { {
+ """", """" }, {
+ ""Case"", ""case"" }, {
+ ""CASE"", ""Case"" }, {
+ ""caSe"", ""cAsE"" }, {
+ ""cookie"", ""quick"" }, {
+ ""quick"", ""cookie"" }, {
+ ""Brian"", ""Bryan"" }, {
+ ""Auto"", ""Otto"" }, {
+ ""Steven"", ""Stefan"" }, {
+ ""Philipowitz"", ""Filipowicz"" }
+ };
+ doubleMetaphoneEqualTest(testFixture, false);
+ doubleMetaphoneEqualTest(testFixture, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private PhonemeBuilder applyFinalRules(final PhonemeBuilder phonemeBuilder,
+ final Map> finalRules) {
+ if (finalRules == null) {
+ throw new NullPointerException(""finalRules can not be null"");
+ }
+ if (finalRules.isEmpty()) {
+ return phonemeBuilder;
+ }
+
+ final Set phonemes = new TreeSet(Rule.Phoneme.COMPARATOR);
+
+ for (final Rule.Phoneme phoneme : phonemeBuilder.getPhonemes()) {
+ PhonemeBuilder subBuilder = PhonemeBuilder.empty(phoneme.getLanguages());
+ final String phonemeText = phoneme.getPhonemeText().toString();
+
+ for (int i = 0; i < phonemeText.length();) {
+ final RulesApplication rulesApplication =
+ new RulesApplication(finalRules, phonemeText, subBuilder, i, maxPhonemes).invoke();
+ final boolean found = rulesApplication.isFound();
+ subBuilder = rulesApplication.getPhonemeBuilder();
+
+ if (!found) {
+ // not found, appending as-is
+ subBuilder.append(phonemeText.subSequence(i, i + 1));
+ }
+
+ i = rulesApplication.getI();
+ }
+
+ // the phonemes map orders the phonemes only based on their text, but ignores the language set
+ // when adding new phonemes, check for equal phonemes and merge their language set, otherwise
+ // phonemes with the same text but different language set get lost
+ phonemes.addAll(subBuilder.getPhonemes());
+ }
+
+ return new PhonemeBuilder(phonemes);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCompatibilityWithOriginalVersion() {
+ // see CODEC-187
+ // comparison: http://stevemorse.org/census/soundex.html
+
+ Map args = new TreeMap();
+ args.put(""nameType"", ""GENERIC"");
+ args.put(""ruleType"", ""APPROX"");
+
+ assertEquals(encode(args, true, ""abram""), ""Ybram|Ybrom|abram|abran|abrom|abron|avram|avrom|obram|obran|obrom|obron|ovram|ovrom"");
+ assertEquals(encode(args, true, ""Bendzin""), ""bndzn|bntsn|bnzn|vndzn|vntsn"");
+
+ args.put(""nameType"", ""ASHKENAZI"");
+ args.put(""ruleType"", ""APPROX"");
+
+ assertEquals(encode(args, true, ""abram""), ""Ybram|Ybrom|abram|abrom|avram|avrom|imbram|imbrom|obram|obrom|ombram|ombrom|ovram|ovrom"");
+ assertEquals(encode(args, true, ""Halpern""), ""YlpYrn|Ylpirn|alpYrn|alpirn|olpYrn|olpirn|xalpirn|xolpirn"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testCompatibilityWithOriginalVersion() {
+ // see CODEC-187
+ // comparison: http://stevemorse.org/census/soundex.html
+
+ Map args = new TreeMap();
+ args.put(""nameType"", ""GENERIC"");
+ args.put(""ruleType"", ""APPROX"");
+
+ assertEquals(encode(args, true, ""abram""), ""Ybram|Ybrom|abram|abran|abrom|abron|avram|avrom|obram|obran|obrom|obron|ovram|ovrom"");
+ assertEquals(encode(args, true, ""Bendzin""), ""bndzn|bntsn|bnzn|vndzn|vntsn"");
+
+ args.put(""nameType"", ""ASHKENAZI"");
+ args.put(""ruleType"", ""APPROX"");
+
+ assertEquals(encode(args, true, ""abram""), ""Ybram|Ybrom|abram|abrom|avram|avrom|imbram|imbrom|obram|obrom|ombram|ombrom|ovram|ovrom"");
+ assertEquals(encode(args, true, ""Halpern""), ""YlpYrn|Ylpirn|alpYrn|alpirn|olpYrn|olpirn|xalpirn|xolpirn"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testCompatibilityWithOriginalVersion() {
+ // see CODEC-187
+ // comparison: http://stevemorse.org/census/soundex.html
+
+ Map args = new TreeMap();
+ args.put(""nameType"", ""GENERIC"");
+ args.put(""ruleType"", ""APPROX"");
+
+ assertEquals(encode(args, true, ""abram""), ""Ybram|Ybrom|abram|abran|abrom|abron|avram|avrom|obram|obran|obrom|obron|ovram|ovrom"");
+ assertEquals(encode(args, true, ""Bendzin""), ""bndzn|bntsn|bnzn|vndzn|vntsn"");
+
+ args.put(""nameType"", ""ASHKENAZI"");
+ args.put(""ruleType"", ""APPROX"");
+
+ assertEquals(encode(args, true, ""abram""), ""Ybram|Ybrom|abram|abrom|avram|avrom|imbram|imbrom|obram|obrom|ombram|ombrom|ovram|ovrom"");
+ assertEquals(encode(args, true, ""Halpern""), ""YlpYrn|Ylpirn|alpYrn|alpirn|olpYrn|olpirn|xalpirn|xolpirn"");
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private char getMappingCode(final String str, final int index) {
+ // map() throws IllegalArgumentException
+ final char mappedChar = this.map(str.charAt(index));
+ // HW rule check
+ if (index > 1 && mappedChar != '0') {
+ final char hwChar = str.charAt(index - 1);
+ if ('H' == hwChar || 'W' == hwChar) {
+ final char preHWChar = str.charAt(index - 2);
+ final char firstCode = this.map(preHWChar);
+ if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) {
+ return 0;
+ }
+ }
+ }
+ return mappedChar;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testHWRuleEx1() {
+ // From
+ // http://www.archives.gov/research_room/genealogy/census/soundex.html:
+ // Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1
+ // for the F). It is not coded A-226.
+ Assert.assertEquals(""A261"", this.getStringEncoder().encode(""Ashcraft""));
+ Assert.assertEquals(""A261"", this.getStringEncoder().encode(""Ashcroft""));
+ Assert.assertEquals(""Y330"", this.getStringEncoder().encode(""yehudit""));
+ Assert.assertEquals(""Y330"", this.getStringEncoder().encode(""yhwdyt""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testCodec200() {
+ final Base32 codec = new Base32(true, (byte)'W'); // should be allowed
+ assertNotNull(codec);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static String newStringIso8859_1(final byte[] bytes) {
+ return new String(bytes, Charsets.ISO_8859_1);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testNewStringNullInput_CODEC229() {
+ Assert.assertNull(StringUtils.newStringUtf8(null));
+ Assert.assertNull(StringUtils.newStringIso8859_1(null));
+ Assert.assertNull(StringUtils.newStringUsAscii(null));
+ Assert.assertNull(StringUtils.newStringUtf16(null));
+ Assert.assertNull(StringUtils.newStringUtf16Be(null));
+ Assert.assertNull(StringUtils.newStringUtf16Le(null));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
+ if (cs1 == cs2) {
+ return true;
+ }
+ if (cs1 == null || cs2 == null) {
+ return false;
+ }
+ if (cs1 instanceof String && cs2 instanceof String) {
+ return cs1.equals(cs2);
+ }
+ return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEqualsCS1() {
+ Assert.assertFalse(StringUtils.equals(new StringBuilder(""abc""), null));
+ Assert.assertFalse(StringUtils.equals(null, new StringBuilder(""abc"")));
+ Assert.assertTrue(StringUtils.equals(new StringBuilder(""abc""), new StringBuilder(""abc"")));
+ Assert.assertFalse(StringUtils.equals(new StringBuilder(""abc""), new StringBuilder(""abcd"")));
+ Assert.assertFalse(StringUtils.equals(new StringBuilder(""abcd""), new StringBuilder(""abc"")));
+ Assert.assertFalse(StringUtils.equals(new StringBuilder(""abc""), new StringBuilder(""ABC"")));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void encode(byte[] in, int inPos, int inAvail) {
+ if (eof) {
+ return;
+ }
+ // inAvail < 0 is how we're informed of EOF in the underlying data we're
+ // encoding.
+ if (inAvail < 0) {
+ eof = true;
+ if (buf == null || buf.length - pos < encodeSize) {
+ resizeBuf();
+ }
+ switch (modulus) {
+ case 1:
+ buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS];
+ buf[pos++] = encodeTable[(x << 4) & MASK_6BITS];
+ // URL-SAFE skips the padding to further reduce size.
+ if (encodeTable == STANDARD_ENCODE_TABLE) {
+ buf[pos++] = PAD;
+ buf[pos++] = PAD;
+ }
+ break;
+
+ case 2:
+ buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS];
+ buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS];
+ buf[pos++] = encodeTable[(x << 2) & MASK_6BITS];
+ // URL-SAFE skips the padding to further reduce size.
+ if (encodeTable == STANDARD_ENCODE_TABLE) {
+ buf[pos++] = PAD;
+ }
+ break;
+ }
+ if (lineLength > 0) {
+ System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
+ pos += lineSeparator.length;
+ }
+ } else {
+ for (int i = 0; i < inAvail; i++) {
+ if (buf == null || buf.length - pos < encodeSize) {
+ resizeBuf();
+ }
+ modulus = (++modulus) % 3;
+ int b = in[inPos++];
+ if (b < 0) { b += 256; }
+ x = (x << 8) + b;
+ if (0 == modulus) {
+ buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS];
+ buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS];
+ buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS];
+ buf[pos++] = encodeTable[x & MASK_6BITS];
+ currentLinePos += 4;
+ if (lineLength > 0 && lineLength <= currentLinePos) {
+ System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);
+ pos += lineSeparator.length;
+ currentLinePos = 0;
+ }
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBase64EmptyInputStream() throws Exception {
+ byte[] emptyEncoded = new byte[0];
+ byte[] emptyDecoded = new byte[0];
+ testByteByByte(emptyEncoded, emptyDecoded, 76, CRLF);
+ testByChunk(emptyEncoded, emptyDecoded, 76, CRLF);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int handleG(String value,
+ DoubleMetaphoneResult result,
+ int index,
+ boolean slavoGermanic) {
+ if (charAt(value, index + 1) == 'H') {
+ index = handleGH(value, result, index);
+ } else if (charAt(value, index + 1) == 'N') {
+ if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) {
+ result.append(""KN"", ""N"");
+ } else if (!contains(value, index + 2, 2, ""EY"") &&
+ charAt(value, index + 1) != 'Y' && !slavoGermanic) {
+ result.append(""N"", ""KN"");
+ } else {
+ result.append(""KN"");
+ }
+ index = index + 2;
+ } else if (contains(value, index + 1, 2, ""LI"") && !slavoGermanic) {
+ result.append(""KL"", ""L"");
+ index += 2;
+ } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) {
+ //-- -ges-, -gep-, -gel-, -gie- at beginning --//
+ result.append('K', 'J');
+ index += 2;
+ } else if ((contains(value, index + 1, 2, ""ER"") ||
+ charAt(value, index + 1) == 'Y') &&
+ !contains(value, 0, 6, ""DANGER"", ""RANGER"", ""MANGER"") &&
+ !contains(value, index - 1, 1, ""E"", ""I"") &&
+ !contains(value, index - 1, 3, ""RGY"", ""OGY"")) {
+ //-- -ger-, -gy- --//
+ result.append('K', 'J');
+ index += 2;
+ } else if (contains(value, index + 1, 1, ""E"", ""I"", ""Y"") ||
+ contains(value, index - 1, 4, ""AGGI"", ""OGGI"")) {
+ //-- Italian ""biaggi"" --//
+ if ((contains(value, 0 ,4, ""VAN "", ""VON "") || contains(value, 0, 3, ""SCH"")) || contains(value, index + 1, 2, ""ET"")) {
+ //-- obvious germanic --//
+ result.append('K');
+ } else if (contains(value, index + 1, 4, ""IER"")) {
+ result.append('J');
+ } else {
+ result.append('J', 'K');
+ }
+ index += 2;
+ } else if (charAt(value, index + 1) == 'G') {
+ index += 2;
+ result.append('K');
+ } else {
+ index++;
+ result.append('K');
+ }
+ return index;
+ }
+
+// Test Case
+[/INST]
+ public void testDoubleMetaphoneAlternate() {
+ String value = null;
+ for (int i = 0; i < TEST_DATA.length; i++) {
+ value = TEST_DATA[i][0];
+ assertEquals(""Test ["" + i + ""]="" + value, TEST_DATA[i][2], doubleMetaphone.doubleMetaphone(value, true));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Base64() {
+ this(false);
+ }
+
+// Test Case
+[/INST]
+ public void testEncoder() throws EncoderException {
+ Encoder enc = new Base64();
+ for (int i = 0; i < STRINGS.length; i++) {
+ if (STRINGS[i] != null) {
+ byte[] base64 = utf8(STRINGS[i]);
+ byte[] binary = BYTES[i];
+ boolean b = Arrays.equals(base64, (byte[]) enc.encode(binary));
+ assertTrue(""Encoder test-"" + i, b);
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void decode(byte[] in, int inPos, int inAvail) {
+ if (eof) {
+ return;
+ }
+ if (inAvail < 0) {
+ eof = true;
+ }
+ for (int i = 0; i < inAvail; i++) {
+ if (buffer == null || buffer.length - pos < decodeSize) {
+ resizeBuffer();
+ }
+ byte b = in[inPos++];
+ if (b == PAD) {
+ // We're done.
+ eof = true;
+ break;
+ } else {
+ if (b >= 0 && b < DECODE_TABLE.length) {
+ int result = DECODE_TABLE[b];
+ if (result >= 0) {
+ modulus = (++modulus) % 4;
+ x = (x << 6) + result;
+ if (modulus == 0) {
+ buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);
+ buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);
+ buffer[pos++] = (byte) (x & MASK_8BITS);
+ }
+ }
+ }
+ }
+ }
+
+ // Two forms of EOF as far as base64 decoder is concerned: actual
+ // EOF (-1) and first time '=' character is encountered in stream.
+ // This approach makes the '=' padding characters completely optional.
+ if (eof && modulus != 0) {
+
+ x = x << 6;
+ switch (modulus) {
+ case 2 :
+ x = x << 6;
+ buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);
+ break;
+ case 3 :
+ buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);
+ buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);
+ break;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testCodec98NPE() throws Exception {
+ byte[] codec98 = StringUtils.getBytesUtf8(Base64TestData.CODEC_98_NPE);
+ ByteArrayInputStream data = new ByteArrayInputStream(codec98);
+ Base64InputStream stream = new Base64InputStream(data);
+
+ // This line causes an NPE in commons-codec-1.4.jar:
+ byte[] decodedBytes = Base64TestData.streamToBytes(stream, new byte[1024]);
+
+ String decoded = StringUtils.newStringUtf8(decodedBytes);
+ assertEquals(
+ ""codec-98 NPE Base64InputStream"", Base64TestData.CODEC_98_NPE_DECODED, decoded
+ );
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read(byte b[], int offset, int len) throws IOException {
+ if (b == null) {
+ throw new NullPointerException();
+ } else if (offset < 0 || len < 0) {
+ throw new IndexOutOfBoundsException();
+ } else if (offset > b.length || offset + len > b.length) {
+ throw new IndexOutOfBoundsException();
+ } else if (len == 0) {
+ return 0;
+ } else {
+ /*
+ Rationale for while-loop on (readLen == 0):
+ -----
+ Base64.readResults() usually returns > 0 or EOF (-1). In the
+ rare case where it returns 0, we just keep trying.
+
+ This is essentially an undocumented contract for InputStream
+ implementors that want their code to work properly with
+ java.io.InputStreamReader, since the latter hates it when
+ InputStream.read(byte[]) returns a zero. Unfortunately our
+ readResults() call must return 0 if a large amount of the data
+ being decoded was non-base64, so this while-loop enables proper
+ interop with InputStreamReader for that scenario.
+ -----
+ This is a fix for CODEC-101
+ */
+ if (!base64.hasData()) {
+ byte[] buf = new byte[doEncode ? 4096 : 8192];
+ int c = in.read(buf);
+ // A little optimization to avoid System.arraycopy()
+ // when possible.
+ if (c > 0 && b.length == len) {
+ base64.setInitialBuffer(b, offset, len);
+ }
+ if (doEncode) {
+ base64.encode(buf, 0, c);
+ } else {
+ base64.decode(buf, 0, c);
+ }
+ }
+ return base64.readResults(b, offset, len);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testCodec101() throws Exception {
+ byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3);
+ ByteArrayInputStream bais = new ByteArrayInputStream(codec101);
+ Base64InputStream in = new Base64InputStream(bais);
+ byte[] result = new byte[8192];
+ int c = in.read(result);
+ assertTrue(""Codec101: First read successful [c="" + c + ""]"", c > 0);
+
+ c = in.read(result);
+ assertTrue(""Codec101: Second read should report end-of-stream [c="" + c + ""]"", c < 0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static String encodeBase64String(byte[] binaryData) {
+ return StringUtils.newStringUtf8(encodeBase64(binaryData, true));
+ }
+
+// Test Case
+[/INST]
+ public void testByteToStringVariations() throws DecoderException {
+ Base64 base64 = new Base64(0);
+ byte[] b1 = StringUtils.getBytesUtf8(""Hello World"");
+ byte[] b2 = new byte[0];
+ byte[] b3 = null;
+ byte[] b4 = Hex.decodeHex(""2bf7cc2701fe4397b49ebeed5acc7090"".toCharArray()); // for url-safe tests
+
+ assertEquals(""byteToString Hello World"", ""SGVsbG8gV29ybGQ="", base64.encodeToString(b1));
+ assertEquals(""byteToString static Hello World"", ""SGVsbG8gV29ybGQ="", Base64.encodeBase64String(b1));
+ assertEquals(""byteToString \""\"""", """", base64.encodeToString(b2));
+ assertEquals(""byteToString static \""\"""", """", Base64.encodeBase64String(b2));
+ assertEquals(""byteToString null"", null, base64.encodeToString(b3));
+ assertEquals(""byteToString static null"", null, Base64.encodeBase64String(b3));
+ assertEquals(""byteToString UUID"", ""K/fMJwH+Q5e0nr7tWsxwkA=="", base64.encodeToString(b4));
+ assertEquals(""byteToString static UUID"", ""K/fMJwH+Q5e0nr7tWsxwkA=="", Base64.encodeBase64String(b4));
+ assertEquals(""byteToString static-url-safe UUID"", ""K_fMJwH-Q5e0nr7tWsxwkA"", Base64.encodeBase64URLSafeString(b4));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read(byte b[], int offset, int len) throws IOException {
+ if (b == null) {
+ throw new NullPointerException();
+ } else if (offset < 0 || len < 0) {
+ throw new IndexOutOfBoundsException();
+ } else if (offset > b.length || offset + len > b.length) {
+ throw new IndexOutOfBoundsException();
+ } else if (len == 0) {
+ return 0;
+ } else {
+ int readLen = 0;
+ /*
+ Rationale for while-loop on (readLen == 0):
+ -----
+ Base64.readResults() usually returns > 0 or EOF (-1). In the
+ rare case where it returns 0, we just keep trying.
+
+ This is essentially an undocumented contract for InputStream
+ implementors that want their code to work properly with
+ java.io.InputStreamReader, since the latter hates it when
+ InputStream.read(byte[]) returns a zero. Unfortunately our
+ readResults() call must return 0 if a large amount of the data
+ being decoded was non-base64, so this while-loop enables proper
+ interop with InputStreamReader for that scenario.
+ -----
+ This is a fix for CODEC-101
+ */
+ while (readLen == 0) {
+ if (!base64.hasData()) {
+ byte[] buf = new byte[doEncode ? 4096 : 8192];
+ int c = in.read(buf);
+ if (c > 0 && b.length == len) {
+ base64.setInitialBuffer(b, offset, len);
+ }
+ if (doEncode) {
+ base64.encode(buf, 0, c);
+ } else {
+ base64.decode(buf, 0, c);
+ }
+ }
+ readLen = base64.readResults(b, offset, len);
+ }
+ return readLen;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testCodec105() throws IOException {
+ Base64InputStream in = new Base64InputStream(new Codec105ErrorInputStream(), true, 0, null);
+ for (int i = 0; i < 5; i++) {
+ in.read();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testCodec105() throws IOException {
+ Base64InputStream in = new Base64InputStream(new Codec105ErrorInputStream(), true, 0, null);
+ for (int i = 0; i < 5; i++) {
+ in.read();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
+ if (binaryData == null || binaryData.length == 0) {
+ return binaryData;
+ }
+
+ long len = getEncodeLength(binaryData, MIME_CHUNK_SIZE, CHUNK_SEPARATOR);
+ if (len > maxResultSize) {
+ throw new IllegalArgumentException(""Input array too big, the output array would be bigger ("" +
+ len +
+ "") than the specified maxium size of "" +
+ maxResultSize);
+ }
+
+ Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
+ return b64.encode(binaryData);
+ }
+
+// Test Case
+[/INST]
+ public void testCodec112() { // size calculation assumes always chunked
+ byte[] in = new byte[] {0};
+ byte[] out=Base64.encodeBase64(in);
+ Base64.encodeBase64(in, false, false, out.length);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Iterator collatedIterator(final Comparator super E> comparator,
+ final Iterator extends E> iterator1,
+ final Iterator extends E> iterator2) {
+ return new CollatingIterator(comparator, iterator1, iterator2);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCollatedIterator() {
+ try {
+ IteratorUtils.collatedIterator(null, collectionOdd.iterator(), null);
+ fail(""expecting NullPointerException"");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ IteratorUtils.collatedIterator(null, null, collectionEven.iterator());
+ fail(""expecting NullPointerException"");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // natural ordering
+ Iterator it =
+ IteratorUtils.collatedIterator(null, collectionOdd.iterator(), collectionEven.iterator());
+
+ List result = IteratorUtils.toList(it);
+ assertEquals(12, result.size());
+
+ List combinedList = new ArrayList();
+ combinedList.addAll(collectionOdd);
+ combinedList.addAll(collectionEven);
+ Collections.sort(combinedList);
+
+ assertEquals(combinedList, result);
+
+ it = IteratorUtils.collatedIterator(null, collectionOdd.iterator(), emptyCollection.iterator());
+ result = IteratorUtils.toList(it);
+ assertEquals(collectionOdd, result);
+
+ final Comparator reverseComparator =
+ ComparatorUtils.reversedComparator(ComparatorUtils.naturalComparator());
+
+ Collections.reverse((List) collectionOdd);
+ Collections.reverse((List) collectionEven);
+ Collections.reverse(combinedList);
+
+ it = IteratorUtils.collatedIterator(reverseComparator,
+ collectionOdd.iterator(),
+ collectionEven.iterator());
+ result = IteratorUtils.toList(it);
+ assertEquals(combinedList, result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Iterator collatedIterator(final Comparator super E> comparator,
+ final Iterator extends E>... iterators) {
+ return new CollatingIterator(comparator, iterators);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCollatedIterator() {
+ try {
+ IteratorUtils.collatedIterator(null, collectionOdd.iterator(), null);
+ fail(""expecting NullPointerException"");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ IteratorUtils.collatedIterator(null, null, collectionEven.iterator());
+ fail(""expecting NullPointerException"");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // natural ordering
+ Iterator it =
+ IteratorUtils.collatedIterator(null, collectionOdd.iterator(), collectionEven.iterator());
+
+ List result = IteratorUtils.toList(it);
+ assertEquals(12, result.size());
+
+ List combinedList = new ArrayList();
+ combinedList.addAll(collectionOdd);
+ combinedList.addAll(collectionEven);
+ Collections.sort(combinedList);
+
+ assertEquals(combinedList, result);
+
+ it = IteratorUtils.collatedIterator(null, collectionOdd.iterator(), emptyCollection.iterator());
+ result = IteratorUtils.toList(it);
+ assertEquals(collectionOdd, result);
+
+ final Comparator reverseComparator =
+ ComparatorUtils.reversedComparator(ComparatorUtils.naturalComparator());
+
+ Collections.reverse((List) collectionOdd);
+ Collections.reverse((List) collectionEven);
+ Collections.reverse(combinedList);
+
+ it = IteratorUtils.collatedIterator(reverseComparator,
+ collectionOdd.iterator(),
+ collectionEven.iterator());
+ result = IteratorUtils.toList(it);
+ assertEquals(combinedList, result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Iterator collatedIterator(final Comparator super E> comparator,
+ final Collection> iterators) {
+ return new CollatingIterator(comparator, iterators);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCollatedIterator() {
+ try {
+ IteratorUtils.collatedIterator(null, collectionOdd.iterator(), null);
+ fail(""expecting NullPointerException"");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ try {
+ IteratorUtils.collatedIterator(null, null, collectionEven.iterator());
+ fail(""expecting NullPointerException"");
+ } catch (NullPointerException npe) {
+ // expected
+ }
+
+ // natural ordering
+ Iterator it =
+ IteratorUtils.collatedIterator(null, collectionOdd.iterator(), collectionEven.iterator());
+
+ List result = IteratorUtils.toList(it);
+ assertEquals(12, result.size());
+
+ List combinedList = new ArrayList();
+ combinedList.addAll(collectionOdd);
+ combinedList.addAll(collectionEven);
+ Collections.sort(combinedList);
+
+ assertEquals(combinedList, result);
+
+ it = IteratorUtils.collatedIterator(null, collectionOdd.iterator(), emptyCollection.iterator());
+ result = IteratorUtils.toList(it);
+ assertEquals(collectionOdd, result);
+
+ final Comparator reverseComparator =
+ ComparatorUtils.reversedComparator(ComparatorUtils.naturalComparator());
+
+ Collections.reverse((List) collectionOdd);
+ Collections.reverse((List) collectionEven);
+ Collections.reverse(combinedList);
+
+ it = IteratorUtils.collatedIterator(reverseComparator,
+ collectionOdd.iterator(),
+ collectionEven.iterator());
+ result = IteratorUtils.toList(it);
+ assertEquals(combinedList, result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Object readResolve() {
+ calculateHashCode(keys);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testEqualsAfterSerializationOfDerivedClass() throws IOException, ClassNotFoundException
+ {
+ final DerivedMultiKey> mk = new DerivedMultiKey(""A"", ""B"");
+
+ // serialize
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final ObjectOutputStream out = new ObjectOutputStream(baos);
+ out.writeObject(mk);
+ out.close();
+
+ // deserialize
+ final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ final ObjectInputStream in = new ObjectInputStream(bais);
+ final DerivedMultiKey> mk2 = (DerivedMultiKey>)in.readObject();
+ in.close();
+
+ assertEquals(mk.hashCode(), mk2.hashCode());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testUnsafeDeSerialization() throws Exception {
+ MultiValueMap map1 = MultiValueMap.multiValueMap(new HashMap(), ArrayList.class);
+ byte[] bytes = serialize(map1);
+ Object result = deserialize(bytes);
+ assertEquals(map1, result);
+
+ MultiValueMap map2 = MultiValueMap.multiValueMap(new HashMap(), (Class) String.class);
+ bytes = serialize(map2);
+ try {
+ result = deserialize(bytes);
+ fail(""unsafe clazz accepted when de-serializing MultiValueMap"");
+ } catch (UnsupportedOperationException ex) {
+ // expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testPrefixMapClear() {
+ Trie trie = new PatriciaTrie();
+ trie.put(""Anna"", 1);
+ trie.put(""Anael"", 2);
+ trie.put(""Analu"", 3);
+ trie.put(""Andreas"", 4);
+ trie.put(""Andrea"", 5);
+ trie.put(""Andres"", 6);
+ trie.put(""Anatole"", 7);
+ SortedMap prefixMap = trie.prefixMap(""And"");
+ assertEquals(new HashSet(Arrays.asList(""Andrea"", ""Andreas"", ""Andres"")), prefixMap.keySet());
+ assertEquals(Arrays.asList(5, 4, 6), new ArrayList(prefixMap.values()));
+
+ prefixMap.clear();
+ assertTrue(prefixMap.isEmpty());
+ assertTrue(prefixMap.keySet().isEmpty());
+ assertTrue(prefixMap.values().isEmpty());
+ assertEquals(new HashSet(Arrays.asList(""Anael"", ""Analu"", ""Anatole"", ""Anna"")), trie.keySet());
+ assertEquals(Arrays.asList(2, 3, 7, 1), new ArrayList(trie.values()));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void close() throws IOException {
+ if (!this.closed) {
+ super.close();
+ this.closed = true;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testCpioUnarchive() throws Exception {
+ final File output = new File(dir, ""bla.cpio"");
+ {
+ final File file1 = getFile(""test1.xml"");
+ final File file2 = getFile(""test2.xml"");
+
+ final OutputStream out = new FileOutputStream(output);
+ final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(""cpio"", out);
+ os.putArchiveEntry(new CpioArchiveEntry(""test1.xml"", file1.length()));
+ IOUtils.copy(new FileInputStream(file1), os);
+ os.closeArchiveEntry();
+
+ os.putArchiveEntry(new CpioArchiveEntry(""test2.xml"", file2.length()));
+ IOUtils.copy(new FileInputStream(file2), os);
+ os.closeArchiveEntry();
+
+ os.close();
+ out.close();
+ }
+
+ // Unarchive Operation
+ final File input = output;
+ final InputStream is = new FileInputStream(input);
+ final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(""cpio"", is);
+
+
+ Map result = new HashMap();
+ ArchiveEntry entry = null;
+ while ((entry = in.getNextEntry()) != null) {
+ File target = new File(dir, entry.getName());
+ final OutputStream out = new FileOutputStream(target);
+ IOUtils.copy(in, out);
+ out.close();
+ result.put(entry.getName(), target);
+ }
+ in.close();
+
+ int lineSepLength = System.getProperty(""line.separator"").length();
+
+ File t = (File)result.get(""test1.xml"");
+ assertTrue(""Expected "" + t.getAbsolutePath() + "" to exist"", t.exists());
+ assertEquals(""length of "" + t.getAbsolutePath(),
+ 72 + 4 * lineSepLength, t.length());
+
+ t = (File)result.get(""test2.xml"");
+ assertTrue(""Expected "" + t.getAbsolutePath() + "" to exist"", t.exists());
+ assertEquals(""length of "" + t.getAbsolutePath(),
+ 73 + 5 * lineSepLength, t.length());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void resolveLocalFileHeaderData(Map
+ entriesWithoutUTF8Flag)
+ throws IOException {
+ // changing the name of a ZipArchiveEntry is going to change
+ // the hashcode - see COMPRESS-164
+ // Map needs to be reconstructed in order to keep central
+ // directory order
+ for (ZipArchiveEntry ze : entries.keySet()) {
+ OffsetEntry offsetEntry = entries.get(ze);
+ long offset = offsetEntry.headerOffset;
+ archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH);
+ byte[] b = new byte[SHORT];
+ archive.readFully(b);
+ int fileNameLen = ZipShort.getValue(b);
+ archive.readFully(b);
+ int extraFieldLen = ZipShort.getValue(b);
+ int lenToSkip = fileNameLen;
+ while (lenToSkip > 0) {
+ int skipped = archive.skipBytes(lenToSkip);
+ if (skipped <= 0) {
+ throw new RuntimeException(""failed to skip file name in""
+ + "" local file header"");
+ }
+ lenToSkip -= skipped;
+ }
+ byte[] localExtraData = new byte[extraFieldLen];
+ archive.readFully(localExtraData);
+ ze.setExtra(localExtraData);
+ offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH
+ + SHORT + SHORT + fileNameLen + extraFieldLen;
+
+ if (entriesWithoutUTF8Flag.containsKey(ze)) {
+ String orig = ze.getName();
+ NameAndComment nc = entriesWithoutUTF8Flag.get(ze);
+ ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name,
+ nc.comment);
+ if (!orig.equals(ze.getName())) {
+ nameMap.remove(orig);
+ nameMap.put(ze.getName(), ze);
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testReadWinZipArchive() throws IOException, URISyntaxException {
+ URL zip = getClass().getResource(""/utf8-winzip-test.zip"");
+ File archive = new File(new URI(zip.toString()));
+ ZipFile zf = null;
+ try {
+ zf = new ZipFile(archive, null, true);
+ assertCanRead(zf, ASCII_TXT);
+ assertCanRead(zf, EURO_FOR_DOLLAR_TXT);
+ assertCanRead(zf, OIL_BARREL_TXT);
+ } finally {
+ ZipFile.closeQuietly(zf);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ArchiveInputStream createArchiveInputStream(final InputStream in)
+ throws ArchiveException {
+ if (in == null) {
+ throw new IllegalArgumentException(""Stream must not be null."");
+ }
+
+ if (!in.markSupported()) {
+ throw new IllegalArgumentException(""Mark is not supported."");
+ }
+
+ final byte[] signature = new byte[12];
+ in.mark(signature.length);
+ try {
+ int signatureLength = in.read(signature);
+ in.reset();
+ if (ZipArchiveInputStream.matches(signature, signatureLength)) {
+ return new ZipArchiveInputStream(in);
+ } else if (JarArchiveInputStream.matches(signature, signatureLength)) {
+ return new JarArchiveInputStream(in);
+ } else if (ArArchiveInputStream.matches(signature, signatureLength)) {
+ return new ArArchiveInputStream(in);
+ } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {
+ return new CpioArchiveInputStream(in);
+ }
+
+ // Dump needs a bigger buffer to check the signature;
+ final byte[] dumpsig = new byte[32];
+ in.mark(dumpsig.length);
+ signatureLength = in.read(dumpsig);
+ in.reset();
+ if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {
+ return new DumpArchiveInputStream(in);
+ }
+
+ // Tar needs an even bigger buffer to check the signature; read the first block
+ final byte[] tarheader = new byte[512];
+ in.mark(tarheader.length);
+ signatureLength = in.read(tarheader);
+ in.reset();
+ if (TarArchiveInputStream.matches(tarheader, signatureLength)) {
+ return new TarArchiveInputStream(in);
+ }
+ // COMPRESS-117 - improve auto-recognition
+ try {
+ TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));
+ tais.getNextEntry();
+ return new TarArchiveInputStream(in);
+ } catch (Exception e) { // NOPMD
+ // can generate IllegalArgumentException as well as IOException
+ // autodetection, simply not a TAR
+ // ignored
+ }
+ } catch (IOException e) {
+ throw new ArchiveException(""Could not use reset and mark operations."", e);
+ }
+
+ throw new ArchiveException(""No Archiver found for the stream signature"");
+ }
+
+// Test Case
+[/INST]
+ public void shortTextFilesAreNoTARs() throws Exception {
+ try {
+ new ArchiveStreamFactory()
+ .createArchiveInputStream(new ByteArrayInputStream(""This certainly is not a tar archive, really, no kidding"".getBytes()));
+ fail(""created an input stream for a non-archive"");
+ } catch (ArchiveException ae) {
+ assertTrue(ae.getMessage().startsWith(""No Archiver found""));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public TarArchiveEntry getNextTarEntry() throws IOException {
+ if (hasHitEOF) {
+ return null;
+ }
+
+ if (currEntry != null) {
+ long numToSkip = entrySize - entryOffset;
+
+ while (numToSkip > 0) {
+ long skipped = skip(numToSkip);
+ if (skipped <= 0) {
+ throw new RuntimeException(""failed to skip current tar entry"");
+ }
+ numToSkip -= skipped;
+ }
+
+ readBuf = null;
+ }
+
+ byte[] headerBuf = getRecord();
+
+ if (hasHitEOF) {
+ currEntry = null;
+ return null;
+ }
+
+ currEntry = new TarArchiveEntry(headerBuf);
+ entryOffset = 0;
+ entrySize = currEntry.getSize();
+
+ if (currEntry.isGNULongNameEntry()) {
+ // read in the name
+ StringBuffer longName = new StringBuffer();
+ byte[] buf = new byte[SMALL_BUFFER_SIZE];
+ int length = 0;
+ while ((length = read(buf)) >= 0) {
+ longName.append(new String(buf, 0, length));
+ }
+ getNextEntry();
+ if (currEntry == null) {
+ // Bugzilla: 40334
+ // Malformed tar file - long entry name not followed by entry
+ return null;
+ }
+ // remove trailing null terminator
+ if (longName.length() > 0
+ && longName.charAt(longName.length() - 1) == 0) {
+ longName.deleteCharAt(longName.length() - 1);
+ }
+ currEntry.setName(longName.toString());
+ }
+
+ if (currEntry.isPaxHeader()){ // Process Pax headers
+ paxHeaders();
+ }
+
+ if (currEntry.isGNUSparse()){ // Process sparse files
+ readGNUSparse();
+ }
+
+ // If the size of the next element in the archive has changed
+ // due to a new size being reported in the posix header
+ // information, we update entrySize here so that it contains
+ // the correct value.
+ entrySize = currEntry.getSize();
+ return currEntry;
+ }
+
+// Test Case
+[/INST]
+ public void testCOMPRESS178() throws Exception {
+ final File input = getFile(""COMPRESS-178.tar"");
+ final InputStream is = new FileInputStream(input);
+ final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(""tar"", is);
+ try {
+ in.getNextEntry();
+ fail(""Expected IOException"");
+ } catch (IOException e) {
+ Throwable t = e.getCause();
+ assertTrue(""Expected cause = IllegalArgumentException"", t instanceof IllegalArgumentException);
+ }
+ in.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void setName(String name) {
+ this.name = name;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void winzipBackSlashWorkaround() throws Exception {
+ URL zip = getClass().getResource(""/test-winzip.zip"");
+ ZipArchiveInputStream in = null;
+ try {
+ in = new ZipArchiveInputStream(new FileInputStream(new File(new URI(zip.toString()))));
+ ZipArchiveEntry zae = in.getNextZipEntry();
+ zae = in.getNextZipEntry();
+ zae = in.getNextZipEntry();
+ assertEquals(""\u00e4/"", zae.getName());
+ } finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long parseOctal(final byte[] buffer, final int offset, final int length) {
+ long result = 0;
+ int end = offset + length;
+ int start = offset;
+
+ if (length < 2){
+ throw new IllegalArgumentException(""Length ""+length+"" must be at least 2"");
+ }
+
+ boolean allNUL = true;
+ for (int i = start; i < end; i++){
+ if (buffer[i] != 0){
+ allNUL = false;
+ break;
+ }
+ }
+ if (allNUL) {
+ return 0L;
+ }
+
+ // Skip leading spaces
+ while (start < end){
+ if (buffer[start] == ' '){
+ start++;
+ } else {
+ break;
+ }
+ }
+
+ // Must have trailing NUL or space
+ byte trailer;
+ trailer = buffer[end-1];
+ if (trailer == 0 || trailer == ' '){
+ end--;
+ } else {
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, end-1, trailer));
+ }
+ // May have additional NUL or space
+ trailer = buffer[end-1];
+ if (trailer == 0 || trailer == ' '){
+ end--;
+ }
+
+ for ( ;start < end; start++) {
+ final byte currentByte = buffer[start];
+ // CheckStyle:MagicNumber OFF
+ if (currentByte < '0' || currentByte > '7'){
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, currentByte));
+ }
+ result = (result << 3) + (currentByte - '0'); // convert from ASCII
+ // CheckStyle:MagicNumber ON
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void workaroundForBrokenTimeHeader() throws Exception {
+ URL tar = getClass().getResource(""/simple-aix-native-tar.tar"");
+ TarArchiveInputStream in = null;
+ try {
+ in = new TarArchiveInputStream(new FileInputStream(new File(new URI(tar.toString()))));
+ TarArchiveEntry tae = in.getNextTarEntry();
+ tae = in.getNextTarEntry();
+ assertEquals(""sample/link-to-txt-file.lnk"", tae.getName());
+ assertEquals(new Date(0), tae.getLastModifiedDate());
+ assertTrue(tae.isSymbolicLink());
+ } finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ ZipArchiveEntry other = (ZipArchiveEntry) obj;
+ String myName = getName();
+ String otherName = other.getName();
+ if (myName == null) {
+ if (otherName != null) {
+ return false;
+ }
+ } else if (!myName.equals(otherName)) {
+ return false;
+ }
+ String myComment = getComment();
+ String otherComment = other.getComment();
+ if (myComment == null) {
+ if (otherComment != null) {
+ return false;
+ }
+ } else if (!myComment.equals(otherComment)) {
+ return false;
+ }
+ return getTime() == other.getTime()
+ && getInternalAttributes() == other.getInternalAttributes()
+ && getPlatform() == other.getPlatform()
+ && getExternalAttributes() == other.getExternalAttributes()
+ && getMethod() == other.getMethod()
+ && getSize() == other.getSize()
+ && getCrc() == other.getCrc()
+ && getCompressedSize() == other.getCompressedSize()
+ && Arrays.equals(getCentralDirectoryExtra(),
+ other.getCentralDirectoryExtra())
+ && Arrays.equals(getLocalFileDataExtra(),
+ other.getLocalFileDataExtra())
+ && gpb.equals(other.gpb);
+ }
+
+// Test Case
+[/INST]
+ public void testNullCommentEqualsEmptyComment() {
+ ZipArchiveEntry entry1 = new ZipArchiveEntry(""foo"");
+ ZipArchiveEntry entry2 = new ZipArchiveEntry(""foo"");
+ ZipArchiveEntry entry3 = new ZipArchiveEntry(""foo"");
+ entry1.setComment(null);
+ entry2.setComment("""");
+ entry3.setComment(""bar"");
+ assertEquals(entry1, entry2);
+ assertFalse(entry1.equals(entry3));
+ assertFalse(entry2.equals(entry3));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ArchiveInputStream createArchiveInputStream(final InputStream in)
+ throws ArchiveException {
+ if (in == null) {
+ throw new IllegalArgumentException(""Stream must not be null."");
+ }
+
+ if (!in.markSupported()) {
+ throw new IllegalArgumentException(""Mark is not supported."");
+ }
+
+ final byte[] signature = new byte[12];
+ in.mark(signature.length);
+ try {
+ int signatureLength = in.read(signature);
+ in.reset();
+ if (ZipArchiveInputStream.matches(signature, signatureLength)) {
+ return new ZipArchiveInputStream(in);
+ } else if (JarArchiveInputStream.matches(signature, signatureLength)) {
+ return new JarArchiveInputStream(in);
+ } else if (ArArchiveInputStream.matches(signature, signatureLength)) {
+ return new ArArchiveInputStream(in);
+ } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {
+ return new CpioArchiveInputStream(in);
+ }
+
+ // Dump needs a bigger buffer to check the signature;
+ final byte[] dumpsig = new byte[32];
+ in.mark(dumpsig.length);
+ signatureLength = in.read(dumpsig);
+ in.reset();
+ if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {
+ return new DumpArchiveInputStream(in);
+ }
+
+ // Tar needs an even bigger buffer to check the signature; read the first block
+ final byte[] tarheader = new byte[512];
+ in.mark(tarheader.length);
+ signatureLength = in.read(tarheader);
+ in.reset();
+ if (TarArchiveInputStream.matches(tarheader, signatureLength)) {
+ return new TarArchiveInputStream(in);
+ }
+ // COMPRESS-117 - improve auto-recognition
+ if (signatureLength >= 512) {
+ try {
+ TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));
+ // COMPRESS-191 - verify the header checksum
+ tais.getNextEntry();
+ return new TarArchiveInputStream(in);
+ } catch (Exception e) { // NOPMD
+ // can generate IllegalArgumentException as well
+ // as IOException
+ // autodetection, simply not a TAR
+ // ignored
+ }
+ }
+ } catch (IOException e) {
+ throw new ArchiveException(""Could not use reset and mark operations."", e);
+ }
+
+ throw new ArchiveException(""No Archiver found for the stream signature"");
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void aiffFilesAreNoTARs() throws Exception {
+ InputStream is = null;
+ try {
+ is = new BufferedInputStream(new FileInputStream(""src/test/resources/testAIFF.aif""));
+ new ArchiveStreamFactory().createArchiveInputStream(is);
+ fail(""created an input stream for a non-archive"");
+ } catch (ArchiveException ae) {
+ assertTrue(ae.getMessage().startsWith(""No Archiver found""));
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long parseOctal(final byte[] buffer, final int offset, final int length) {
+ long result = 0;
+ int end = offset + length;
+ int start = offset;
+
+ if (length < 2){
+ throw new IllegalArgumentException(""Length ""+length+"" must be at least 2"");
+ }
+
+ if (buffer[start] == 0) {
+ return 0L;
+ }
+
+ // Skip leading spaces
+ while (start < end){
+ if (buffer[start] == ' '){
+ start++;
+ } else {
+ break;
+ }
+ }
+
+ // Must have trailing NUL or space
+ byte trailer;
+ trailer = buffer[end-1];
+ if (trailer == 0 || trailer == ' '){
+ end--;
+ } else {
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, end-1, trailer));
+ }
+ // May have additional NULs or spaces
+ trailer = buffer[end - 1];
+ if (trailer == 0 || trailer == ' '){
+ end--;
+ }
+
+ for ( ;start < end; start++) {
+ final byte currentByte = buffer[start];
+ // CheckStyle:MagicNumber OFF
+ if (currentByte < '0' || currentByte > '7'){
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, currentByte));
+ }
+ result = (result << 3) + (currentByte - '0'); // convert from ASCII
+ // CheckStyle:MagicNumber ON
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCompress197() throws Exception {
+ TarArchiveInputStream tar = getTestStream(""/COMPRESS-197.tar"");
+ try {
+ TarArchiveEntry entry = tar.getNextTarEntry();
+ while (entry != null) {
+ entry = tar.getNextTarEntry();
+ }
+ } catch (IOException e) {
+ fail(""COMPRESS-197: "" + e.getMessage());
+ } finally {
+ tar.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void writePaxHeaders(String entryName,
+ Map headers) throws IOException {
+ String name = ""./PaxHeaders.X/"" + stripTo7Bits(entryName);
+ // TarEntry's constructor would think this is a directory
+ // and not allow any data to be written
+ if (name.length() >= TarConstants.NAMELEN) {
+ name = name.substring(0, TarConstants.NAMELEN - 1);
+ }
+ TarArchiveEntry pex = new TarArchiveEntry(name,
+ TarConstants.LF_PAX_EXTENDED_HEADER_LC);
+
+ StringWriter w = new StringWriter();
+ for (Map.Entry h : headers.entrySet()) {
+ String key = h.getKey();
+ String value = h.getValue();
+ int len = key.length() + value.length()
+ + 3 /* blank, equals and newline */
+ + 2 /* guess 9 < actual length < 100 */;
+ String line = len + "" "" + key + ""="" + value + ""\n"";
+ int actualLength = line.getBytes(CharsetNames.UTF_8).length;
+ while (len != actualLength) {
+ // Adjust for cases where length < 10 or > 100
+ // or where UTF-8 encoding isn't a single octet
+ // per character.
+ // Must be in loop as size may go from 99 to 100 in
+ // first pass so we'd need a second.
+ len = actualLength;
+ line = len + "" "" + key + ""="" + value + ""\n"";
+ actualLength = line.getBytes(CharsetNames.UTF_8).length;
+ }
+ w.write(line);
+ }
+ byte[] data = w.toString().getBytes(CharsetNames.UTF_8);
+ pex.setSize(data.length);
+ putArchiveEntry(pex);
+ write(data);
+ closeArchiveEntry();
+ }
+
+// Test Case
+[/INST]
+ public void testWriteNonAsciiDirectoryNamePosixMode() throws Exception {
+ String n = ""f\u00f6\u00f6/"";
+ TarArchiveEntry t = new TarArchiveEntry(n);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
+ tos.setAddPaxHeadersForNonAsciiNames(true);
+ tos.putArchiveEntry(t);
+ tos.closeArchiveEntry();
+ tos.close();
+ byte[] data = bos.toByteArray();
+ TarArchiveInputStream tin =
+ new TarArchiveInputStream(new ByteArrayInputStream(data));
+ TarArchiveEntry e = tin.getNextTarEntry();
+ assertEquals(n, e.getName());
+ assertTrue(e.isDirectory());
+ tin.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void reparseCentralDirectoryData(boolean hasUncompressedSize,
+ boolean hasCompressedSize,
+ boolean hasRelativeHeaderOffset,
+ boolean hasDiskStart)
+ throws ZipException {
+ if (rawCentralDirectoryData != null) {
+ int expectedLength = (hasUncompressedSize ? DWORD : 0)
+ + (hasCompressedSize ? DWORD : 0)
+ + (hasRelativeHeaderOffset ? DWORD : 0)
+ + (hasDiskStart ? WORD : 0);
+ if (rawCentralDirectoryData.length != expectedLength) {
+ throw new ZipException(""central directory zip64 extended""
+ + "" information extra field's length""
+ + "" doesn't match central directory""
+ + "" data. Expected length ""
+ + expectedLength + "" but is ""
+ + rawCentralDirectoryData.length);
+ }
+ int offset = 0;
+ if (hasUncompressedSize) {
+ size = new ZipEightByteInteger(rawCentralDirectoryData, offset);
+ offset += DWORD;
+ }
+ if (hasCompressedSize) {
+ compressedSize = new ZipEightByteInteger(rawCentralDirectoryData,
+ offset);
+ offset += DWORD;
+ }
+ if (hasRelativeHeaderOffset) {
+ relativeHeaderOffset =
+ new ZipEightByteInteger(rawCentralDirectoryData, offset);
+ offset += DWORD;
+ }
+ if (hasDiskStart) {
+ diskStart = new ZipLong(rawCentralDirectoryData, offset);
+ offset += WORD;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testExcessDataInZip64ExtraField() throws Exception {
+ File archive = getFile(""COMPRESS-228.zip"");
+ zf = new ZipFile(archive);
+ // actually, if we get here, the test already has passed
+
+ ZipArchiveEntry ze = zf.getEntry(""src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java"");
+ assertEquals(26101, ze.getSize());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ArArchiveEntry getNextArEntry() throws IOException {
+ // hit EOF before previous entry was complete
+ // TODO: throw an exception instead?
+
+ if (offset == 0) {
+ final byte[] expected = ArArchiveEntry.HEADER.getBytes();
+ final byte[] realized = new byte[expected.length];
+ final int read = read(realized);
+ if (read != expected.length) {
+ throw new IOException(""failed to read header"");
+ }
+ for (int i = 0; i < expected.length; i++) {
+ if (expected[i] != realized[i]) {
+ throw new IOException(""invalid header "" + new String(realized));
+ }
+ }
+ }
+
+ // hit eof
+
+ if (input.available() == 0) {
+ return null;
+ }
+
+ if (offset % 2 != 0) {
+ read();
+ }
+ final byte[] name = new byte[16];
+ final byte[] lastmodified = new byte[12];
+ final byte[] userid = new byte[6];
+ final byte[] groupid = new byte[6];
+ final byte[] filemode = new byte[8];
+ final byte[] length = new byte[10];
+
+ read(name);
+ read(lastmodified);
+ read(userid);
+ read(groupid);
+ read(filemode);
+ read(length);
+
+ {
+ final byte[] expected = ArArchiveEntry.TRAILER.getBytes();
+ final byte[] realized = new byte[expected.length];
+ final int read = read(realized);
+ if (read != expected.length) {
+ throw new IOException(""failed to read entry header"");
+ }
+ for (int i = 0; i < expected.length; i++) {
+ if (expected[i] != realized[i]) {
+ throw new IOException(""invalid entry header. not read the content?"");
+ }
+ }
+ }
+
+ return new ArArchiveEntry(new String(name).trim(),
+ Long.parseLong(new String(length)
+ .trim()));
+ }
+
+// Test Case
+[/INST]
+ public void testArDelete() throws Exception {
+ final File output = new File(dir, ""bla.ar"");
+
+ final File file1 = getFile(""test1.xml"");
+ final File file2 = getFile(""test2.xml"");
+ {
+ // create
+
+ final OutputStream out = new FileOutputStream(output);
+ final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(""ar"", out);
+ os.putArchiveEntry(new ArArchiveEntry(""test1.xml"", file1.length()));
+ IOUtils.copy(new FileInputStream(file1), os);
+ os.closeArchiveEntry();
+
+ os.putArchiveEntry(new ArArchiveEntry(""test2.xml"", file2.length()));
+ IOUtils.copy(new FileInputStream(file2), os);
+ os.closeArchiveEntry();
+ os.close();
+ out.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read() throws IOException {
+ final int ret = input.read();
+ offset += (ret > 0 ? 1 : 0);
+ return ret;
+ }
+
+// Test Case
+[/INST]
+ public void testArDelete() throws Exception {
+ final File output = new File(dir, ""bla.ar"");
+
+ final File file1 = getFile(""test1.xml"");
+ final File file2 = getFile(""test2.xml"");
+ {
+ // create
+
+ final OutputStream out = new FileOutputStream(output);
+ final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(""ar"", out);
+ os.putArchiveEntry(new ArArchiveEntry(""test1.xml"", file1.length()));
+ IOUtils.copy(new FileInputStream(file1), os);
+ os.closeArchiveEntry();
+
+ os.putArchiveEntry(new ArArchiveEntry(""test2.xml"", file2.length()));
+ IOUtils.copy(new FileInputStream(file2), os);
+ os.closeArchiveEntry();
+ os.close();
+ out.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read(byte[] b, final int off, final int len) throws IOException {
+ int toRead = len;
+ final int ret = this.input.read(b, off, toRead);
+ offset += (ret > 0 ? ret : 0);
+ return ret;
+ }
+
+// Test Case
+[/INST]
+ public void testArDelete() throws Exception {
+ final File output = new File(dir, ""bla.ar"");
+
+ final File file1 = getFile(""test1.xml"");
+ final File file2 = getFile(""test2.xml"");
+ {
+ // create
+
+ final OutputStream out = new FileOutputStream(output);
+ final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(""ar"", out);
+ os.putArchiveEntry(new ArArchiveEntry(""test1.xml"", file1.length()));
+ IOUtils.copy(new FileInputStream(file1), os);
+ os.closeArchiveEntry();
+
+ os.putArchiveEntry(new ArArchiveEntry(""test2.xml"", file2.length()));
+ IOUtils.copy(new FileInputStream(file2), os);
+ os.closeArchiveEntry();
+ os.close();
+ out.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testArDelete() throws Exception {
+ final File output = new File(dir, ""bla.ar"");
+
+ final File file1 = getFile(""test1.xml"");
+ final File file2 = getFile(""test2.xml"");
+ {
+ // create
+
+ final OutputStream out = new FileOutputStream(output);
+ final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(""ar"", out);
+ os.putArchiveEntry(new ArArchiveEntry(""test1.xml"", file1.length()));
+ IOUtils.copy(new FileInputStream(file1), os);
+ os.closeArchiveEntry();
+
+ os.putArchiveEntry(new ArArchiveEntry(""test2.xml"", file2.length()));
+ IOUtils.copy(new FileInputStream(file2), os);
+ os.closeArchiveEntry();
+ os.close();
+ out.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {
+ int cache = 0;
+ int shift = 7;
+ for (int i = 0; i < length; i++) {
+ cache |= ((bits.get(i) ? 1 : 0) << shift);
+ --shift;
+ if (shift == 0) {
+ header.write(cache);
+ shift = 7;
+ cache = 0;
+ }
+ }
+ if (length > 0 && shift > 0) {
+ header.write(cache);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSevenEmptyFiles() throws Exception {
+ testCompress252(7, 0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public BZip2CompressorInputStream(final InputStream in, final boolean decompressConcatenated) throws IOException {
+ this.in = in;
+ this.decompressConcatenated = decompressConcatenated;
+
+ init(true);
+ initBlock();
+ setupBlock();
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int read0() throws IOException {
+ final int retChar = this.currentChar;
+ switch (currentState) {
+ case EOF:
+ return -1;
+
+ case START_BLOCK_STATE:
+ throw new IllegalStateException();
+
+ case RAND_PART_A_STATE:
+ throw new IllegalStateException();
+
+ case RAND_PART_B_STATE:
+ setupRandPartB();
+ break;
+
+ case RAND_PART_C_STATE:
+ setupRandPartC();
+ break;
+
+ case NO_RAND_PART_A_STATE:
+ throw new IllegalStateException();
+
+ case NO_RAND_PART_B_STATE:
+ setupNoRandPartB();
+ break;
+
+ case NO_RAND_PART_C_STATE:
+ setupNoRandPartC();
+ break;
+
+ default:
+ throw new IllegalStateException();
+ }
+ return retChar;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int setupRandPartA() throws IOException {
+ if (this.su_i2 <= this.last) {
+ this.su_chPrev = this.su_ch2;
+ int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
+ this.su_tPos = this.data.tt[this.su_tPos];
+ if (this.su_rNToGo == 0) {
+ this.su_rNToGo = Rand.rNums(this.su_rTPos) - 1;
+ if (++this.su_rTPos == 512) {
+ this.su_rTPos = 0;
+ }
+ } else {
+ this.su_rNToGo--;
+ }
+ this.su_ch2 = su_ch2Shadow ^= (this.su_rNToGo == 1) ? 1 : 0;
+ this.su_i2++;
+ this.currentChar = su_ch2Shadow;
+ this.currentState = RAND_PART_B_STATE;
+ this.crc.updateCRC(su_ch2Shadow);
+ return su_ch2Shadow;
+ } else {
+ endBlock();
+ initBlock();
+ return setupBlock();
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int setupNoRandPartA() throws IOException {
+ if (this.su_i2 <= this.last) {
+ this.su_chPrev = this.su_ch2;
+ int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
+ this.su_ch2 = su_ch2Shadow;
+ this.su_tPos = this.data.tt[this.su_tPos];
+ this.su_i2++;
+ this.currentChar = su_ch2Shadow;
+ this.currentState = NO_RAND_PART_B_STATE;
+ this.crc.updateCRC(su_ch2Shadow);
+ return su_ch2Shadow;
+ } else {
+ this.currentState = NO_RAND_PART_A_STATE;
+ endBlock();
+ initBlock();
+ return setupBlock();
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int setupRandPartC() throws IOException {
+ if (this.su_j2 < this.su_z) {
+ this.currentChar = this.su_ch2;
+ this.crc.updateCRC(this.su_ch2);
+ this.su_j2++;
+ return this.su_ch2;
+ } else {
+ this.currentState = RAND_PART_A_STATE;
+ this.su_i2++;
+ this.su_count = 0;
+ return setupRandPartA();
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int setupNoRandPartC() throws IOException {
+ if (this.su_j2 < this.su_z) {
+ int su_ch2Shadow = this.su_ch2;
+ this.currentChar = su_ch2Shadow;
+ this.crc.updateCRC(su_ch2Shadow);
+ this.su_j2++;
+ this.currentState = NO_RAND_PART_C_STATE;
+ return su_ch2Shadow;
+ } else {
+ this.su_i2++;
+ this.su_count = 0;
+ return setupNoRandPartA();
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testPartialReadTruncatedData() throws IOException {
+ //with BZ2File(self.filename) as f:
+ // self.assertEqual(f.read(len(self.TEXT)), self.TEXT)
+ // self.assertRaises(EOFError, f.read, 1)
+
+ final int length = TEXT.length();
+ ByteBuffer buffer = ByteBuffer.allocate(length);
+ bz2Channel.read(buffer);
+
+ assertArrayEquals(Arrays.copyOfRange(TEXT.getBytes(), 0, length),
+ buffer.array());
+
+ // subsequent read should throw
+ buffer = ByteBuffer.allocate(1);
+ try {
+ bz2Channel.read(buffer);
+ Assert.fail(""The read should have thrown."");
+ } catch (IOException e) {
+ // pass
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ InputStream decode(final InputStream in, final Coder coder,
+ byte[] password) throws IOException {
+ byte propsByte = coder.properties[0];
+ long dictSize = coder.properties[1];
+ for (int i = 1; i < 4; i++) {
+ dictSize |= (coder.properties[i + 1] << (8 * i));
+ }
+ if (dictSize > LZMAInputStream.DICT_SIZE_MAX) {
+ throw new IOException(""Dictionary larger than 4GiB maximum size"");
+ }
+ return new LZMAInputStream(in, -1, propsByte, (int) dictSize);
+ }
+
+// Test Case
+[/INST]
+ public void testCompressedHeaderWithNonDefaultDictionarySize() throws Exception {
+ SevenZFile sevenZFile = new SevenZFile(getFile(""COMPRESS-256.7z""));
+ try {
+ int count = 0;
+ while (sevenZFile.getNextEntry() != null) {
+ count++;
+ }
+ assertEquals(446, count);
+ } finally {
+ sevenZFile.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long parseOctal(final byte[] buffer, final int offset, final int length) {
+ long result = 0;
+ int end = offset + length;
+ int start = offset;
+
+ if (length < 2){
+ throw new IllegalArgumentException(""Length ""+length+"" must be at least 2"");
+ }
+
+ if (buffer[start] == 0) {
+ return 0L;
+ }
+
+ // Skip leading spaces
+ while (start < end){
+ if (buffer[start] == ' '){
+ start++;
+ } else {
+ break;
+ }
+ }
+
+ // Trim all trailing NULs and spaces.
+ // The ustar and POSIX tar specs require a trailing NUL or
+ // space but some implementations use the extra digit for big
+ // sizes/uids/gids ...
+ byte trailer = buffer[end - 1];
+ if (trailer == 0 || trailer == ' '){
+ end--;
+ } else {
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, end-1, trailer));
+ }
+ trailer = buffer[end - 1];
+ while (start < end - 1 && (trailer == 0 || trailer == ' ')) {
+ end--;
+ trailer = buffer[end - 1];
+ }
+
+ for ( ;start < end; start++) {
+ final byte currentByte = buffer[start];
+ // CheckStyle:MagicNumber OFF
+ if (currentByte < '0' || currentByte > '7'){
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, currentByte));
+ }
+ result = (result << 3) + (currentByte - '0'); // convert from ASCII
+ // CheckStyle:MagicNumber ON
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testParseOctal() throws Exception{
+ long value;
+ byte [] buffer;
+ final long MAX_OCTAL = 077777777777L; // Allowed 11 digits
+ final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations
+ final String maxOctal = ""777777777777""; // Maximum valid octal
+ buffer = maxOctal.getBytes(CharsetNames.UTF_8);
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL_OVERFLOW, value);
+ buffer[buffer.length - 1] = ' ';
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL, value);
+ buffer[buffer.length-1]=0;
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL, value);
+ buffer=new byte[]{0,0};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ buffer=new byte[]{0,' '};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ZipArchiveInputStream(InputStream inputStream,
+ String encoding,
+ boolean useUnicodeExtraFields,
+ boolean allowStoredEntriesWithDataDescriptor) {
+ zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+ this.useUnicodeExtraFields = useUnicodeExtraFields;
+ in = new PushbackInputStream(inputStream, buf.capacity());
+ this.allowStoredEntriesWithDataDescriptor =
+ allowStoredEntriesWithDataDescriptor;
+ // haven't read anything so far
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testReadingOfFirstStoredEntry() throws Exception {
+ ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-264.zip"")));
+
+ try {
+ ZipArchiveEntry ze = in.getNextZipEntry();
+ assertEquals(5, ze.getSize());
+ assertArrayEquals(new byte[] {'d', 'a', 't', 'a', '\n'},
+ IOUtils.toByteArray(in));
+ } finally {
+ in.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long skip(InputStream input, long numToSkip) throws IOException {
+ long available = numToSkip;
+ while (numToSkip > 0) {
+ long skipped = input.skip(numToSkip);
+ if (skipped == 0) {
+ break;
+ }
+ numToSkip -= skipped;
+ }
+
+ return available - numToSkip;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void skipUsingRead() throws Exception {
+ skip(new StreamWrapper() {
+ public InputStream wrap(InputStream toWrap) {
+ return new FilterInputStream(toWrap) {
+ public long skip(long s) {
+ return 0;
+ }
+ };
+ }
+ });
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long parseOctal(final byte[] buffer, final int offset, final int length) {
+ long result = 0;
+ int end = offset + length;
+ int start = offset;
+
+ if (length < 2){
+ throw new IllegalArgumentException(""Length ""+length+"" must be at least 2"");
+ }
+
+ if (buffer[start] == 0) {
+ return 0L;
+ }
+
+ // Skip leading spaces
+ while (start < end){
+ if (buffer[start] == ' '){
+ start++;
+ } else {
+ break;
+ }
+ }
+
+ // Trim all trailing NULs and spaces.
+ // The ustar and POSIX tar specs require a trailing NUL or
+ // space but some implementations use the extra digit for big
+ // sizes/uids/gids ...
+ byte trailer = buffer[end - 1];
+ while (start < end && (trailer == 0 || trailer == ' ')) {
+ end--;
+ trailer = buffer[end - 1];
+ }
+ if (start == end) {
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, trailer));
+ }
+
+ for ( ;start < end; start++) {
+ final byte currentByte = buffer[start];
+ // CheckStyle:MagicNumber OFF
+ if (currentByte < '0' || currentByte > '7'){
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, currentByte));
+ }
+ result = (result << 3) + (currentByte - '0'); // convert from ASCII
+ // CheckStyle:MagicNumber ON
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testParseOctal() throws Exception{
+ long value;
+ byte [] buffer;
+ final long MAX_OCTAL = 077777777777L; // Allowed 11 digits
+ final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations
+ final String maxOctal = ""777777777777""; // Maximum valid octal
+ buffer = maxOctal.getBytes(CharsetNames.UTF_8);
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL_OVERFLOW, value);
+ buffer[buffer.length - 1] = ' ';
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL, value);
+ buffer[buffer.length-1]=0;
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL, value);
+ buffer=new byte[]{0,0};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ buffer=new byte[]{0,' '};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ buffer=new byte[]{' ',0};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read(byte[] buf, int offset, int numToRead) throws IOException {
+ int totalRead = 0;
+
+ if (hasHitEOF || entryOffset >= entrySize) {
+ return -1;
+ }
+
+ if (currEntry == null) {
+ throw new IllegalStateException(""No current tar entry"");
+ }
+
+ numToRead = Math.min(numToRead, available());
+
+ totalRead = is.read(buf, offset, numToRead);
+ count(totalRead);
+
+ if (totalRead == -1) {
+ hasHitEOF = true;
+ } else {
+ entryOffset += totalRead;
+ }
+
+ return totalRead;
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = IOException.class)
+ public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
+ File dir = mkdir(""COMPRESS-279"");
+ TarArchiveInputStream is = getTestStream(""/COMPRESS-279.tar"");
+ FileOutputStream out = null;
+ try {
+ TarArchiveEntry entry = is.getNextTarEntry();
+ int count = 0;
+ while (entry != null) {
+ out = new FileOutputStream(new File(dir, String.valueOf(count)));
+ IOUtils.copy(is, out);
+ out.close();
+ out = null;
+ count++;
+ entry = is.getNextTarEntry();
+ }
+ } finally {
+ is.close();
+ if (out != null) {
+ out.close();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public DumpArchiveInputStream(InputStream is, String encoding)
+ throws ArchiveException {
+ this.raw = new TapeInputStream(is);
+ this.hasHitEOF = false;
+ this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+
+ try {
+ // read header, verify it's a dump archive.
+ byte[] headerBytes = raw.readRecord();
+
+ if (!DumpArchiveUtil.verify(headerBytes)) {
+ throw new UnrecognizedFormatException();
+ }
+
+ // get summary information
+ summary = new DumpArchiveSummary(headerBytes, this.zipEncoding);
+
+ // reset buffer with actual block size.
+ raw.resetBlockSize(summary.getNTRec(), summary.isCompressed());
+
+ // allocate our read buffer.
+ blockBuffer = new byte[4 * DumpArchiveConstants.TP_SIZE];
+
+ // skip past CLRI and BITS segments since we don't handle them yet.
+ readCLRI();
+ readBITS();
+ } catch (IOException ex) {
+ throw new ArchiveException(ex.getMessage(), ex);
+ }
+
+ // put in a dummy record for the root node.
+ Dirent root = new Dirent(2, 2, 4, ""."");
+ names.put(2, root);
+
+ // use priority based on queue to ensure parent directories are
+ // released first.
+ queue = new PriorityQueue(10,
+ new Comparator() {
+ public int compare(DumpArchiveEntry p, DumpArchiveEntry q) {
+ if (p.getOriginalName() == null || q.getOriginalName() == null) {
+ return Integer.MAX_VALUE;
+ }
+
+ return p.getOriginalName().compareTo(q.getOriginalName());
+ }
+ });
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public TarArchiveInputStream(InputStream is, int blockSize, int recordSize,
+ String encoding) {
+ this.is = is;
+ this.hasHitEOF = false;
+ this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+ this.recordSize = recordSize;
+ this.blockSize = blockSize;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public CpioArchiveOutputStream(final OutputStream out, final short format,
+ final int blockSize, final String encoding) {
+ this.out = out;
+ switch (format) {
+ case FORMAT_NEW:
+ case FORMAT_NEW_CRC:
+ case FORMAT_OLD_ASCII:
+ case FORMAT_OLD_BINARY:
+ break;
+ default:
+ throw new IllegalArgumentException(""Unknown format: ""+format);
+
+ }
+ this.entryFormat = format;
+ this.blockSize = blockSize;
+ this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public CpioArchiveInputStream(final InputStream in, int blockSize, String encoding) {
+ this.in = in;
+ this.blockSize = blockSize;
+ this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public TarArchiveOutputStream(OutputStream os, int blockSize,
+ int recordSize, String encoding) {
+ out = new CountingOutputStream(os);
+ this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+
+ this.assemLen = 0;
+ this.assemBuf = new byte[recordSize];
+ this.recordBuf = new byte[recordSize];
+ this.recordSize = recordSize;
+ this.recordsPerBlock = blockSize / recordSize;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ZipArchiveInputStream(InputStream inputStream,
+ String encoding,
+ boolean useUnicodeExtraFields,
+ boolean allowStoredEntriesWithDataDescriptor) {
+ zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
+ this.useUnicodeExtraFields = useUnicodeExtraFields;
+ in = new PushbackInputStream(inputStream, buf.capacity());
+ this.allowStoredEntriesWithDataDescriptor =
+ allowStoredEntriesWithDataDescriptor;
+ // haven't read anything so far
+ buf.limit(0);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ArchiveOutputStream createArchiveOutputStream(
+ final String archiverName, final OutputStream out)
+ throws ArchiveException {
+ if (archiverName == null) {
+ throw new IllegalArgumentException(""Archivername must not be null."");
+ }
+ if (out == null) {
+ throw new IllegalArgumentException(""OutputStream must not be null."");
+ }
+
+ if (AR.equalsIgnoreCase(archiverName)) {
+ return new ArArchiveOutputStream(out);
+ }
+ if (ZIP.equalsIgnoreCase(archiverName)) {
+ ZipArchiveOutputStream zip = new ZipArchiveOutputStream(out);
+ if (entryEncoding != null) {
+ zip.setEncoding(entryEncoding);
+ }
+ return zip;
+ }
+ if (TAR.equalsIgnoreCase(archiverName)) {
+ if (entryEncoding != null) {
+ return new TarArchiveOutputStream(out, entryEncoding);
+ } else {
+ return new TarArchiveOutputStream(out);
+ }
+ }
+ if (JAR.equalsIgnoreCase(archiverName)) {
+ return new JarArchiveOutputStream(out);
+ }
+ if (CPIO.equalsIgnoreCase(archiverName)) {
+ if (entryEncoding != null) {
+ return new CpioArchiveOutputStream(out, entryEncoding);
+ } else {
+ return new CpioArchiveOutputStream(out);
+ }
+ }
+ if (SEVEN_Z.equalsIgnoreCase(archiverName)) {
+ throw new StreamingNotSupportedException(SEVEN_Z);
+ }
+ throw new ArchiveException(""Archiver: "" + archiverName + "" not found."");
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ArchiveInputStream createArchiveInputStream(final InputStream in)
+ throws ArchiveException {
+ if (in == null) {
+ throw new IllegalArgumentException(""Stream must not be null."");
+ }
+
+ if (!in.markSupported()) {
+ throw new IllegalArgumentException(""Mark is not supported."");
+ }
+
+ final byte[] signature = new byte[12];
+ in.mark(signature.length);
+ try {
+ int signatureLength = IOUtils.readFully(in, signature);
+ in.reset();
+ if (ZipArchiveInputStream.matches(signature, signatureLength)) {
+ if (entryEncoding != null) {
+ return new ZipArchiveInputStream(in, entryEncoding);
+ } else {
+ return new ZipArchiveInputStream(in);
+ }
+ } else if (JarArchiveInputStream.matches(signature, signatureLength)) {
+ if (entryEncoding != null) {
+ return new JarArchiveInputStream(in, entryEncoding);
+ } else {
+ return new JarArchiveInputStream(in);
+ }
+ } else if (ArArchiveInputStream.matches(signature, signatureLength)) {
+ return new ArArchiveInputStream(in);
+ } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {
+ if (entryEncoding != null) {
+ return new CpioArchiveInputStream(in, entryEncoding);
+ } else {
+ return new CpioArchiveInputStream(in);
+ }
+ } else if (ArjArchiveInputStream.matches(signature, signatureLength)) {
+ return new ArjArchiveInputStream(in);
+ } else if (SevenZFile.matches(signature, signatureLength)) {
+ throw new StreamingNotSupportedException(SEVEN_Z);
+ }
+
+ // Dump needs a bigger buffer to check the signature;
+ final byte[] dumpsig = new byte[32];
+ in.mark(dumpsig.length);
+ signatureLength = IOUtils.readFully(in, dumpsig);
+ in.reset();
+ if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {
+ return new DumpArchiveInputStream(in, entryEncoding);
+ }
+
+ // Tar needs an even bigger buffer to check the signature; read the first block
+ final byte[] tarheader = new byte[512];
+ in.mark(tarheader.length);
+ signatureLength = IOUtils.readFully(in, tarheader);
+ in.reset();
+ if (TarArchiveInputStream.matches(tarheader, signatureLength)) {
+ return new TarArchiveInputStream(in, entryEncoding);
+ }
+ // COMPRESS-117 - improve auto-recognition
+ if (signatureLength >= 512) {
+ TarArchiveInputStream tais = null;
+ try {
+ tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));
+ // COMPRESS-191 - verify the header checksum
+ if (tais.getNextTarEntry().isCheckSumOK()) {
+ return new TarArchiveInputStream(in, encoding);
+ }
+ } catch (Exception e) { // NOPMD
+ // can generate IllegalArgumentException as well
+ // as IOException
+ // autodetection, simply not a TAR
+ // ignored
+ } finally {
+ IOUtils.closeQuietly(tais);
+ }
+ }
+ } catch (IOException e) {
+ throw new ArchiveException(""Could not use reset and mark operations."", e);
+ }
+
+ throw new ArchiveException(""No Archiver found for the stream signature"");
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testEncodingInputStream() throws Exception {
+ int failed = 0;
+ for(int i = 1; i <= TESTS.length; i++) {
+ TestData test = TESTS[i-1];
+ ArchiveInputStream ais = getInputStreamFor(test.type, test.testFile, test.fac);
+ final String field = getField(ais,test.fieldName);
+ if (!eq(test.expectedEncoding,field)) {
+ System.out.println(""Failed test "" + i + "". expected: "" + test.expectedEncoding + "" actual: "" + field + "" type: "" + test.type);
+ failed++;
+ }
+ }
+ if (failed > 0) {
+ fail(""Tests failed: "" + failed);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void finish() throws IOException {
+ writeEOFRecord();
+ writeEOFRecord();
+ }
+
+// Test Case
+[/INST]
+ public void testFinish() throws Exception {
+ OutputStream out1 = new ByteArrayOutputStream();
+
+ ArchiveOutputStream aos1 = factory.createArchiveOutputStream(""zip"", out1);
+ aos1.putArchiveEntry(new ZipArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""jar"", out1);
+ aos1.putArchiveEntry(new JarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""ar"", out1);
+ aos1.putArchiveEntry(new ArArchiveEntry(""dummy"", 100));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""cpio"", out1);
+ aos1.putArchiveEntry(new CpioArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""tar"", out1);
+ aos1.putArchiveEntry(new TarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void putArchiveEntry(ArchiveEntry archiveEntry) throws IOException {
+ TarArchiveEntry entry = (TarArchiveEntry) archiveEntry;
+ if (entry.getName().length() >= TarConstants.NAMELEN) {
+
+ if (longFileMode == LONGFILE_GNU) {
+ // create a TarEntry for the LongLink, the contents
+ // of which are the entry's name
+ TarArchiveEntry longLinkEntry = new TarArchiveEntry(TarConstants.GNU_LONGLINK,
+ TarConstants.LF_GNUTYPE_LONGNAME);
+
+ final byte[] nameBytes = entry.getName().getBytes(); // TODO is it correct to use the default charset here?
+ longLinkEntry.setSize(nameBytes.length + 1); // +1 for NUL
+ putArchiveEntry(longLinkEntry);
+ write(nameBytes);
+ write(0); // NUL terminator
+ closeArchiveEntry();
+ } else if (longFileMode != LONGFILE_TRUNCATE) {
+ throw new RuntimeException(""file name '"" + entry.getName()
+ + ""' is too long ( > ""
+ + TarConstants.NAMELEN + "" bytes)"");
+ }
+ }
+
+ entry.writeEntryHeader(recordBuf);
+ buffer.writeRecord(recordBuf);
+
+ currBytes = 0;
+
+ if (entry.isDirectory()) {
+ currSize = 0;
+ } else {
+ currSize = entry.getSize();
+ }
+ currName = entry.getName();
+ }
+
+// Test Case
+[/INST]
+ public void testFinish() throws Exception {
+ OutputStream out1 = new ByteArrayOutputStream();
+
+ ArchiveOutputStream aos1 = factory.createArchiveOutputStream(""zip"", out1);
+ aos1.putArchiveEntry(new ZipArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""jar"", out1);
+ aos1.putArchiveEntry(new JarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""ar"", out1);
+ aos1.putArchiveEntry(new ArArchiveEntry(""dummy"", 100));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""cpio"", out1);
+ aos1.putArchiveEntry(new CpioArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""tar"", out1);
+ aos1.putArchiveEntry(new TarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void closeArchiveEntry() throws IOException {
+ if (assemLen > 0) {
+ for (int i = assemLen; i < assemBuf.length; ++i) {
+ assemBuf[i] = 0;
+ }
+
+ buffer.writeRecord(assemBuf);
+
+ currBytes += assemLen;
+ assemLen = 0;
+ }
+
+ if (currBytes < currSize) {
+ throw new IOException(""entry '"" + currName + ""' closed at '""
+ + currBytes
+ + ""' before the '"" + currSize
+ + ""' bytes specified in the header were written"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testFinish() throws Exception {
+ OutputStream out1 = new ByteArrayOutputStream();
+
+ ArchiveOutputStream aos1 = factory.createArchiveOutputStream(""zip"", out1);
+ aos1.putArchiveEntry(new ZipArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""jar"", out1);
+ aos1.putArchiveEntry(new JarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""ar"", out1);
+ aos1.putArchiveEntry(new ArArchiveEntry(""dummy"", 100));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""cpio"", out1);
+ aos1.putArchiveEntry(new CpioArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""tar"", out1);
+ aos1.putArchiveEntry(new TarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testFinish() throws Exception {
+ OutputStream out1 = new ByteArrayOutputStream();
+
+ ArchiveOutputStream aos1 = factory.createArchiveOutputStream(""zip"", out1);
+ aos1.putArchiveEntry(new ZipArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""jar"", out1);
+ aos1.putArchiveEntry(new JarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""ar"", out1);
+ aos1.putArchiveEntry(new ArArchiveEntry(""dummy"", 100));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""cpio"", out1);
+ aos1.putArchiveEntry(new CpioArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+
+ aos1 = factory.createArchiveOutputStream(""tar"", out1);
+ aos1.putArchiveEntry(new TarArchiveEntry(""dummy""));
+ try {
+ aos1.finish();
+ fail(""After putArchive should follow closeArchive"");
+ } catch (IOException io) {
+ // Exception expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read(final byte[] dest, final int offs, final int len)
+ throws IOException {
+ if (offs < 0) {
+ throw new IndexOutOfBoundsException(""offs("" + offs + "") < 0."");
+ }
+ if (len < 0) {
+ throw new IndexOutOfBoundsException(""len("" + len + "") < 0."");
+ }
+ if (offs + len > dest.length) {
+ throw new IndexOutOfBoundsException(""offs("" + offs + "") + len(""
+ + len + "") > dest.length("" + dest.length + "")."");
+ }
+ if (this.in == null) {
+ throw new IOException(""stream closed"");
+ }
+
+ final int hi = offs + len;
+ int destOffs = offs;
+ int b;
+ while (destOffs < hi && ((b = read0()) >= 0)) {
+ dest[destOffs++] = (byte) b;
+ count(1);
+ }
+
+ int c = (destOffs == offs) ? -1 : (destOffs - offs);
+ return c;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void readOfLength0ShouldReturn0() throws Exception {
+ // Create a big random piece of data
+ byte[] rawData = new byte[1048576];
+ for (int i=0; i < rawData.length; ++i) {
+ rawData[i] = (byte) Math.floor(Math.random()*256);
+ }
+
+ // Compress it
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);
+ bzipOut.write(rawData);
+ bzipOut.flush();
+ bzipOut.close();
+ baos.flush();
+ baos.close();
+
+ // Try to read it back in
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);
+ byte[] buffer = new byte[1024];
+ Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
+ Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));
+ Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
+ bzipIn.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long parseOctal(final byte[] buffer, final int offset, final int length) {
+ long result = 0;
+ int end = offset + length;
+ int start = offset;
+
+ if (length < 2){
+ throw new IllegalArgumentException(""Length ""+length+"" must be at least 2"");
+ }
+
+ if (buffer[start] == 0) {
+ return 0L;
+ }
+
+ // Skip leading spaces
+ while (start < end){
+ if (buffer[start] == ' '){
+ start++;
+ } else {
+ break;
+ }
+ }
+
+ // Trim all trailing NULs and spaces.
+ // The ustar and POSIX tar specs require a trailing NUL or
+ // space but some implementations use the extra digit for big
+ // sizes/uids/gids ...
+ byte trailer = buffer[end - 1];
+ while (start < end && (trailer == 0 || trailer == ' ')) {
+ end--;
+ trailer = buffer[end - 1];
+ }
+
+ for ( ;start < end; start++) {
+ final byte currentByte = buffer[start];
+ if (currentByte == 0) {
+ break;
+ }
+ // CheckStyle:MagicNumber OFF
+ if (currentByte < '0' || currentByte > '7'){
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, currentByte));
+ }
+ result = (result << 3) + (currentByte - '0'); // convert from ASCII
+ // CheckStyle:MagicNumber ON
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCOMPRESS178() throws Exception {
+ final File input = getFile(""COMPRESS-178.tar"");
+ final InputStream is = new FileInputStream(input);
+ final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(""tar"", is);
+ try {
+ in.getNextEntry();
+ fail(""Expected IOException"");
+ } catch (IOException e) {
+ Throwable t = e.getCause();
+ assertTrue(""Expected cause = IllegalArgumentException"", t instanceof IllegalArgumentException);
+ }
+ in.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void applyPaxHeadersToCurrentEntry(Map headers) {
+ /*
+ * The following headers are defined for Pax.
+ * atime, ctime, charset: cannot use these without changing TarArchiveEntry fields
+ * mtime
+ * comment
+ * gid, gname
+ * linkpath
+ * size
+ * uid,uname
+ * SCHILY.devminor, SCHILY.devmajor: don't have setters/getters for those
+ */
+ for (Entry ent : headers.entrySet()){
+ String key = ent.getKey();
+ String val = ent.getValue();
+ if (""path"".equals(key)){
+ currEntry.setName(val);
+ } else if (""linkpath"".equals(key)){
+ currEntry.setLinkName(val);
+ } else if (""gid"".equals(key)){
+ currEntry.setGroupId(Integer.parseInt(val));
+ } else if (""gname"".equals(key)){
+ currEntry.setGroupName(val);
+ } else if (""uid"".equals(key)){
+ currEntry.setUserId(Integer.parseInt(val));
+ } else if (""uname"".equals(key)){
+ currEntry.setUserName(val);
+ } else if (""size"".equals(key)){
+ currEntry.setSize(Long.parseLong(val));
+ } else if (""mtime"".equals(key)){
+ currEntry.setModTime((long) (Double.parseDouble(val) * 1000));
+ } else if (""SCHILY.devminor"".equals(key)){
+ currEntry.setDevMinor(Integer.parseInt(val));
+ } else if (""SCHILY.devmajor"".equals(key)){
+ currEntry.setDevMajor(Integer.parseInt(val));
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void shouldReadBigGid() throws Exception {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
+ tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
+ TarArchiveEntry t = new TarArchiveEntry(""name"");
+ t.setGroupId(4294967294l);
+ t.setSize(1);
+ tos.putArchiveEntry(t);
+ tos.write(30);
+ tos.closeArchiveEntry();
+ tos.close();
+ byte[] data = bos.toByteArray();
+ ByteArrayInputStream bis = new ByteArrayInputStream(data);
+ TarArchiveInputStream tis =
+ new TarArchiveInputStream(bis);
+ t = tis.getNextTarEntry();
+ assertEquals(4294967294l, t.getLongGroupId());
+ tis.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testDetection() throws Exception {
+ CompressorInputStream bzip2 = getStreamFor(""bla.txt.bz2"");
+ assertNotNull(bzip2);
+ assertTrue(bzip2 instanceof BZip2CompressorInputStream);
+
+ CompressorInputStream gzip = getStreamFor(""bla.tgz"");
+ assertNotNull(gzip);
+ assertTrue(gzip instanceof GzipCompressorInputStream);
+
+ CompressorInputStream pack200 = getStreamFor(""bla.pack"");
+ assertNotNull(pack200);
+ assertTrue(pack200 instanceof Pack200CompressorInputStream);
+
+ CompressorInputStream xz = getStreamFor(""bla.tar.xz"");
+ assertNotNull(xz);
+ assertTrue(xz instanceof XZCompressorInputStream);
+
+ CompressorInputStream zlib = getStreamFor(""bla.tar.deflatez"");
+ assertNotNull(zlib);
+ assertTrue(zlib instanceof DeflateCompressorInputStream);
+
+ try {
+ factory.createCompressorInputStream(new ByteArrayInputStream(new byte[0]));
+ fail(""No exception thrown for an empty input stream"");
+ } catch (CompressorException e) {
+ // expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testDetection() throws Exception {
+ CompressorInputStream bzip2 = getStreamFor(""bla.txt.bz2"");
+ assertNotNull(bzip2);
+ assertTrue(bzip2 instanceof BZip2CompressorInputStream);
+
+ CompressorInputStream gzip = getStreamFor(""bla.tgz"");
+ assertNotNull(gzip);
+ assertTrue(gzip instanceof GzipCompressorInputStream);
+
+ CompressorInputStream pack200 = getStreamFor(""bla.pack"");
+ assertNotNull(pack200);
+ assertTrue(pack200 instanceof Pack200CompressorInputStream);
+
+ CompressorInputStream xz = getStreamFor(""bla.tar.xz"");
+ assertNotNull(xz);
+ assertTrue(xz instanceof XZCompressorInputStream);
+
+ CompressorInputStream zlib = getStreamFor(""bla.tar.deflatez"");
+ assertNotNull(zlib);
+ assertTrue(zlib instanceof DeflateCompressorInputStream);
+
+ try {
+ factory.createCompressorInputStream(new ByteArrayInputStream(new byte[0]));
+ fail(""No exception thrown for an empty input stream"");
+ } catch (CompressorException e) {
+ // expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testDetection() throws Exception {
+ CompressorInputStream bzip2 = getStreamFor(""bla.txt.bz2"");
+ assertNotNull(bzip2);
+ assertTrue(bzip2 instanceof BZip2CompressorInputStream);
+
+ CompressorInputStream gzip = getStreamFor(""bla.tgz"");
+ assertNotNull(gzip);
+ assertTrue(gzip instanceof GzipCompressorInputStream);
+
+ CompressorInputStream pack200 = getStreamFor(""bla.pack"");
+ assertNotNull(pack200);
+ assertTrue(pack200 instanceof Pack200CompressorInputStream);
+
+ CompressorInputStream xz = getStreamFor(""bla.tar.xz"");
+ assertNotNull(xz);
+ assertTrue(xz instanceof XZCompressorInputStream);
+
+ CompressorInputStream zlib = getStreamFor(""bla.tar.deflatez"");
+ assertNotNull(zlib);
+ assertTrue(zlib instanceof DeflateCompressorInputStream);
+
+ try {
+ factory.createCompressorInputStream(new ByteArrayInputStream(new byte[0]));
+ fail(""No exception thrown for an empty input stream"");
+ } catch (CompressorException e) {
+ // expected
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ZipShort getCentralDirectoryLength() {
+ return getLocalFileDataLength();
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testParseReparse() throws ZipException {
+
+ // Version=1, Len=0, Len=0.
+ final byte[] ZERO_LEN = {1, 0, 0};
+
+ // Version=1, Len=1, zero, Len=1, zero.
+ final byte[] ZERO_UID_GID = {1, 1, 0, 1, 0};
+
+ // Version=1, Len=1, one, Len=1, one
+ final byte[] ONE_UID_GID = {1, 1, 1, 1, 1};
+
+ // Version=1, Len=2, one thousand, Len=2, one thousand
+ final byte[] ONE_THOUSAND_UID_GID = {1, 2, -24, 3, 2, -24, 3};
+
+ // (2^32 - 2). I guess they avoid (2^32 - 1) since it's identical to -1 in
+ // two's complement, and -1 often has a special meaning.
+ final byte[] UNIX_MAX_UID_GID = {1, 4, -2, -1, -1, -1, 4, -2, -1, -1, -1};
+
+ // Version=1, Len=5, 2^32, Len=5, 2^32 + 1
+ // Esoteric test: can we handle 40 bit numbers?
+ final byte[] LENGTH_5 = {1, 5, 0, 0, 0, 0, 1, 5, 1, 0, 0, 0, 1};
+
+ // Version=1, Len=8, 2^63 - 2, Len=8, 2^63 - 1
+ // Esoteric test: can we handle 64 bit numbers?
+ final byte[] LENGTH_8 = {1, 8, -2, -1, -1, -1, -1, -1, -1, 127, 8, -1, -1, -1, -1, -1, -1, -1, 127};
+
+ final long TWO_TO_32 = 0x100000000L;
+ final long MAX = TWO_TO_32 - 2;
+
+ parseReparse(0, 0, ZERO_LEN, 0, 0);
+ parseReparse(0, 0, ZERO_UID_GID, 0, 0);
+ parseReparse(1, 1, ONE_UID_GID, 1, 1);
+ parseReparse(1000, 1000, ONE_THOUSAND_UID_GID, 1000, 1000);
+ parseReparse(MAX, MAX, UNIX_MAX_UID_GID, MAX, MAX);
+ parseReparse(-2, -2, UNIX_MAX_UID_GID, MAX, MAX);
+ parseReparse(TWO_TO_32, TWO_TO_32 + 1, LENGTH_5, TWO_TO_32, TWO_TO_32 + 1);
+ parseReparse(Long.MAX_VALUE - 1, Long.MAX_VALUE, LENGTH_8, Long.MAX_VALUE - 1, Long.MAX_VALUE);
+
+ // We never emit this, but we should be able to parse it:
+ final byte[] SPURIOUS_ZEROES_1 = {1, 4, -1, 0, 0, 0, 4, -128, 0, 0, 0};
+ final byte[] EXPECTED_1 = {1, 1, -1, 1, -128};
+ xf.parseFromLocalFileData(SPURIOUS_ZEROES_1, 0, SPURIOUS_ZEROES_1.length);
+
+ assertEquals(255, xf.getUID());
+ assertEquals(128, xf.getGID());
+ assertTrue(Arrays.equals(EXPECTED_1, xf.getLocalFileDataData()));
+
+ final byte[] SPURIOUS_ZEROES_2 = {1, 4, -1, -1, 0, 0, 4, 1, 2, 0, 0};
+ final byte[] EXPECTED_2 = {1, 2, -1, -1, 2, 1, 2};
+ xf.parseFromLocalFileData(SPURIOUS_ZEROES_2, 0, SPURIOUS_ZEROES_2.length);
+
+ assertEquals(65535, xf.getUID());
+ assertEquals(513, xf.getGID());
+ assertTrue(Arrays.equals(EXPECTED_2, xf.getLocalFileDataData()));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testParseReparse() throws ZipException {
+
+ // Version=1, Len=0, Len=0.
+ final byte[] ZERO_LEN = {1, 0, 0};
+
+ // Version=1, Len=1, zero, Len=1, zero.
+ final byte[] ZERO_UID_GID = {1, 1, 0, 1, 0};
+
+ // Version=1, Len=1, one, Len=1, one
+ final byte[] ONE_UID_GID = {1, 1, 1, 1, 1};
+
+ // Version=1, Len=2, one thousand, Len=2, one thousand
+ final byte[] ONE_THOUSAND_UID_GID = {1, 2, -24, 3, 2, -24, 3};
+
+ // (2^32 - 2). I guess they avoid (2^32 - 1) since it's identical to -1 in
+ // two's complement, and -1 often has a special meaning.
+ final byte[] UNIX_MAX_UID_GID = {1, 4, -2, -1, -1, -1, 4, -2, -1, -1, -1};
+
+ // Version=1, Len=5, 2^32, Len=5, 2^32 + 1
+ // Esoteric test: can we handle 40 bit numbers?
+ final byte[] LENGTH_5 = {1, 5, 0, 0, 0, 0, 1, 5, 1, 0, 0, 0, 1};
+
+ // Version=1, Len=8, 2^63 - 2, Len=8, 2^63 - 1
+ // Esoteric test: can we handle 64 bit numbers?
+ final byte[] LENGTH_8 = {1, 8, -2, -1, -1, -1, -1, -1, -1, 127, 8, -1, -1, -1, -1, -1, -1, -1, 127};
+
+ final long TWO_TO_32 = 0x100000000L;
+ final long MAX = TWO_TO_32 - 2;
+
+ parseReparse(0, 0, ZERO_LEN, 0, 0);
+ parseReparse(0, 0, ZERO_UID_GID, 0, 0);
+ parseReparse(1, 1, ONE_UID_GID, 1, 1);
+ parseReparse(1000, 1000, ONE_THOUSAND_UID_GID, 1000, 1000);
+ parseReparse(MAX, MAX, UNIX_MAX_UID_GID, MAX, MAX);
+ parseReparse(-2, -2, UNIX_MAX_UID_GID, MAX, MAX);
+ parseReparse(TWO_TO_32, TWO_TO_32 + 1, LENGTH_5, TWO_TO_32, TWO_TO_32 + 1);
+ parseReparse(Long.MAX_VALUE - 1, Long.MAX_VALUE, LENGTH_8, Long.MAX_VALUE - 1, Long.MAX_VALUE);
+
+ // We never emit this, but we should be able to parse it:
+ final byte[] SPURIOUS_ZEROES_1 = {1, 4, -1, 0, 0, 0, 4, -128, 0, 0, 0};
+ final byte[] EXPECTED_1 = {1, 1, -1, 1, -128};
+ xf.parseFromLocalFileData(SPURIOUS_ZEROES_1, 0, SPURIOUS_ZEROES_1.length);
+
+ assertEquals(255, xf.getUID());
+ assertEquals(128, xf.getGID());
+ assertTrue(Arrays.equals(EXPECTED_1, xf.getLocalFileDataData()));
+
+ final byte[] SPURIOUS_ZEROES_2 = {1, 4, -1, -1, 0, 0, 4, 1, 2, 0, 0};
+ final byte[] EXPECTED_2 = {1, 2, -1, -1, 2, 1, 2};
+ xf.parseFromLocalFileData(SPURIOUS_ZEROES_2, 0, SPURIOUS_ZEROES_2.length);
+
+ assertEquals(65535, xf.getUID());
+ assertEquals(513, xf.getGID());
+ assertTrue(Arrays.equals(EXPECTED_2, xf.getLocalFileDataData()));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static boolean verifyCheckSum(byte[] header) {
+ long storedSum = 0;
+ long unsignedSum = 0;
+ long signedSum = 0;
+
+ int digits = 0;
+ for (int i = 0; i < header.length; i++) {
+ byte b = header[i];
+ if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) {
+ if ('0' <= b && b <= '7' && digits++ < 6) {
+ storedSum = storedSum * 8 + b - '0';
+ } else if (digits > 0) {
+ digits = 6;
+ }
+ b = ' ';
+ }
+ unsignedSum += 0xff & b;
+ signedSum += b;
+ }
+ return storedSum == unsignedSum || storedSum == signedSum;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testCOMPRESS335() throws Exception {
+ final ArchiveInputStream tar = getStreamFor(""COMPRESS-335.tar"");
+ assertNotNull(tar);
+ assertTrue(tar instanceof TarArchiveInputStream);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private InputStream getCurrentStream() throws IOException {
+ if (deferredBlockStreams.isEmpty()) {
+ throw new IllegalStateException(""No current 7z entry (call getNextEntry() first)."");
+ }
+
+ while (deferredBlockStreams.size() > 1) {
+ // In solid compression mode we need to decompress all leading folder'
+ // streams to get access to an entry. We defer this until really needed
+ // so that entire blocks can be skipped without wasting time for decompression.
+ final InputStream stream = deferredBlockStreams.remove(0);
+ IOUtils.skip(stream, Long.MAX_VALUE);
+ stream.close();
+ }
+
+ return deferredBlockStreams.get(0);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void readEntriesOfSize0() throws IOException {
+ final SevenZFile sevenZFile = new SevenZFile(getFile(""COMPRESS-348.7z""));
+ try {
+ int entries = 0;
+ SevenZArchiveEntry entry = sevenZFile.getNextEntry();
+ while (entry != null) {
+ entries++;
+ int b = sevenZFile.read();
+ if (""2.txt"".equals(entry.getName()) || ""5.txt"".equals(entry.getName())) {
+ assertEquals(-1, b);
+ } else {
+ assertNotEquals(-1, b);
+ }
+ entry = sevenZFile.getNextEntry();
+ }
+ assertEquals(5, entries);
+ } finally {
+ sevenZFile.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Map parsePaxHeaders(final InputStream i)
+ throws IOException {
+ final Map headers = new HashMap(globalPaxHeaders);
+ // Format is ""length keyword=value\n"";
+ while(true){ // get length
+ int ch;
+ int len = 0;
+ int read = 0;
+ while((ch = i.read()) != -1) {
+ read++;
+ if (ch == ' '){
+ // Get keyword
+ final ByteArrayOutputStream coll = new ByteArrayOutputStream();
+ while((ch = i.read()) != -1) {
+ read++;
+ if (ch == '='){ // end of keyword
+ final String keyword = coll.toString(CharsetNames.UTF_8);
+ // Get rest of entry
+ final int restLen = len - read;
+ if (restLen == 1) { // only NL
+ headers.remove(keyword);
+ } else {
+ final byte[] rest = new byte[restLen];
+ final int got = IOUtils.readFully(i, rest);
+ if (got != restLen) {
+ throw new IOException(""Failed to read ""
+ + ""Paxheader. Expected ""
+ + restLen
+ + "" bytes, read ""
+ + got);
+ }
+ // Drop trailing NL
+ final String value = new String(rest, 0,
+ restLen - 1, CharsetNames.UTF_8);
+ headers.put(keyword, value);
+ }
+ break;
+ }
+ coll.write((byte) ch);
+ }
+ break; // Processed single header
+ }
+ len *= 10;
+ len += ch - '0';
+ }
+ if (ch == -1){ // EOF
+ break;
+ }
+ }
+ return headers;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void survivesBlankLinesInPaxHeader() throws Exception {
+ final TarArchiveInputStream is = getTestStream(""/COMPRESS-355.tar"");
+ try {
+ final TarArchiveEntry entry = is.getNextTarEntry();
+ assertEquals(""package/package.json"", entry.getName());
+ assertNull(is.getNextTarEntry());
+ } finally {
+ is.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean isDirectory() {
+ if (file != null) {
+ return file.isDirectory();
+ }
+
+ if (linkFlag == LF_DIR) {
+ return true;
+ }
+
+ if (getName().endsWith(""/"")) {
+ return true;
+ }
+
+ return false;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void survivesPaxHeaderWithNameEndingInSlash() throws Exception {
+ final TarArchiveInputStream is = getTestStream(""/COMPRESS-356.tar"");
+ try {
+ final TarArchiveEntry entry = is.getNextTarEntry();
+ assertEquals(""package/package.json"", entry.getName());
+ assertNull(is.getNextTarEntry());
+ } finally {
+ is.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static String sanitize(String s) {
+ final char[] chars = s.toCharArray();
+ final int len = chars.length;
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < len; i++) {
+ final char c = chars[i];
+ if (!Character.isISOControl(c)) {
+ Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
+ if (block != null && block != Character.UnicodeBlock.SPECIALS) {
+ sb.append(c);
+ continue;
+ }
+ }
+ sb.append('?');
+ }
+ return sb.toString();
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void sanitizeShortensString() {
+ String input = ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789"";
+ String expected = ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901..."";
+ assertEquals(expected, ArchiveUtils.sanitize(input));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void sanitizeShortensString() {
+ String input = ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789"";
+ String expected = ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901234567890123456789012345678901234567890123456789""
+ + ""012345678901..."";
+ assertEquals(expected, ArchiveUtils.sanitize(input));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ChangeSetResults perform(ArchiveInputStream in, ArchiveOutputStream out)
+ throws IOException {
+ ChangeSetResults results = new ChangeSetResults();
+
+ Set workingSet = new LinkedHashSet(changes);
+
+ for (Iterator it = workingSet.iterator(); it.hasNext();) {
+ Change change = (Change) it.next();
+
+ if (change.type() == Change.TYPE_ADD && change.isReplaceMode()) {
+ copyStream(change.getInput(), out, change.getEntry());
+ it.remove();
+ results.addedFromChangeSet(change.getEntry().getName());
+ }
+ }
+
+ ArchiveEntry entry = null;
+ while ((entry = in.getNextEntry()) != null) {
+ boolean copy = true;
+
+ for (Iterator it = workingSet.iterator(); it.hasNext();) {
+ Change change = (Change) it.next();
+
+ final int type = change.type();
+ final String name = entry.getName();
+ if (type == Change.TYPE_DELETE && name != null) {
+ if (name.equals(change.targetFile())) {
+ copy = false;
+ it.remove();
+ results.deleted(name);
+ break;
+ }
+ } else if(type == Change.TYPE_DELETE_DIR && name != null) {
+ if (name.startsWith(change.targetFile() + ""/"")) {
+ copy = false;
+ results.deleted(name);
+ break;
+ }
+ }
+ }
+
+ if (copy) {
+ if (!isDeletedLater(workingSet, entry) && !results.hasBeenAdded(entry.getName())) {
+ copyStream(in, out, entry);
+ results.addedFromStream(entry.getName());
+ }
+ }
+ }
+
+ // Adds files which hasn't been added from the original and do not have replace mode on
+ for (Iterator it = workingSet.iterator(); it.hasNext();) {
+ Change change = (Change) it.next();
+
+ if (change.type() == Change.TYPE_ADD &&
+ !change.isReplaceMode() &&
+ !results.hasBeenAdded(change.getEntry().getName())) {
+ copyStream(change.getInput(), out, change.getEntry());
+ it.remove();
+ results.addedFromChangeSet(change.getEntry().getName());
+ }
+ }
+ return results;
+ }
+
+// Test Case
+[/INST]
+ public void testJarMarker() throws IOException {
+ File testArchive = File.createTempFile(""jar-aostest"", "".jar"");
+ JarArchiveOutputStream out = null;
+ ZipFile zf = null;
+ try {
+
+ out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
+ out.putArchiveEntry(new ZipArchiveEntry(""foo/""));
+ out.closeArchiveEntry();
+ out.putArchiveEntry(new ZipArchiveEntry(""bar/""));
+ out.closeArchiveEntry();
+ out.finish();
+ out.close();
+ out = null;
+
+ zf = new ZipFile(testArchive);
+ ZipArchiveEntry ze = zf.getEntry(""foo/"");
+ assertNotNull(ze);
+ ZipExtraField[] fes = ze.getExtraFields();
+ assertEquals(1, fes.length);
+ assertTrue(fes[0] instanceof JarMarker);
+
+ ze = zf.getEntry(""bar/"");
+ assertNotNull(ze);
+ fes = ze.getExtraFields();
+ assertEquals(0, fes.length);
+ } finally {
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) { /* swallow */ }
+ }
+ ZipFile.closeQuietly(zf);
+ if (testArchive.exists()) {
+ testArchive.delete();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void close() throws IOException {
+ if (!closed) {
+ finish();
+ buffer.close();
+ out.close();
+ closed = true;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testJarMarker() throws IOException {
+ File testArchive = File.createTempFile(""jar-aostest"", "".jar"");
+ JarArchiveOutputStream out = null;
+ ZipFile zf = null;
+ try {
+
+ out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
+ out.putArchiveEntry(new ZipArchiveEntry(""foo/""));
+ out.closeArchiveEntry();
+ out.putArchiveEntry(new ZipArchiveEntry(""bar/""));
+ out.closeArchiveEntry();
+ out.finish();
+ out.close();
+ out = null;
+
+ zf = new ZipFile(testArchive);
+ ZipArchiveEntry ze = zf.getEntry(""foo/"");
+ assertNotNull(ze);
+ ZipExtraField[] fes = ze.getExtraFields();
+ assertEquals(1, fes.length);
+ assertTrue(fes[0] instanceof JarMarker);
+
+ ze = zf.getEntry(""bar/"");
+ assertNotNull(ze);
+ fes = ze.getExtraFields();
+ assertEquals(0, fes.length);
+ } finally {
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) { /* swallow */ }
+ }
+ ZipFile.closeQuietly(zf);
+ if (testArchive.exists()) {
+ testArchive.delete();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void close() throws IOException {
+ if (!this.closed) {
+ this.finish();
+ out.close();
+ this.closed = true;
+ }
+ }
+
+
+// Test Case
+[/INST]
+ public void testJarMarker() throws IOException {
+ File testArchive = File.createTempFile(""jar-aostest"", "".jar"");
+ JarArchiveOutputStream out = null;
+ ZipFile zf = null;
+ try {
+
+ out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
+ out.putArchiveEntry(new ZipArchiveEntry(""foo/""));
+ out.closeArchiveEntry();
+ out.putArchiveEntry(new ZipArchiveEntry(""bar/""));
+ out.closeArchiveEntry();
+ out.finish();
+ out.close();
+ out = null;
+
+ zf = new ZipFile(testArchive);
+ ZipArchiveEntry ze = zf.getEntry(""foo/"");
+ assertNotNull(ze);
+ ZipExtraField[] fes = ze.getExtraFields();
+ assertEquals(1, fes.length);
+ assertTrue(fes[0] instanceof JarMarker);
+
+ ze = zf.getEntry(""bar/"");
+ assertNotNull(ze);
+ fes = ze.getExtraFields();
+ assertEquals(0, fes.length);
+ } finally {
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) { /* swallow */ }
+ }
+ ZipFile.closeQuietly(zf);
+ if (testArchive.exists()) {
+ testArchive.delete();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void close() throws IOException {
+ finish();
+ if (raf != null) {
+ raf.close();
+ }
+ if (out != null) {
+ out.close();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testJarMarker() throws IOException {
+ File testArchive = File.createTempFile(""jar-aostest"", "".jar"");
+ JarArchiveOutputStream out = null;
+ ZipFile zf = null;
+ try {
+
+ out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
+ out.putArchiveEntry(new ZipArchiveEntry(""foo/""));
+ out.closeArchiveEntry();
+ out.putArchiveEntry(new ZipArchiveEntry(""bar/""));
+ out.closeArchiveEntry();
+ out.finish();
+ out.close();
+ out = null;
+
+ zf = new ZipFile(testArchive);
+ ZipArchiveEntry ze = zf.getEntry(""foo/"");
+ assertNotNull(ze);
+ ZipExtraField[] fes = ze.getExtraFields();
+ assertEquals(1, fes.length);
+ assertTrue(fes[0] instanceof JarMarker);
+
+ ze = zf.getEntry(""bar/"");
+ assertNotNull(ze);
+ fes = ze.getExtraFields();
+ assertEquals(0, fes.length);
+ } finally {
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) { /* swallow */ }
+ }
+ ZipFile.closeQuietly(zf);
+ if (testArchive.exists()) {
+ testArchive.delete();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public long readBits(final int count) throws IOException {
+ if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
+ throw new IllegalArgumentException(""count must not be negative or greater than "" + MAXIMUM_CACHE_SIZE);
+ }
+ while (bitsCachedSize < count) {
+ final long nextByte = in.read();
+ if (nextByte < 0) {
+ return nextByte;
+ }
+ if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
+ bitsCached |= (nextByte << bitsCachedSize);
+ } else {
+ bitsCached <<= 8;
+ bitsCached |= nextByte;
+ }
+ bitsCachedSize += 8;
+ }
+ // bitsCachedSize >= 57 and left-shifting it 8 bits would cause an overflow
+
+ final long bitsOut;
+ if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
+ bitsOut = (bitsCached & MASKS[count]);
+ bitsCached >>>= count;
+ } else {
+ bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
+ }
+ bitsCachedSize -= count;
+ return bitsOut;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void littleEndianWithOverflow() throws Exception {
+ ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
+ 87, // 01010111
+ 45, // 00101101
+ 66, // 01000010
+ 15, // 00001111
+ 90, // 01011010
+ 29, // 00011101
+ 88, // 01011000
+ 61, // 00111101
+ 33, // 00100001
+ 74 // 01001010
+ });
+ BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE_ENDIAN);
+ assertEquals(23, // 10111
+ bin.readBits(5));
+ assertEquals(714595605644185962l, // 0001-00111101-01011000-00011101-01011010-00001111-01000010-00101101-010
+ bin.readBits(63));
+ assertEquals(1186, // 01001010-0010
+ bin.readBits(12));
+ assertEquals(-1 , bin.readBits(1));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ZipArchiveEntry getNextZipEntry() throws IOException {
+ boolean firstEntry = true;
+ if (closed || hitCentralDirectory) {
+ return null;
+ }
+ if (current != null) {
+ closeEntry();
+ firstEntry = false;
+ }
+
+ try {
+ if (firstEntry) {
+ // split archives have a special signature before the
+ // first local file header - look for it and fail with
+ // the appropriate error message if this is a split
+ // archive.
+ readFirstLocalFileHeader(LFH_BUF);
+ } else {
+ readFully(LFH_BUF);
+ }
+ } catch (final EOFException e) {
+ return null;
+ }
+
+ final ZipLong sig = new ZipLong(LFH_BUF);
+ if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) {
+ hitCentralDirectory = true;
+ skipRemainderOfArchive();
+ }
+ if (!sig.equals(ZipLong.LFH_SIG)) {
+ return null;
+ }
+
+ int off = WORD;
+ current = new CurrentEntry();
+
+ final int versionMadeBy = ZipShort.getValue(LFH_BUF, off);
+ off += SHORT;
+ current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);
+
+ final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off);
+ final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();
+ final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;
+ current.hasDataDescriptor = gpFlag.usesDataDescriptor();
+ current.entry.setGeneralPurposeBit(gpFlag);
+
+ off += SHORT;
+
+ current.entry.setMethod(ZipShort.getValue(LFH_BUF, off));
+ off += SHORT;
+
+ final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off));
+ current.entry.setTime(time);
+ off += WORD;
+
+ ZipLong size = null, cSize = null;
+ if (!current.hasDataDescriptor) {
+ current.entry.setCrc(ZipLong.getValue(LFH_BUF, off));
+ off += WORD;
+
+ cSize = new ZipLong(LFH_BUF, off);
+ off += WORD;
+
+ size = new ZipLong(LFH_BUF, off);
+ off += WORD;
+ } else {
+ off += 3 * WORD;
+ }
+
+ final int fileNameLen = ZipShort.getValue(LFH_BUF, off);
+
+ off += SHORT;
+
+ final int extraLen = ZipShort.getValue(LFH_BUF, off);
+ off += SHORT;
+
+ final byte[] fileName = new byte[fileNameLen];
+ readFully(fileName);
+ current.entry.setName(entryEncoding.decode(fileName), fileName);
+
+ final byte[] extraData = new byte[extraLen];
+ readFully(extraData);
+ current.entry.setExtra(extraData);
+
+ if (!hasUTF8Flag && useUnicodeExtraFields) {
+ ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);
+ }
+
+ processZip64Extra(size, cSize);
+
+ if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {
+ if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) {
+ current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));
+ } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) {
+ current.in = new ExplodingInputStream(
+ current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),
+ current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),
+ new BoundedInputStream(in, current.entry.getCompressedSize()));
+ } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {
+ current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));
+ }
+ }
+
+ entriesRead++;
+ return current.entry;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testListAllFilesWithNestedArchive() throws Exception {
+ final File input = getFile(""OSX_ArchiveWithNestedArchive.zip"");
+
+ final List results = new ArrayList<>();
+ final List expectedExceptions = new ArrayList<>();
+
+ final InputStream is = new FileInputStream(input);
+ ArchiveInputStream in = null;
+ try {
+ in = new ArchiveStreamFactory().createArchiveInputStream(""zip"", is);
+
+ ZipArchiveEntry entry = null;
+ while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
+ results.add(entry.getName());
+
+ final ArchiveInputStream nestedIn = new ArchiveStreamFactory().createArchiveInputStream(""zip"", in);
+ try {
+ ZipArchiveEntry nestedEntry = null;
+ while ((nestedEntry = (ZipArchiveEntry) nestedIn.getNextEntry()) != null) {
+ results.add(nestedEntry.getName());
+ }
+ } catch (ZipException ex) {
+ // expected since you cannot create a final ArchiveInputStream from test3.xml
+ expectedExceptions.add(ex);
+ }
+ // nested stream must not be closed here
+ }
+ } finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+ is.close();
+
+ assertTrue(results.contains(""NestedArchiv.zip""));
+ assertTrue(results.contains(""test1.xml""));
+ assertTrue(results.contains(""test2.xml""));
+ assertTrue(results.contains(""test3.xml""));
+ assertEquals(1, expectedExceptions.size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean isUnixSymlink() {
+ return (getUnixMode() & UnixStat.LINK_FLAG) == UnixStat.LINK_FLAG;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception {
+ try (ZipFile zf = new ZipFile(getFile(""COMPRESS-379.jar""))) {
+ ZipArchiveEntry ze = zf.getEntry(""META-INF/maven/"");
+ assertFalse(ze.isUnixSymlink());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception {
+ try (ZipFile zf = new ZipFile(getFile(""COMPRESS-379.jar""))) {
+ ZipArchiveEntry ze = zf.getEntry(""META-INF/maven/"");
+ assertFalse(ze.isUnixSymlink());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void writeLocalFileHeader(final ZipArchiveEntry ze, final boolean phased) throws IOException {
+ final boolean encodable = zipEncoding.canEncode(ze.getName());
+ final ByteBuffer name = getName(ze);
+
+ if (createUnicodeExtraFields != UnicodeExtraFieldPolicy.NEVER) {
+ addUnicodeExtraFields(ze, encodable, name);
+ }
+
+ final long localHeaderStart = streamCompressor.getTotalBytesWritten();
+ final byte[] localHeader = createLocalFileHeader(ze, name, encodable, phased, localHeaderStart);
+ metaData.put(ze, new EntryMetaData(localHeaderStart, usesDataDescriptor(ze.getMethod())));
+ entry.localDataStart = localHeaderStart + LFH_CRC_OFFSET; // At crc offset
+ writeCounted(localHeader);
+ entry.dataStart = streamCompressor.getTotalBytesWritten();
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void doesntWriteDataDescriptorWhenAddingRawEntries() throws IOException {
+ ByteArrayOutputStream init = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(init)) {
+ zos.putArchiveEntry(new ZipArchiveEntry(""test1.txt""));
+ zos.write(""foo"".getBytes(""UTF-8""));
+ zos.closeArchiveEntry();
+ }
+
+ File f = new File(dir, ""test.zip"");
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ fos.write(init.toByteArray());
+ }
+
+ ByteArrayOutputStream o = new ByteArrayOutputStream();
+ ZipArchiveEntry zae;
+ try (ZipFile zf = new ZipFile(f);
+ ZipArchiveOutputStream zos = new ZipArchiveOutputStream(o)) {
+ zae = zf.getEntry(""test1.txt"");
+ zos.addRawArchiveEntry(zae, zf.getRawInputStream(zae));
+ }
+
+ byte[] data = o.toByteArray();
+ byte[] versionInLFH = Arrays.copyOfRange(data, 4, 6);
+ // still 2.0 because of Deflate
+ assertArrayEquals(new byte[] { 20, 0 }, versionInLFH);
+ byte[] gpbInLFH = Arrays.copyOfRange(data, 6, 8);
+ // no DD but EFS flag
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInLFH);
+
+ int cdhStart = findCentralDirectory(data);
+ byte[] versionInCDH = Arrays.copyOfRange(data, cdhStart + 6, cdhStart + 8);
+ assertArrayEquals(new byte[] { 20, 0 }, versionInCDH);
+ byte[] gpbInCDH = Arrays.copyOfRange(data, cdhStart + 8, cdhStart + 10);
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInCDH);
+
+ int ddStart = cdhStart - 16;
+ assertNotEquals(ZipLong.DD_SIG, new ZipLong(data, ddStart));
+ long crcFromLFH = ZipLong.getValue(data, 14);
+ long cSizeFromLFH = ZipLong.getValue(data, 18);
+ long sizeFromLFH = ZipLong.getValue(data, 22);
+ assertEquals(3, sizeFromLFH);
+
+ long crcFromCDH = ZipLong.getValue(data, cdhStart + 16);
+ assertEquals(crcFromLFH, crcFromCDH);
+ long cSizeFromCDH = ZipLong.getValue(data, cdhStart + 20);
+ assertEquals(cSizeFromLFH, cSizeFromCDH);
+ long sizeFromCDH = ZipLong.getValue(data, cdhStart + 24);
+ assertEquals(sizeFromLFH, sizeFromCDH);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private byte[] createLocalFileHeader(final ZipArchiveEntry ze, final ByteBuffer name, final boolean encodable,
+ final boolean phased, long archiveOffset) throws IOException {
+ ResourceAlignmentExtraField oldAlignmentEx =
+ (ResourceAlignmentExtraField) ze.getExtraField(ResourceAlignmentExtraField.ID);
+ if (oldAlignmentEx != null) {
+ ze.removeExtraField(ResourceAlignmentExtraField.ID);
+ }
+
+ int alignment = ze.getAlignment();
+ if (alignment <= 0 && oldAlignmentEx != null) {
+ alignment = oldAlignmentEx.getAlignment();
+ }
+
+ if (alignment > 1 || (oldAlignmentEx != null && !oldAlignmentEx.allowMethodChange())) {
+ int oldLength = LFH_FILENAME_OFFSET +
+ name.limit() - name.position() +
+ ze.getLocalFileDataExtra().length;
+
+ int padding = (int) ((-archiveOffset - oldLength - ZipExtraField.EXTRAFIELD_HEADER_SIZE
+ - ResourceAlignmentExtraField.BASE_SIZE) &
+ (alignment - 1));
+ ze.addExtraField(new ResourceAlignmentExtraField(alignment,
+ oldAlignmentEx != null && oldAlignmentEx.allowMethodChange(), padding));
+ }
+
+ final byte[] extra = ze.getLocalFileDataExtra();
+ final int nameLen = name.limit() - name.position();
+ final int len = LFH_FILENAME_OFFSET + nameLen + extra.length;
+ final byte[] buf = new byte[len];
+
+ System.arraycopy(LFH_SIG, 0, buf, LFH_SIG_OFFSET, WORD);
+
+ //store method in local variable to prevent multiple method calls
+ final int zipMethod = ze.getMethod();
+ final boolean dataDescriptor = usesDataDescriptor(zipMethod);
+
+ putShort(versionNeededToExtract(zipMethod, hasZip64Extra(ze), dataDescriptor), buf, LFH_VERSION_NEEDED_OFFSET);
+
+ final GeneralPurposeBit generalPurposeBit = getGeneralPurposeBits(!encodable && fallbackToUTF8, dataDescriptor);
+ generalPurposeBit.encode(buf, LFH_GPB_OFFSET);
+
+ // compression method
+ putShort(zipMethod, buf, LFH_METHOD_OFFSET);
+
+ ZipUtil.toDosTime(calendarInstance, ze.getTime(), buf, LFH_TIME_OFFSET);
+
+ // CRC
+ if (phased){
+ putLong(ze.getCrc(), buf, LFH_CRC_OFFSET);
+ } else if (zipMethod == DEFLATED || channel != null) {
+ System.arraycopy(LZERO, 0, buf, LFH_CRC_OFFSET, WORD);
+ } else {
+ putLong(ze.getCrc(), buf, LFH_CRC_OFFSET);
+ }
+
+ // compressed length
+ // uncompressed length
+ if (hasZip64Extra(entry.entry)){
+ // point to ZIP64 extended information extra field for
+ // sizes, may get rewritten once sizes are known if
+ // stream is seekable
+ ZipLong.ZIP64_MAGIC.putLong(buf, LFH_COMPRESSED_SIZE_OFFSET);
+ ZipLong.ZIP64_MAGIC.putLong(buf, LFH_ORIGINAL_SIZE_OFFSET);
+ } else if (phased) {
+ putLong(ze.getCompressedSize(), buf, LFH_COMPRESSED_SIZE_OFFSET);
+ putLong(ze.getSize(), buf, LFH_ORIGINAL_SIZE_OFFSET);
+ } else if (zipMethod == DEFLATED || channel != null) {
+ System.arraycopy(LZERO, 0, buf, LFH_COMPRESSED_SIZE_OFFSET, WORD);
+ System.arraycopy(LZERO, 0, buf, LFH_ORIGINAL_SIZE_OFFSET, WORD);
+ } else { // Stored
+ putLong(ze.getSize(), buf, LFH_COMPRESSED_SIZE_OFFSET);
+ putLong(ze.getSize(), buf, LFH_ORIGINAL_SIZE_OFFSET);
+ }
+ // file name length
+ putShort(nameLen, buf, LFH_FILENAME_LENGTH_OFFSET);
+
+ // extra field length
+ putShort(extra.length, buf, LFH_EXTRA_LENGTH_OFFSET);
+
+ // file name
+ System.arraycopy( name.array(), name.arrayOffset(), buf, LFH_FILENAME_OFFSET, nameLen);
+
+ // extra fields
+ System.arraycopy(extra, 0, buf, LFH_FILENAME_OFFSET + nameLen, extra.length);
+
+ return buf;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void doesntWriteDataDescriptorWhenAddingRawEntries() throws IOException {
+ ByteArrayOutputStream init = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(init)) {
+ zos.putArchiveEntry(new ZipArchiveEntry(""test1.txt""));
+ zos.write(""foo"".getBytes(""UTF-8""));
+ zos.closeArchiveEntry();
+ }
+
+ File f = new File(dir, ""test.zip"");
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ fos.write(init.toByteArray());
+ }
+
+ ByteArrayOutputStream o = new ByteArrayOutputStream();
+ ZipArchiveEntry zae;
+ try (ZipFile zf = new ZipFile(f);
+ ZipArchiveOutputStream zos = new ZipArchiveOutputStream(o)) {
+ zae = zf.getEntry(""test1.txt"");
+ zos.addRawArchiveEntry(zae, zf.getRawInputStream(zae));
+ }
+
+ byte[] data = o.toByteArray();
+ byte[] versionInLFH = Arrays.copyOfRange(data, 4, 6);
+ // still 2.0 because of Deflate
+ assertArrayEquals(new byte[] { 20, 0 }, versionInLFH);
+ byte[] gpbInLFH = Arrays.copyOfRange(data, 6, 8);
+ // no DD but EFS flag
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInLFH);
+
+ int cdhStart = findCentralDirectory(data);
+ byte[] versionInCDH = Arrays.copyOfRange(data, cdhStart + 6, cdhStart + 8);
+ assertArrayEquals(new byte[] { 20, 0 }, versionInCDH);
+ byte[] gpbInCDH = Arrays.copyOfRange(data, cdhStart + 8, cdhStart + 10);
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInCDH);
+
+ int ddStart = cdhStart - 16;
+ assertNotEquals(ZipLong.DD_SIG, new ZipLong(data, ddStart));
+ long crcFromLFH = ZipLong.getValue(data, 14);
+ long cSizeFromLFH = ZipLong.getValue(data, 18);
+ long sizeFromLFH = ZipLong.getValue(data, 22);
+ assertEquals(3, sizeFromLFH);
+
+ long crcFromCDH = ZipLong.getValue(data, cdhStart + 16);
+ assertEquals(crcFromLFH, crcFromCDH);
+ long cSizeFromCDH = ZipLong.getValue(data, cdhStart + 20);
+ assertEquals(cSizeFromLFH, cSizeFromCDH);
+ long sizeFromCDH = ZipLong.getValue(data, cdhStart + 24);
+ assertEquals(sizeFromLFH, sizeFromCDH);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void writeDataDescriptor(final ZipArchiveEntry ze) throws IOException {
+ if (ze.getMethod() != DEFLATED || channel != null) {
+ return;
+ }
+ writeCounted(DD_SIG);
+ writeCounted(ZipLong.getBytes(ze.getCrc()));
+ if (!hasZip64Extra(ze)) {
+ writeCounted(ZipLong.getBytes(ze.getCompressedSize()));
+ writeCounted(ZipLong.getBytes(ze.getSize()));
+ } else {
+ writeCounted(ZipEightByteInteger.getBytes(ze.getCompressedSize()));
+ writeCounted(ZipEightByteInteger.getBytes(ze.getSize()));
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void doesntWriteDataDescriptorWhenAddingRawEntries() throws IOException {
+ ByteArrayOutputStream init = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(init)) {
+ zos.putArchiveEntry(new ZipArchiveEntry(""test1.txt""));
+ zos.write(""foo"".getBytes(""UTF-8""));
+ zos.closeArchiveEntry();
+ }
+
+ File f = new File(dir, ""test.zip"");
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ fos.write(init.toByteArray());
+ }
+
+ ByteArrayOutputStream o = new ByteArrayOutputStream();
+ ZipArchiveEntry zae;
+ try (ZipFile zf = new ZipFile(f);
+ ZipArchiveOutputStream zos = new ZipArchiveOutputStream(o)) {
+ zae = zf.getEntry(""test1.txt"");
+ zos.addRawArchiveEntry(zae, zf.getRawInputStream(zae));
+ }
+
+ byte[] data = o.toByteArray();
+ byte[] versionInLFH = Arrays.copyOfRange(data, 4, 6);
+ // still 2.0 because of Deflate
+ assertArrayEquals(new byte[] { 20, 0 }, versionInLFH);
+ byte[] gpbInLFH = Arrays.copyOfRange(data, 6, 8);
+ // no DD but EFS flag
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInLFH);
+
+ int cdhStart = findCentralDirectory(data);
+ byte[] versionInCDH = Arrays.copyOfRange(data, cdhStart + 6, cdhStart + 8);
+ assertArrayEquals(new byte[] { 20, 0 }, versionInCDH);
+ byte[] gpbInCDH = Arrays.copyOfRange(data, cdhStart + 8, cdhStart + 10);
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInCDH);
+
+ int ddStart = cdhStart - 16;
+ assertNotEquals(ZipLong.DD_SIG, new ZipLong(data, ddStart));
+ long crcFromLFH = ZipLong.getValue(data, 14);
+ long cSizeFromLFH = ZipLong.getValue(data, 18);
+ long sizeFromLFH = ZipLong.getValue(data, 22);
+ assertEquals(3, sizeFromLFH);
+
+ long crcFromCDH = ZipLong.getValue(data, cdhStart + 16);
+ assertEquals(crcFromLFH, crcFromCDH);
+ long cSizeFromCDH = ZipLong.getValue(data, cdhStart + 20);
+ assertEquals(cSizeFromLFH, cSizeFromCDH);
+ long sizeFromCDH = ZipLong.getValue(data, cdhStart + 24);
+ assertEquals(sizeFromLFH, sizeFromCDH);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean usesDataDescriptor(final int zipMethod) {
+ return zipMethod == DEFLATED && channel == null;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void doesntWriteDataDescriptorWhenAddingRawEntries() throws IOException {
+ ByteArrayOutputStream init = new ByteArrayOutputStream();
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(init)) {
+ zos.putArchiveEntry(new ZipArchiveEntry(""test1.txt""));
+ zos.write(""foo"".getBytes(""UTF-8""));
+ zos.closeArchiveEntry();
+ }
+
+ File f = new File(dir, ""test.zip"");
+ try (FileOutputStream fos = new FileOutputStream(f)) {
+ fos.write(init.toByteArray());
+ }
+
+ ByteArrayOutputStream o = new ByteArrayOutputStream();
+ ZipArchiveEntry zae;
+ try (ZipFile zf = new ZipFile(f);
+ ZipArchiveOutputStream zos = new ZipArchiveOutputStream(o)) {
+ zae = zf.getEntry(""test1.txt"");
+ zos.addRawArchiveEntry(zae, zf.getRawInputStream(zae));
+ }
+
+ byte[] data = o.toByteArray();
+ byte[] versionInLFH = Arrays.copyOfRange(data, 4, 6);
+ // still 2.0 because of Deflate
+ assertArrayEquals(new byte[] { 20, 0 }, versionInLFH);
+ byte[] gpbInLFH = Arrays.copyOfRange(data, 6, 8);
+ // no DD but EFS flag
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInLFH);
+
+ int cdhStart = findCentralDirectory(data);
+ byte[] versionInCDH = Arrays.copyOfRange(data, cdhStart + 6, cdhStart + 8);
+ assertArrayEquals(new byte[] { 20, 0 }, versionInCDH);
+ byte[] gpbInCDH = Arrays.copyOfRange(data, cdhStart + 8, cdhStart + 10);
+ assertArrayEquals(new byte[] { 0, 8 }, gpbInCDH);
+
+ int ddStart = cdhStart - 16;
+ assertNotEquals(ZipLong.DD_SIG, new ZipLong(data, ddStart));
+ long crcFromLFH = ZipLong.getValue(data, 14);
+ long cSizeFromLFH = ZipLong.getValue(data, 18);
+ long sizeFromLFH = ZipLong.getValue(data, 22);
+ assertEquals(3, sizeFromLFH);
+
+ long crcFromCDH = ZipLong.getValue(data, cdhStart + 16);
+ assertEquals(crcFromLFH, crcFromCDH);
+ long cSizeFromCDH = ZipLong.getValue(data, cdhStart + 20);
+ assertEquals(cSizeFromLFH, cSizeFromCDH);
+ long sizeFromCDH = ZipLong.getValue(data, cdhStart + 24);
+ assertEquals(sizeFromLFH, sizeFromCDH);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) {
+
+
+
+ this.checksum = checksum;
+ this.in = in;
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = NullPointerException.class)
+ public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() {
+
+ ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
+
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static int formatLongOctalOrBinaryBytes(
+ final long value, final byte[] buf, final int offset, final int length) {
+
+ // Check whether we are dealing with UID/GID or SIZE field
+ final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE;
+
+ final boolean negative = value < 0;
+ if (!negative && value <= maxAsOctalChar) { // OK to store as octal chars
+ return formatLongOctalBytes(value, buf, offset, length);
+ }
+
+ if (length < 9) {
+ formatLongBinary(value, buf, offset, length, negative);
+ }
+ formatBigIntegerBinary(value, buf, offset, length, negative);
+
+ buf[offset] = (byte) (negative ? 0xff : 0x80);
+ return offset + length;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testRoundTripOctalOrBinary8() {
+ testRoundTripOctalOrBinary(8);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static ZipLong unixTimeToZipLong(long l) {
+ final long TWO_TO_32 = 0x100000000L;
+ if (l >= TWO_TO_32) {
+ throw new IllegalArgumentException(""X5455 timestamps must fit in a signed 32 bit integer: "" + l);
+ }
+ return new ZipLong(l);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testGettersSetters() {
+ // X5455 is concerned with time, so let's
+ // get a timestamp to play with (Jan 1st, 2000).
+ final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(""UTC""));
+ cal.set(Calendar.YEAR, 2000);
+ cal.set(Calendar.MONTH, Calendar.JANUARY);
+ cal.set(Calendar.DATE, 1);
+ cal.set(Calendar.HOUR_OF_DAY, 0);
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+ final long timeMillis = cal.getTimeInMillis();
+ final ZipLong time = new ZipLong(timeMillis / 1000);
+
+ // set too big
+ try {
+ // Java time is 1000 x larger (milliseconds).
+ xf.setModifyJavaTime(new Date(1000L * (MAX_TIME_SECONDS.getValue() + 1L)));
+ fail(""Time too big for 32 bits!"");
+ } catch (final IllegalArgumentException iae) {
+ // All is good.
+ }
+
+ // get/set modify time
+ xf.setModifyTime(time);
+ assertEquals(time, xf.getModifyTime());
+ Date xfModifyJavaTime = xf.getModifyJavaTime();
+ assertEquals(timeMillis, xfModifyJavaTime.getTime());
+ xf.setModifyJavaTime(new Date(timeMillis));
+ assertEquals(time, xf.getModifyTime());
+ assertEquals(timeMillis, xf.getModifyJavaTime().getTime());
+ // Make sure milliseconds get zeroed out:
+ xf.setModifyJavaTime(new Date(timeMillis + 123));
+ assertEquals(time, xf.getModifyTime());
+ assertEquals(timeMillis, xf.getModifyJavaTime().getTime());
+ // Null
+ xf.setModifyTime(null);
+ assertNull(xf.getModifyJavaTime());
+ xf.setModifyJavaTime(null);
+ assertNull(xf.getModifyTime());
+
+ // get/set access time
+ xf.setAccessTime(time);
+ assertEquals(time, xf.getAccessTime());
+ assertEquals(timeMillis, xf.getAccessJavaTime().getTime());
+ xf.setAccessJavaTime(new Date(timeMillis));
+ assertEquals(time, xf.getAccessTime());
+ assertEquals(timeMillis, xf.getAccessJavaTime().getTime());
+ // Make sure milliseconds get zeroed out:
+ xf.setAccessJavaTime(new Date(timeMillis + 123));
+ assertEquals(time, xf.getAccessTime());
+ assertEquals(timeMillis, xf.getAccessJavaTime().getTime());
+ // Null
+ xf.setAccessTime(null);
+ assertNull(xf.getAccessJavaTime());
+ xf.setAccessJavaTime(null);
+ assertNull(xf.getAccessTime());
+
+ // get/set create time
+ xf.setCreateTime(time);
+ assertEquals(time, xf.getCreateTime());
+ assertEquals(timeMillis, xf.getCreateJavaTime().getTime());
+ xf.setCreateJavaTime(new Date(timeMillis));
+ assertEquals(time, xf.getCreateTime());
+ assertEquals(timeMillis, xf.getCreateJavaTime().getTime());
+ // Make sure milliseconds get zeroed out:
+ xf.setCreateJavaTime(new Date(timeMillis + 123));
+ assertEquals(time, xf.getCreateTime());
+ assertEquals(timeMillis, xf.getCreateJavaTime().getTime());
+ // Null
+ xf.setCreateTime(null);
+ assertNull(xf.getCreateJavaTime());
+ xf.setCreateJavaTime(null);
+ assertNull(xf.getCreateTime());
+
+
+ // initialize for flags
+ xf.setModifyTime(time);
+ xf.setAccessTime(time);
+ xf.setCreateTime(time);
+
+ // get/set flags: 000
+ xf.setFlags((byte) 0);
+ assertEquals(0, xf.getFlags());
+ assertFalse(xf.isBit0_modifyTimePresent());
+ assertFalse(xf.isBit1_accessTimePresent());
+ assertFalse(xf.isBit2_createTimePresent());
+ // Local length=1, Central length=1 (flags only!)
+ assertEquals(1, xf.getLocalFileDataLength().getValue());
+ assertEquals(1, xf.getCentralDirectoryLength().getValue());
+
+ // get/set flags: 001
+ xf.setFlags((byte) 1);
+ assertEquals(1, xf.getFlags());
+ assertTrue(xf.isBit0_modifyTimePresent());
+ assertFalse(xf.isBit1_accessTimePresent());
+ assertFalse(xf.isBit2_createTimePresent());
+ // Local length=5, Central length=5 (flags + mod)
+ assertEquals(5, xf.getLocalFileDataLength().getValue());
+ assertEquals(5, xf.getCentralDirectoryLength().getValue());
+
+ // get/set flags: 010
+ xf.setFlags((byte) 2);
+ assertEquals(2, xf.getFlags());
+ assertFalse(xf.isBit0_modifyTimePresent());
+ assertTrue(xf.isBit1_accessTimePresent());
+ assertFalse(xf.isBit2_createTimePresent());
+ // Local length=5, Central length=1
+ assertEquals(5, xf.getLocalFileDataLength().getValue());
+ assertEquals(1, xf.getCentralDirectoryLength().getValue());
+
+ // get/set flags: 100
+ xf.setFlags((byte) 4);
+ assertEquals(4, xf.getFlags());
+ assertFalse(xf.isBit0_modifyTimePresent());
+ assertFalse(xf.isBit1_accessTimePresent());
+ assertTrue(xf.isBit2_createTimePresent());
+ // Local length=5, Central length=1
+ assertEquals(5, xf.getLocalFileDataLength().getValue());
+ assertEquals(1, xf.getCentralDirectoryLength().getValue());
+
+ // get/set flags: 111
+ xf.setFlags((byte) 7);
+ assertEquals(7, xf.getFlags());
+ assertTrue(xf.isBit0_modifyTimePresent());
+ assertTrue(xf.isBit1_accessTimePresent());
+ assertTrue(xf.isBit2_createTimePresent());
+ // Local length=13, Central length=5
+ assertEquals(13, xf.getLocalFileDataLength().getValue());
+ assertEquals(5, xf.getCentralDirectoryLength().getValue());
+
+ // get/set flags: 11111111
+ xf.setFlags((byte) -1);
+ assertEquals(-1, xf.getFlags());
+ assertTrue(xf.isBit0_modifyTimePresent());
+ assertTrue(xf.isBit1_accessTimePresent());
+ assertTrue(xf.isBit2_createTimePresent());
+ // Local length=13, Central length=5
+ assertEquals(13, xf.getLocalFileDataLength().getValue());
+ assertEquals(5, xf.getCentralDirectoryLength().getValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean canReadEntryData(final ArchiveEntry ae) {
+ if (ae instanceof ZipArchiveEntry) {
+ final ZipArchiveEntry ze = (ZipArchiveEntry) ae;
+ return ZipUtil.canHandleEntryData(ze)
+ && supportsDataDescriptorFor(ze);
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception {
+ // we never read any data
+ try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new ByteArrayInputStream(new byte[0]))) {
+ ZipArchiveEntry e = new ZipArchiveEntry(""test"");
+ e.setMethod(ZipMethod.DEFLATED.getCode());
+ assertTrue(zis.canReadEntryData(e));
+ e.setMethod(ZipMethod.ENHANCED_DEFLATED.getCode());
+ assertTrue(zis.canReadEntryData(e));
+ e.setMethod(ZipMethod.BZIP2.getCode());
+ assertFalse(zis.canReadEntryData(e));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public int read(final byte[] buffer, final int offset, final int length) throws IOException {
+ if (closed) {
+ throw new IOException(""The stream is closed"");
+ }
+
+ if (current == null) {
+ return -1;
+ }
+
+ // avoid int overflow, check null buffer
+ if (offset > buffer.length || length < 0 || offset < 0 || buffer.length - offset < length) {
+ throw new ArrayIndexOutOfBoundsException();
+ }
+
+ ZipUtil.checkRequestedFeatures(current.entry);
+ if (!supportsDataDescriptorFor(current.entry)) {
+ throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.DATA_DESCRIPTOR,
+ current.entry);
+ }
+
+ int read;
+ if (current.entry.getMethod() == ZipArchiveOutputStream.STORED) {
+ read = readStored(buffer, offset, length);
+ } else if (current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED) {
+ read = readDeflated(buffer, offset, length);
+ } else if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()
+ || current.entry.getMethod() == ZipMethod.IMPLODING.getCode()
+ || current.entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()
+ || current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {
+ read = current.in.read(buffer, offset, length);
+ } else {
+ throw new UnsupportedZipFeatureException(ZipMethod.getMethodByCode(current.entry.getMethod()),
+ current.entry);
+ }
+
+ if (read >= 0) {
+ current.crc.update(buffer, offset, read);
+ }
+
+ return read;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception {
+ // we never read any data
+ try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new ByteArrayInputStream(new byte[0]))) {
+ ZipArchiveEntry e = new ZipArchiveEntry(""test"");
+ e.setMethod(ZipMethod.DEFLATED.getCode());
+ assertTrue(zis.canReadEntryData(e));
+ e.setMethod(ZipMethod.ENHANCED_DEFLATED.getCode());
+ assertTrue(zis.canReadEntryData(e));
+ e.setMethod(ZipMethod.BZIP2.getCode());
+ assertFalse(zis.canReadEntryData(e));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read(byte[] buffer, int start, int length) throws IOException {
+ if (closed) {
+ throw new IOException(""The stream is closed"");
+ }
+ if (inf.finished() || current == null) {
+ return -1;
+ }
+
+ // avoid int overflow, check null buffer
+ if (start <= buffer.length && length >= 0 && start >= 0
+ && buffer.length - start >= length) {
+ if (current.getMethod() == ZipArchiveOutputStream.STORED) {
+ int csize = (int) current.getSize();
+ if (readBytesOfEntry >= csize) {
+ return -1;
+ }
+ if (offsetInBuffer >= lengthOfLastRead) {
+ offsetInBuffer = 0;
+ if ((lengthOfLastRead = in.read(buf)) == -1) {
+ return -1;
+ }
+ count(lengthOfLastRead);
+ bytesReadFromStream += lengthOfLastRead;
+ }
+ int toRead = length > lengthOfLastRead
+ ? lengthOfLastRead - offsetInBuffer
+ : length;
+ if ((csize - readBytesOfEntry) < toRead) {
+ toRead = csize - readBytesOfEntry;
+ }
+ System.arraycopy(buf, offsetInBuffer, buffer, start, toRead);
+ offsetInBuffer += toRead;
+ readBytesOfEntry += toRead;
+ crc.update(buffer, start, toRead);
+ return toRead;
+ }
+ if (inf.needsInput()) {
+ fill();
+ if (lengthOfLastRead > 0) {
+ bytesReadFromStream += lengthOfLastRead;
+ }
+ }
+ int read = 0;
+ try {
+ read = inf.inflate(buffer, start, length);
+ } catch (DataFormatException e) {
+ throw new ZipException(e.getMessage());
+ }
+ if (read == 0 && inf.finished()) {
+ return -1;
+ }
+ crc.update(buffer, start, read);
+ return read;
+ }
+ throw new ArrayIndexOutOfBoundsException();
+ }
+
+// Test Case
+[/INST]
+ public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
+ URISyntaxException {
+
+ URL zip = getClass().getResource(""/apache-maven-2.2.1.zip.001"");
+ FileInputStream archive = new FileInputStream(
+ new File(new URI(zip.toString())));
+ ZipArchiveInputStream zi = null;
+ try {
+ zi = new ZipArchiveInputStream(archive,null,false);
+
+ // these are the entries that are supposed to be processed
+ // correctly without any problems
+ for (int i = 0; i < ENTRIES.length; i++) {
+ assertEquals(ENTRIES[i], zi.getNextEntry().getName());
+ }
+
+ // this is the last entry that is truncated
+ ArchiveEntry lastEntry = zi.getNextEntry();
+ assertEquals(LAST_ENTRY_NAME, lastEntry.getName());
+ byte [] buffer = new byte [4096];
+
+ // before the fix, we'd get 0 bytes on this read and all
+ // subsequent reads thus a client application might enter
+ // an infinite loop after the fix, we should get an
+ // exception
+ try {
+ int read = 0;
+ while ((read = zi.read(buffer)) > 0) { }
+ fail(""shouldn't be able to read from truncated entry"");
+ } catch (IOException e) {
+ assertEquals(""Truncated ZIP file"", e.getMessage());
+ }
+
+ // and now we get another entry, which should also yield
+ // an exception
+ try {
+ zi.getNextEntry();
+ fail(""shouldn't be able to read another entry from truncated""
+ + "" file"");
+ } catch (IOException e) {
+ // this is to be expected
+ }
+ } finally {
+ if (zi != null) {
+ zi.close();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ZipArchiveEntry(String name) {
+ super(name);
+ }
+
+// Test Case
+[/INST]
+ public void testNotEquals() {
+ ZipArchiveEntry entry1 = new ZipArchiveEntry(""foo"");
+ ZipArchiveEntry entry2 = new ZipArchiveEntry(""bar"");
+ assertFalse(entry1.equals(entry2));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ ZipArchiveEntry other = (ZipArchiveEntry) obj;
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testNotEquals() {
+ ZipArchiveEntry entry1 = new ZipArchiveEntry(""foo"");
+ ZipArchiveEntry entry2 = new ZipArchiveEntry(""bar"");
+ assertFalse(entry1.equals(entry2));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static String parseName(byte[] buffer, final int offset, final int length) {
+ StringBuffer result = new StringBuffer(length);
+ int end = offset + length;
+
+ for (int i = offset; i < end; ++i) {
+ if (buffer[i] == 0) {
+ break;
+ }
+ result.append((char) buffer[i]);
+ }
+
+ return result.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testRoundTripNames(){
+ checkName("""");
+ checkName(""The quick brown fox\n"");
+ checkName(""\177"");
+ // checkName(""\0""); // does not work, because NUL is ignored
+ // COMPRESS-114
+ checkName(""0302-0601-3???F06?W220?ZB?LALALA??????????CAN??DC???04?060302?MOE.model"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static long parseOctal(final byte[] buffer, final int offset, final int length) {
+ long result = 0;
+ boolean stillPadding = true;
+ int end = offset + length;
+ int start = offset;
+
+ for (int i = start; i < end; i++){
+ final byte currentByte = buffer[i];
+ if (currentByte == 0) {
+ break;
+ }
+
+ // Skip leading spaces
+ if (currentByte == (byte) ' ' || currentByte == '0') {
+ if (stillPadding) {
+ continue;
+ }
+ if (currentByte == (byte) ' ') {
+ break;
+ }
+ }
+
+ // Must have trailing NUL or space
+ // May have additional NUL or space
+
+ stillPadding = false;
+ // CheckStyle:MagicNumber OFF
+ if (currentByte < '0' || currentByte > '7'){
+ throw new IllegalArgumentException(
+ exceptionMessage(buffer, offset, length, start, currentByte));
+ }
+ result = (result << 3) + (currentByte - '0'); // convert from ASCII
+ // CheckStyle:MagicNumber ON
+ }
+
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testParseOctalInvalid() throws Exception{
+ byte [] buffer;
+ buffer=new byte[0]; // empty byte array
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - should be at least 2 bytes long"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer=new byte[]{0}; // 1-byte array
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - should be at least 2 bytes long"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer=new byte[]{0,0,' '}; // not all NULs
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - not all NULs"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer=new byte[]{' ',0,0,0}; // not all NULs
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - not all NULs"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer = ""abcdef "".getBytes(""UTF-8""); // Invalid input
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer = ""77777777777"".getBytes(""UTF-8""); // Invalid input - no trailer
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - no trailer"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer = "" 0 07 "".getBytes(""UTF-8""); // Invalid - embedded space
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - embedded space"");
+ } catch (IllegalArgumentException expected) {
+ }
+ buffer = "" 0\00007 "".getBytes(""UTF-8""); // Invalid - embedded NUL
+ try {
+ TarUtils.parseOctal(buffer,0, buffer.length);
+ fail(""Expected IllegalArgumentException - embedded NUL"");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void write(byte[] wBuf, int wOffset, int numToWrite) throws IOException {
+ if ((currBytes + numToWrite) > currSize) {
+ throw new IOException(""request to write '"" + numToWrite
+ + ""' bytes exceeds size in header of '""
+ + currSize + ""' bytes for entry '""
+ + currName + ""'"");
+
+ //
+ // We have to deal with assembly!!!
+ // The programmer can be writing little 32 byte chunks for all
+ // we know, and we must assemble complete records for writing.
+ // REVIEW Maybe this should be in TarBuffer? Could that help to
+ // eliminate some of the buffer copying.
+ //
+ }
+
+ if (assemLen > 0) {
+ if ((assemLen + numToWrite) >= recordBuf.length) {
+ int aLen = recordBuf.length - assemLen;
+
+ System.arraycopy(assemBuf, 0, recordBuf, 0,
+ assemLen);
+ System.arraycopy(wBuf, wOffset, recordBuf,
+ assemLen, aLen);
+ buffer.writeRecord(recordBuf);
+
+ currBytes += recordBuf.length;
+ wOffset += aLen;
+ numToWrite -= aLen;
+ assemLen = 0;
+ } else {
+ System.arraycopy(wBuf, wOffset, assemBuf, assemLen,
+ numToWrite);
+
+ wOffset += numToWrite;
+ assemLen += numToWrite;
+ numToWrite = 0;
+ }
+ }
+
+ //
+ // When we get here we have EITHER:
+ // o An empty ""assemble"" buffer.
+ // o No bytes to write (numToWrite == 0)
+ //
+ while (numToWrite > 0) {
+ if (numToWrite < recordBuf.length) {
+ System.arraycopy(wBuf, wOffset, assemBuf, assemLen,
+ numToWrite);
+
+ assemLen += numToWrite;
+
+ break;
+ }
+
+ buffer.writeRecord(wBuf, wOffset);
+
+ int num = recordBuf.length;
+
+ currBytes += num;
+ numToWrite -= num;
+ wOffset += num;
+ }
+ count(numToWrite);
+ }
+
+// Test Case
+[/INST]
+ public void testCount() throws Exception {
+ File f = File.createTempFile(""commons-compress-tarcount"", "".tar"");
+ f.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(f);
+
+ ArchiveOutputStream tarOut = new ArchiveStreamFactory()
+ .createArchiveOutputStream(ArchiveStreamFactory.TAR, fos);
+
+ File file1 = getFile(""test1.xml"");
+ TarArchiveEntry sEntry = new TarArchiveEntry(file1);
+ tarOut.putArchiveEntry(sEntry);
+
+ FileInputStream in = new FileInputStream(file1);
+ byte[] buf = new byte[8192];
+
+ int read = 0;
+ while ((read = in.read(buf)) > 0) {
+ tarOut.write(buf, 0, read);
+ }
+
+ in.close();
+ tarOut.closeArchiveEntry();
+ tarOut.close();
+
+ assertEquals(f.length(), tarOut.getBytesWritten());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testCount() throws Exception {
+ File f = File.createTempFile(""commons-compress-tarcount"", "".tar"");
+ f.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(f);
+
+ ArchiveOutputStream tarOut = new ArchiveStreamFactory()
+ .createArchiveOutputStream(ArchiveStreamFactory.TAR, fos);
+
+ File file1 = getFile(""test1.xml"");
+ TarArchiveEntry sEntry = new TarArchiveEntry(file1);
+ tarOut.putArchiveEntry(sEntry);
+
+ FileInputStream in = new FileInputStream(file1);
+ byte[] buf = new byte[8192];
+
+ int read = 0;
+ while ((read = in.read(buf)) > 0) {
+ tarOut.write(buf, 0, read);
+ }
+
+ in.close();
+ tarOut.closeArchiveEntry();
+ tarOut.close();
+
+ assertEquals(f.length(), tarOut.getBytesWritten());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int read() throws IOException {
+ int current = super.read();
+ if (current == '\n') {
+ lineCounter++;
+ }
+ lastChar = current;
+ return lastChar;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testGetLineNumberWithCR() throws Exception {
+ CSVParser parser = new CSVParser(""a\rb\rc"", CSVFormat.DEFAULT.withLineSeparator(""\r""));
+
+ assertEquals(0, parser.getLineNumber());
+ assertNotNull(parser.getRecord());
+ assertEquals(1, parser.getLineNumber());
+ assertNotNull(parser.getRecord());
+ assertEquals(2, parser.getLineNumber());
+ assertNotNull(parser.getRecord());
+ assertEquals(2, parser.getLineNumber());
+ assertNull(parser.getRecord());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException {
+ Assertions.notNull(out, ""out"");
+ Assertions.notNull(format, ""format"");
+
+ this.out = out;
+ this.format = format;
+ this.format.validate();
+ // TODO: Is it a good idea to do this here instead of on the first call to a print method?
+ // It seems a pain to have to track whether the header has already been printed or not.
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testHeader() throws IOException {
+ final StringWriter sw = new StringWriter();
+ final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null)
+ .withHeader(""C1"", ""C2"", ""C3""));
+ printer.printRecord(""a"", ""b"", ""c"");
+ printer.printRecord(""x"", ""y"", ""z"");
+ assertEquals(""C1,C2,C3\r\na,b,c\r\nx,y,z\r\n"", sw.toString());
+ printer.close();
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Map initializeHeader() throws IOException {
+ Map hdrMap = null;
+ final String[] formatHeader = this.format.getHeader();
+ if (formatHeader != null) {
+ hdrMap = new LinkedHashMap();
+
+ String[] headerRecord = null;
+ if (formatHeader.length == 0) {
+ // read the header from the first line of the file
+ final CSVRecord nextRecord = this.nextRecord();
+ if (nextRecord != null) {
+ headerRecord = nextRecord.values();
+ }
+ } else {
+ if (this.format.getSkipHeaderRecord()) {
+ this.nextRecord();
+ }
+ headerRecord = formatHeader;
+ }
+
+ // build the name to index mappings
+ if (headerRecord != null) {
+ for (int i = 0; i < headerRecord.length; i++) {
+ final String header = headerRecord[i];
+ final boolean containsHeader = hdrMap.containsKey(header);
+ final boolean emptyHeader = header.trim().isEmpty();
+ if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) {
+ throw new IllegalArgumentException(""The header contains a duplicate name: \"""" + header +
+ ""\"" in "" + Arrays.toString(headerRecord));
+ }
+ hdrMap.put(header, Integer.valueOf(i));
+ }
+ }
+ }
+ return hdrMap;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testHeaderMissingWithNull() throws Exception {
+ final Reader in = new StringReader(""a,,c,,d\n1,2,3,4\nx,y,z,zz"");
+ CSVFormat.DEFAULT.withHeader().withNullString("""").withIgnoreEmptyHeaders(true).parse(in).iterator();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testExcelHeaderCountLessThanData() throws Exception {
+ final String code = ""A,B,C,,\r\na,b,c,d,e\r\n"";
+ final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL.withHeader());
+ try {
+ for (CSVRecord record : parser.getRecords()) {
+ Assert.assertEquals(""a"", record.get(""A""));
+ Assert.assertEquals(""b"", record.get(""B""));
+ Assert.assertEquals(""c"", record.get(""C""));
+ }
+ } finally {
+ parser.close();
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void print(final Object object, final CharSequence value, final int offset, final int len)
+ throws IOException {
+ if (!newRecord) {
+ out.append(format.getDelimiter());
+ }
+ if (format.isQuoteCharacterSet()) {
+ // the original object is needed so can check for Number
+ printAndQuote(object, value, offset, len);
+ } else if (format.isEscapeCharacterSet()) {
+ printAndEscape(value, offset, len);
+ } else {
+ out.append(value, offset, offset + len);
+ }
+ newRecord = false;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testMySqlNullOutput() throws IOException {
+ Object[] s = new String[] { ""NULL"", null };
+ CSVFormat format = CSVFormat.MYSQL.withQuote('""').withNullString(""NULL"").withQuoteMode(QuoteMode.NON_NUMERIC);
+ StringWriter writer = new StringWriter();
+ CSVPrinter printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ String expected = ""\""NULL\""\tNULL\n"";
+ assertEquals(expected, writer.toString());
+ String[] record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(new Object[2], record0);
+
+ s = new String[] { ""\\N"", null };
+ format = CSVFormat.MYSQL.withNullString(""\\N"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\N\t\\N\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\\N"", ""A"" };
+ format = CSVFormat.MYSQL.withNullString(""\\N"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\N\tA\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\n"", ""A"" };
+ format = CSVFormat.MYSQL.withNullString(""\\N"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\n\tA\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { """", null };
+ format = CSVFormat.MYSQL.withNullString(""NULL"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\tNULL\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { """", null };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\t\\N\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\\N"", """", ""\u000e,\\\r"" };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\N\t\t\u000e,\\\\\\r\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""NULL"", ""\\\r"" };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""NULL\t\\\\\\r\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\\\r"" };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\\\r\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testMySqlNullOutput() throws IOException {
+ Object[] s = new String[] { ""NULL"", null };
+ CSVFormat format = CSVFormat.MYSQL.withQuote('""').withNullString(""NULL"").withQuoteMode(QuoteMode.NON_NUMERIC);
+ StringWriter writer = new StringWriter();
+ CSVPrinter printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ String expected = ""\""NULL\""\tNULL\n"";
+ assertEquals(expected, writer.toString());
+ String[] record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(new Object[2], record0);
+
+ s = new String[] { ""\\N"", null };
+ format = CSVFormat.MYSQL.withNullString(""\\N"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\N\t\\N\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\\N"", ""A"" };
+ format = CSVFormat.MYSQL.withNullString(""\\N"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\N\tA\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\n"", ""A"" };
+ format = CSVFormat.MYSQL.withNullString(""\\N"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\n\tA\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { """", null };
+ format = CSVFormat.MYSQL.withNullString(""NULL"");
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\tNULL\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { """", null };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\t\\N\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\\N"", """", ""\u000e,\\\r"" };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\N\t\t\u000e,\\\\\\r\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""NULL"", ""\\\r"" };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""NULL\t\\\\\\r\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+
+ s = new String[] { ""\\\r"" };
+ format = CSVFormat.MYSQL;
+ writer = new StringWriter();
+ printer = new CSVPrinter(writer, format);
+ printer.printRecord(s);
+ printer.close();
+ expected = ""\\\\\\r\n"";
+ assertEquals(expected, writer.toString());
+ record0 = toFirstRecordValues(expected, format);
+ assertArrayEquals(expectNulls(s, format), record0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,
+ final Appendable out, final boolean newRecord) throws IOException {
+ boolean quote = false;
+ int start = offset;
+ int pos = offset;
+ final int end = offset + len;
+
+ final char delimChar = getDelimiter();
+ final char quoteChar = getQuoteCharacter().charValue();
+
+ QuoteMode quoteModePolicy = getQuoteMode();
+ if (quoteModePolicy == null) {
+ quoteModePolicy = QuoteMode.MINIMAL;
+ }
+ switch (quoteModePolicy) {
+ case ALL:
+ quote = true;
+ break;
+ case NON_NUMERIC:
+ quote = !(object instanceof Number);
+ break;
+ case NONE:
+ // Use the existing escaping code
+ printAndEscape(value, offset, len, out);
+ return;
+ case MINIMAL:
+ if (len <= 0) {
+ // always quote an empty token that is the first
+ // on the line, as it may be the only thing on the
+ // line. If it were not quoted in that case,
+ // an empty line has no tokens.
+ if (newRecord) {
+ quote = true;
+ }
+ } else {
+ char c = value.charAt(pos);
+
+ // RFC4180 (https://tools.ietf.org/html/rfc4180) TEXTDATA = %x20-21 / %x23-2B / %x2D-7E
+ if (newRecord && (c < '0' || c > '9' && c < 'A' || c > 'Z' && c < 'a' || c > 'z')) {
+ quote = true;
+ } else if (c <= COMMENT) {
+ // Some other chars at the start of a value caused the parser to fail, so for now
+ // encapsulate if we start in anything less than '#'. We are being conservative
+ // by including the default comment char too.
+ quote = true;
+ } else {
+ while (pos < end) {
+ c = value.charAt(pos);
+ if (c == LF || c == CR || c == quoteChar || c == delimChar) {
+ quote = true;
+ break;
+ }
+ pos++;
+ }
+
+ if (!quote) {
+ pos = end - 1;
+ c = value.charAt(pos);
+ // Some other chars at the end caused the parser to fail, so for now
+ // encapsulate if we end in anything less than ' '
+ if (c <= SP) {
+ quote = true;
+ }
+ }
+ }
+ }
+
+ if (!quote) {
+ // no encapsulation needed - write out the original value
+ out.append(value, start, end);
+ return;
+ }
+ break;
+ default:
+ throw new IllegalStateException(""Unexpected Quote value: "" + quoteModePolicy);
+ }
+
+ if (!quote) {
+ // no encapsulation needed - write out the original value
+ out.append(value, start, end);
+ return;
+ }
+
+ // we hit something that needed encapsulation
+ out.append(quoteChar);
+
+ // Pick up where we left off: pos should be positioned on the first character that caused
+ // the need for encapsulation.
+ while (pos < end) {
+ final char c = value.charAt(pos);
+ if (c == quoteChar) {
+ // write out the chunk up until this point
+
+ // add 1 to the length to write out the encapsulator also
+ out.append(value, start, pos + 1);
+ // put the next starting position on the encapsulator so we will
+ // write it out again with the next string (effectively doubling it)
+ start = pos;
+ }
+ pos++;
+ }
+
+ // write the last segment
+ out.append(value, start, pos);
+ out.append(quoteChar);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEscapeNull1() throws IOException {
+ StringWriter sw = new StringWriter();
+ try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) {
+ printer.print(""\\"");
+ }
+ assertEquals(""\\"", sw.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,
+ final Appendable out, final boolean newRecord) throws IOException {
+ boolean quote = false;
+ int start = offset;
+ int pos = offset;
+ final int end = offset + len;
+
+ final char delimChar = getDelimiter();
+ final char quoteChar = getQuoteCharacter().charValue();
+
+ QuoteMode quoteModePolicy = getQuoteMode();
+ if (quoteModePolicy == null) {
+ quoteModePolicy = QuoteMode.MINIMAL;
+ }
+ switch (quoteModePolicy) {
+ case ALL:
+ case ALL_NON_NULL:
+ quote = true;
+ break;
+ case NON_NUMERIC:
+ quote = !(object instanceof Number);
+ break;
+ case NONE:
+ // Use the existing escaping code
+ printAndEscape(value, offset, len, out);
+ return;
+ case MINIMAL:
+ if (len <= 0) {
+ // always quote an empty token that is the first
+ // on the line, as it may be the only thing on the
+ // line. If it were not quoted in that case,
+ // an empty line has no tokens.
+ if (newRecord) {
+ quote = true;
+ }
+ } else {
+ char c = value.charAt(pos);
+
+ if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) {
+ quote = true;
+ } else if (c <= COMMENT) {
+ // Some other chars at the start of a value caused the parser to fail, so for now
+ // encapsulate if we start in anything less than '#'. We are being conservative
+ // by including the default comment char too.
+ quote = true;
+ } else {
+ while (pos < end) {
+ c = value.charAt(pos);
+ if (c == LF || c == CR || c == quoteChar || c == delimChar) {
+ quote = true;
+ break;
+ }
+ pos++;
+ }
+
+ if (!quote) {
+ pos = end - 1;
+ c = value.charAt(pos);
+ // Some other chars at the end caused the parser to fail, so for now
+ // encapsulate if we end in anything less than ' '
+ if (c <= SP) {
+ quote = true;
+ }
+ }
+ }
+ }
+
+ if (!quote) {
+ // no encapsulation needed - write out the original value
+ out.append(value, start, end);
+ return;
+ }
+ break;
+ default:
+ throw new IllegalStateException(""Unexpected Quote value: "" + quoteModePolicy);
+ }
+
+ if (!quote) {
+ // no encapsulation needed - write out the original value
+ out.append(value, start, end);
+ return;
+ }
+
+ // we hit something that needed encapsulation
+ out.append(quoteChar);
+
+ // Pick up where we left off: pos should be positioned on the first character that caused
+ // the need for encapsulation.
+ while (pos < end) {
+ final char c = value.charAt(pos);
+ if (c == quoteChar) {
+ // write out the chunk up until this point
+
+ // add 1 to the length to write out the encapsulator also
+ out.append(value, start, pos + 1);
+ // put the next starting position on the encapsulator so we will
+ // write it out again with the next string (effectively doubling it)
+ start = pos;
+ }
+ pos++;
+ }
+
+ // write the last segment
+ out.append(value, start, pos);
+ out.append(quoteChar);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testDontQuoteEuroFirstChar() throws IOException {
+ final StringWriter sw = new StringWriter();
+ try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) {
+ printer.printRecord(EURO_CH, ""Deux"");
+ assertEquals(EURO_CH + "",Deux"" + recordSeparator, sw.toString());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""resource"")
+ public CSVParser(final Reader reader, final CSVFormat format, final long characterOffset, final long recordNumber)
+ throws IOException {
+ Assertions.notNull(reader, ""reader"");
+ Assertions.notNull(format, ""format"");
+
+ this.format = format;
+ this.lexer = new Lexer(format, new ExtendedBufferedReader(reader));
+ this.headerMap = this.initializeHeader();
+ this.characterOffset = characterOffset;
+ this.recordNumber = recordNumber - 1;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testIteratorSequenceBreaking() throws IOException {
+ final String fiveRows = ""1\n2\n3\n4\n5\n"";
+
+ // Iterator hasNext() shouldn't break sequence
+ CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ int recordNumber = 0;
+ Iterator iter = parser.iterator();
+ recordNumber = 0;
+ while (iter.hasNext()) {
+ CSVRecord record = iter.next();
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ iter.hasNext();
+ while (iter.hasNext()) {
+ CSVRecord record = iter.next();
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+
+ // Consecutive enhanced for loops shouldn't break sequence
+ parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ recordNumber = 0;
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+
+ // Consecutive enhanced for loops with hasNext() peeking shouldn't break sequence
+ parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ recordNumber = 0;
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ parser.iterator().hasNext();
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Iterator iterator() {
+ return new Iterator() {
+ private CSVRecord current;
+
+ private CSVRecord getNextRecord() {
+ try {
+ return CSVParser.this.nextRecord();
+ } catch (final IOException e) {
+ throw new IllegalStateException(
+ e.getClass().getSimpleName() + "" reading next record: "" + e.toString(), e);
+ }
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (CSVParser.this.isClosed()) {
+ return false;
+ }
+ if (this.current == null) {
+ this.current = this.getNextRecord();
+ }
+
+ return this.current != null;
+ }
+
+ @Override
+ public CSVRecord next() {
+ if (CSVParser.this.isClosed()) {
+ throw new NoSuchElementException(""CSVParser has been closed"");
+ }
+ CSVRecord next = this.current;
+ this.current = null;
+
+ if (next == null) {
+ // hasNext() wasn't called before
+ next = this.getNextRecord();
+ if (next == null) {
+ throw new NoSuchElementException(""No more CSV records available"");
+ }
+ }
+
+ return next;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testIteratorSequenceBreaking() throws IOException {
+ final String fiveRows = ""1\n2\n3\n4\n5\n"";
+
+ // Iterator hasNext() shouldn't break sequence
+ CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ int recordNumber = 0;
+ Iterator iter = parser.iterator();
+ recordNumber = 0;
+ while (iter.hasNext()) {
+ CSVRecord record = iter.next();
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ iter.hasNext();
+ while (iter.hasNext()) {
+ CSVRecord record = iter.next();
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+
+ // Consecutive enhanced for loops shouldn't break sequence
+ parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ recordNumber = 0;
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+
+ // Consecutive enhanced for loops with hasNext() peeking shouldn't break sequence
+ parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ recordNumber = 0;
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ parser.iterator().hasNext();
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test
+ public void testIteratorSequenceBreaking() throws IOException {
+ final String fiveRows = ""1\n2\n3\n4\n5\n"";
+
+ // Iterator hasNext() shouldn't break sequence
+ CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ int recordNumber = 0;
+ Iterator iter = parser.iterator();
+ recordNumber = 0;
+ while (iter.hasNext()) {
+ CSVRecord record = iter.next();
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ iter.hasNext();
+ while (iter.hasNext()) {
+ CSVRecord record = iter.next();
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+
+ // Consecutive enhanced for loops shouldn't break sequence
+ parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ recordNumber = 0;
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+
+ // Consecutive enhanced for loops with hasNext() peeking shouldn't break sequence
+ parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows));
+ recordNumber = 0;
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ if (recordNumber >= 2) {
+ break;
+ }
+ }
+ parser.iterator().hasNext();
+ for (CSVRecord record : parser) {
+ recordNumber++;
+ assertEquals(String.valueOf(recordNumber), record.get(0));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String get(final String name) {
+ if (mapping == null) {
+ throw new IllegalStateException(
+ ""No header mapping was specified, the record values can't be accessed by name"");
+ }
+ final Integer index = mapping.get(name);
+ return index != null ? values[index.intValue()] : null;
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = IllegalArgumentException.class)
+ public void testGetStringInconsistentRecord() {
+ header.put(""fourth"", Integer.valueOf(4));
+ recordWithHeader.get(""fourth"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ int readEscape() throws IOException {
+ // the escape char has just been read (normally a backslash)
+ final int c = in.read();
+ switch (c) {
+ case 'r':
+ return CR;
+ case 'n':
+ return LF;
+ case 't':
+ return TAB;
+ case 'b':
+ return BACKSPACE;
+ case 'f':
+ return FF;
+ case CR:
+ case LF:
+ case FF: // TODO is this correct?
+ case TAB: // TODO is this correct? Do tabs need to be escaped?
+ case BACKSPACE: // TODO is this correct?
+ return c;
+ case END_OF_STREAM:
+ throw new IOException(""EOF whilst processing escape sequence"");
+ default:
+ // Now check for meta-characters
+ return c;
+ // indicate unexpected char - available from in.getLastChar()
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testEscapedMySqlNullValue() throws Exception {
+ // MySQL uses \N to symbolize null values. We have to restore this
+ final Lexer lexer = getLexer(""character\\NEscaped"", formatWithEscaping);
+ assertThat(lexer.nextToken(new Token()), hasContent(""character\\NEscaped""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Map getHeaderMap() {
+ return new LinkedHashMap(this.headerMap);
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testNoHeaderMap() throws Exception {
+ final CSVParser parser = CSVParser.parse(""a,b,c\n1,2,3\nx,y,z"", CSVFormat.DEFAULT);
+ Assert.assertNull(parser.getHeaderMap());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void println() throws IOException {
+ final String recordSeparator = format.getRecordSeparator();
+ out.append(recordSeparator);
+ newRecord = true;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testNullRecordSeparatorCsv106() {
+ final CSVFormat format = CSVFormat.newFormat(';').withSkipHeaderRecord(true).withHeader(""H1"", ""H2"");
+ final String formatStr = format.format(""A"", ""B"");
+ assertNotNull(formatStr);
+ assertFalse(formatStr.endsWith(""null""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ > M putIn(final M map) {
+ for (final Entry entry : mapping.entrySet()) {
+ final int col = entry.getValue().intValue();
+ map.put(entry.getKey(), values[col]);
+ }
+ return map;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testToMapWithShortRecord() throws Exception {
+ final CSVParser parser = CSVParser.parse(""a,b"", CSVFormat.DEFAULT.withHeader(""A"", ""B"", ""C""));
+ final CSVRecord shortRec = parser.iterator().next();
+ shortRec.toMap();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Map initializeHeader() throws IOException {
+ Map hdrMap = null;
+ final String[] formatHeader = this.format.getHeader();
+ if (formatHeader != null) {
+ hdrMap = new LinkedHashMap();
+
+ String[] header = null;
+ if (formatHeader.length == 0) {
+ // read the header from the first line of the file
+ final CSVRecord nextRecord = this.nextRecord();
+ if (nextRecord != null) {
+ header = nextRecord.values();
+ }
+ } else {
+ if (this.format.getSkipHeaderRecord()) {
+ this.nextRecord();
+ }
+ header = formatHeader;
+ }
+
+ // build the name to index mappings
+ if (header != null) {
+ for (int i = 0; i < header.length; i++) {
+ hdrMap.put(header[i], Integer.valueOf(i));
+ }
+ }
+ }
+ return hdrMap;
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = IllegalStateException.class)
+ public void testDuplicateHeaderEntries() throws Exception {
+ CSVParser.parse(""a,b,a\n1,2,3\nx,y,z"", CSVFormat.DEFAULT.withHeader(new String[]{}));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ @Test(expected = IllegalStateException.class)
+ public void testDuplicateHeaderEntries() throws Exception {
+ CSVParser.parse(""a,b,a\n1,2,3\nx,y,z"", CSVFormat.DEFAULT.withHeader(new String[]{}));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private CSVFormat(final char delimiter, final Character quoteChar,
+ final Quote quotePolicy, final Character commentStart,
+ final Character escape, final boolean ignoreSurroundingSpaces,
+ final boolean ignoreEmptyLines, final String recordSeparator,
+ final String nullString, final String[] header, final boolean skipHeaderRecord) {
+ if (isLineBreak(delimiter)) {
+ throw new IllegalArgumentException(""The delimiter cannot be a line break"");
+ }
+ this.delimiter = delimiter;
+ this.quoteChar = quoteChar;
+ this.quotePolicy = quotePolicy;
+ this.commentStart = commentStart;
+ this.escape = escape;
+ this.ignoreSurroundingSpaces = ignoreSurroundingSpaces;
+ this.ignoreEmptyLines = ignoreEmptyLines;
+ this.recordSeparator = recordSeparator;
+ this.nullString = nullString;
+ if (header == null) {
+ this.header = null;
+ } else {
+ this.header = header.clone();
+ }
+ this.skipHeaderRecord = skipHeaderRecord;
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = IllegalArgumentException.class)
+ public void testDuplicateHeaderElements() {
+ CSVFormat.DEFAULT.withHeader(""A"", ""A"").validate();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ void validate() throws IllegalStateException {
+ if (quoteChar != null && delimiter == quoteChar.charValue()) {
+ throw new IllegalStateException(
+ ""The quoteChar character and the delimiter cannot be the same ('"" + quoteChar + ""')"");
+ }
+
+ if (escape != null && delimiter == escape.charValue()) {
+ throw new IllegalStateException(
+ ""The escape character and the delimiter cannot be the same ('"" + escape + ""')"");
+ }
+
+ if (commentStart != null && delimiter == commentStart.charValue()) {
+ throw new IllegalStateException(
+ ""The comment start character and the delimiter cannot be the same ('"" + commentStart + ""')"");
+ }
+
+ if (quoteChar != null && quoteChar.equals(commentStart)) {
+ throw new IllegalStateException(
+ ""The comment start character and the quoteChar cannot be the same ('"" + commentStart + ""')"");
+ }
+
+ if (escape != null && escape.equals(commentStart)) {
+ throw new IllegalStateException(
+ ""The comment start and the escape character cannot be the same ('"" + commentStart + ""')"");
+ }
+
+ if (escape == null && quotePolicy == Quote.NONE) {
+ throw new IllegalStateException(""No quotes mode set but no escape character is set"");
+ }
+
+ if (header != null) {
+ final Set set = new HashSet(header.length);
+ set.addAll(Arrays.asList(header));
+ if (set.size() != header.length) {
+ throw new IllegalStateException(""The header contains duplicate names: "" + Arrays.toString(header));
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test(expected = IllegalArgumentException.class)
+ public void testDuplicateHeaderElements() {
+ CSVFormat.DEFAULT.withHeader(""A"", ""A"").validate();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ > M putIn(final M map) {
+ for (final Entry entry : mapping.entrySet()) {
+ final int col = entry.getValue().intValue();
+ if (col < values.length) {
+ map.put(entry.getKey(), values[col]);
+ }
+ }
+ return map;
+ }
+
+// Test Case
+[/INST]
+ @Test
+ public void testToMapWithNoHeader() throws Exception {
+ final CSVParser parser = CSVParser.parse(""a,b"", CSVFormat.newFormat(','));
+ final CSVRecord shortRec = parser.iterator().next();
+ Map map = shortRec.toMap();
+ assertNotNull(""Map is not null."", map);
+ assertTrue(""Map is empty."", map.isEmpty());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static Type getActualType(
+ Type typeToEvaluate, Type parentType, Class> rawParentClass) {
+ if (typeToEvaluate instanceof Class>) {
+ return typeToEvaluate;
+ } else if (typeToEvaluate instanceof ParameterizedType) {
+ ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
+ Type owner = castedType.getOwnerType();
+ Type[] actualTypeParameters =
+ extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
+ Type rawType = castedType.getRawType();
+ return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
+ } else if (typeToEvaluate instanceof GenericArrayType) {
+ GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
+ Type componentType = castedType.getGenericComponentType();
+ Type actualType = getActualType(componentType, parentType, rawParentClass);
+ if (componentType.equals(actualType)) {
+ return castedType;
+ }
+ return actualType instanceof Class> ?
+ TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType))
+ : new GenericArrayTypeImpl(actualType);
+ } else if (typeToEvaluate instanceof TypeVariable>) {
+ if (parentType instanceof ParameterizedType) {
+ // The class definition has the actual types used for the type variables.
+ // Find the matching actual type for the Type Variable used for the field.
+ // For example, class Foo { A a; }
+ // new Foo(); defines the actual type of A to be Integer.
+ // So, to find the type of the field a, we will have to look at the class'
+ // actual type arguments.
+ TypeVariable> fieldTypeVariable = (TypeVariable>) typeToEvaluate;
+ TypeVariable>[] classTypeVariables = rawParentClass.getTypeParameters();
+ ParameterizedType objParameterizedType = (ParameterizedType) parentType;
+ int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
+ Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
+ return actualTypeArguments[indexOfActualTypeArgument];
+
+
+ }
+
+ throw new UnsupportedOperationException(""Expecting parameterized type, got "" + parentType
+ + "".\n Are you missing the use of TypeToken idiom?\n See ""
+ + ""http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener"");
+ } else if (typeToEvaluate instanceof WildcardType) {
+ WildcardType castedType = (WildcardType) typeToEvaluate;
+ return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
+ } else {
+ throw new IllegalArgumentException(""Type \'"" + typeToEvaluate + ""\' is not a Class, ""
+ + ""ParameterizedType, GenericArrayType or TypeVariable. Can't extract type."");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSingle() throws Exception {
+ Gson gson = new Gson();
+ Bar bar1 = new Bar(""someString"", 1);
+ ArrayList arrayList = new ArrayList();
+ arrayList.add(1);
+ arrayList.add(2);
+ bar1.map.put(""key1"", arrayList);
+ bar1.map.put(""key2"", new ArrayList());
+ String json = gson.toJson(bar1);
+ System.out.println(json);
+
+ Bar bar2 = gson.fromJson(json, Bar.class);
+ assertEquals(bar1, bar2);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testSingle() throws Exception {
+ Gson gson = new Gson();
+ Bar bar1 = new Bar(""someString"", 1);
+ ArrayList arrayList = new ArrayList();
+ arrayList.add(1);
+ arrayList.add(2);
+ bar1.map.put(""key1"", arrayList);
+ bar1.map.put(""key2"", new ArrayList());
+ String json = gson.toJson(bar1);
+ System.out.println(json);
+
+ Bar bar2 = gson.fromJson(json, Bar.class);
+ assertEquals(bar1, bar2);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private ReflectiveTypeAdapterFactory.BoundField createBoundField(
+ final Gson context, final Field field, final String name,
+ final TypeToken> fieldType, boolean serialize, boolean deserialize) {
+ final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());
+ // special casing primitives here saves ~5% on Android...
+ JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);
+ TypeAdapter> mapped = null;
+ if (annotation != null) {
+ mapped = getTypeAdapter(constructorConstructor, context, fieldType, annotation);
+ }
+ final boolean jsonAdapterPresent = mapped != null;
+ if (mapped == null) mapped = context.getAdapter(fieldType);
+
+ final TypeAdapter> typeAdapter = mapped;
+ return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {
+ @SuppressWarnings({""unchecked"", ""rawtypes""}) // the type adapter and field type always agree
+ @Override void write(JsonWriter writer, Object value)
+ throws IOException, IllegalAccessException {
+ Object fieldValue = field.get(value);
+ TypeAdapter t =
+ new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());
+ t.write(writer, fieldValue);
+ }
+ @Override void read(JsonReader reader, Object value)
+ throws IOException, IllegalAccessException {
+ Object fieldValue = typeAdapter.read(reader);
+ if (fieldValue != null || !isPrimitive) {
+ field.set(value, fieldValue);
+ }
+ }
+ @Override public boolean writeField(Object value) throws IOException, IllegalAccessException {
+ if (!serialized) return false;
+ Object fieldValue = field.get(value);
+ return fieldValue != value; // avoid recursion for example for Throwable.cause
+ }
+ };
+ }
+
+// Test Case
+[/INST]
+ public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() {
+ Gson gson = new Gson();
+ String json = gson.toJson(new GadgetWithPrimitivePart(42));
+ assertEquals(""{\""part\"":\""42\""}"", json);
+ GadgetWithPrimitivePart gadget = gson.fromJson(json, GadgetWithPrimitivePart.class);
+ assertEquals(42, gadget.part);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Number read(JsonReader in) throws IOException {
+ JsonToken jsonToken = in.peek();
+ switch (jsonToken) {
+ case NULL:
+ in.nextNull();
+ return null;
+ case NUMBER:
+ return new LazilyParsedNumber(in.nextString());
+ default:
+ throw new JsonSyntaxException(""Expecting number, got: "" + jsonToken);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNumberAsStringDeserialization() {
+ Number value = gson.fromJson(""\""18\"""", Number.class);
+ assertEquals(18, value.intValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override public void skipValue() throws IOException {
+ if (peek() == JsonToken.NAME) {
+ nextName();
+ pathNames[stackSize - 2] = ""null"";
+ } else {
+ popStack();
+ pathNames[stackSize - 1] = ""null"";
+ }
+ pathIndices[stackSize - 1]++;
+ }
+
+// Test Case
+[/INST]
+ public void testSkipValue_filledJsonObject() throws IOException {
+ JsonObject jsonObject = new JsonObject();
+ JsonArray jsonArray = new JsonArray();
+ jsonArray.add('c');
+ jsonArray.add(""text"");
+ jsonObject.add(""a"", jsonArray);
+ jsonObject.addProperty(""b"", true);
+ jsonObject.addProperty(""i"", 1);
+ jsonObject.add(""n"", JsonNull.INSTANCE);
+ JsonObject jsonObject2 = new JsonObject();
+ jsonObject2.addProperty(""n"", 2L);
+ jsonObject.add(""o"", jsonObject2);
+ jsonObject.addProperty(""s"", ""text"");
+ JsonTreeReader in = new JsonTreeReader(jsonObject);
+ in.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, in.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int peekNumber() throws IOException {
+ // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
+ char[] buffer = this.buffer;
+ int p = pos;
+ int l = limit;
+
+ long value = 0; // Negative to accommodate Long.MIN_VALUE more easily.
+ boolean negative = false;
+ boolean fitsInLong = true;
+ int last = NUMBER_CHAR_NONE;
+
+ int i = 0;
+
+ charactersOfNumber:
+ for (; true; i++) {
+ if (p + i == l) {
+ if (i == buffer.length) {
+ // Though this looks like a well-formed number, it's too long to continue reading. Give up
+ // and let the application handle this as an unquoted literal.
+ return PEEKED_NONE;
+ }
+ if (!fillBuffer(i + 1)) {
+ break;
+ }
+ p = pos;
+ l = limit;
+ }
+
+ char c = buffer[p + i];
+ switch (c) {
+ case '-':
+ if (last == NUMBER_CHAR_NONE) {
+ negative = true;
+ last = NUMBER_CHAR_SIGN;
+ continue;
+ } else if (last == NUMBER_CHAR_EXP_E) {
+ last = NUMBER_CHAR_EXP_SIGN;
+ continue;
+ }
+ return PEEKED_NONE;
+
+ case '+':
+ if (last == NUMBER_CHAR_EXP_E) {
+ last = NUMBER_CHAR_EXP_SIGN;
+ continue;
+ }
+ return PEEKED_NONE;
+
+ case 'e':
+ case 'E':
+ if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {
+ last = NUMBER_CHAR_EXP_E;
+ continue;
+ }
+ return PEEKED_NONE;
+
+ case '.':
+ if (last == NUMBER_CHAR_DIGIT) {
+ last = NUMBER_CHAR_DECIMAL;
+ continue;
+ }
+ return PEEKED_NONE;
+
+ default:
+ if (c < '0' || c > '9') {
+ if (!isLiteral(c)) {
+ break charactersOfNumber;
+ }
+ return PEEKED_NONE;
+ }
+ if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {
+ value = -(c - '0');
+ last = NUMBER_CHAR_DIGIT;
+ } else if (last == NUMBER_CHAR_DIGIT) {
+ if (value == 0) {
+ return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal).
+ }
+ long newValue = value * 10 - (c - '0');
+ fitsInLong &= value > MIN_INCOMPLETE_INTEGER
+ || (value == MIN_INCOMPLETE_INTEGER && newValue < value);
+ value = newValue;
+ } else if (last == NUMBER_CHAR_DECIMAL) {
+ last = NUMBER_CHAR_FRACTION_DIGIT;
+ } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {
+ last = NUMBER_CHAR_EXP_DIGIT;
+ }
+ }
+ }
+
+ // We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
+ if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
+ peekedLong = negative ? value : -value;
+ pos += i;
+ return peeked = PEEKED_LONG;
+ } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT
+ || last == NUMBER_CHAR_EXP_DIGIT) {
+ peekedNumberLength = i;
+ return peeked = PEEKED_NUMBER;
+ } else {
+ return PEEKED_NONE;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNegativeZero() throws Exception {
+ JsonReader reader = new JsonReader(reader(""[-0]""));
+ reader.setLenient(false);
+ reader.beginArray();
+ assertEquals(NUMBER, reader.peek());
+ assertEquals(""-0"", reader.nextString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static WildcardType subtypeOf(Type bound) {
+ Type[] upperBounds;
+ upperBounds = new Type[] { bound };
+ return new WildcardTypeImpl(upperBounds, EMPTY_TYPE_ARRAY);
+ }
+
+// Test Case
+[/INST]
+ public void testDoubleSupertype() {
+ assertEquals($Gson$Types.supertypeOf(Number.class),
+ $Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static WildcardType supertypeOf(Type bound) {
+ Type[] lowerBounds;
+ lowerBounds = new Type[] { bound };
+ return new WildcardTypeImpl(new Type[] { Object.class }, lowerBounds);
+ }
+
+// Test Case
+[/INST]
+ public void testDoubleSupertype() {
+ assertEquals($Gson$Types.supertypeOf(Number.class),
+ $Gson$Types.supertypeOf($Gson$Types.supertypeOf(Number.class)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter value(double value) throws IOException {
+ writeDeferredName();
+ if (Double.isNaN(value) || Double.isInfinite(value)) {
+ throw new IllegalArgumentException(""Numeric values must be finite, but was "" + value);
+ }
+ beforeValue();
+ out.append(Double.toString(value));
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testNonFiniteDoublesWhenLenient() throws IOException {
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.setLenient(true);
+ jsonWriter.beginArray();
+ jsonWriter.value(Double.NaN);
+ jsonWriter.value(Double.NEGATIVE_INFINITY);
+ jsonWriter.value(Double.POSITIVE_INFINITY);
+ jsonWriter.endArray();
+ assertEquals(""[NaN,-Infinity,Infinity]"", stringWriter.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static Type resolve(Type context, Class> contextRawType, Type toResolve,
+ Collection visitedTypeVariables) {
+ // this implementation is made a little more complicated in an attempt to avoid object-creation
+ while (true) {
+ if (toResolve instanceof TypeVariable) {
+ TypeVariable> typeVariable = (TypeVariable>) toResolve;
+ // cannot reduce due to infinite recursion
+ toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
+ if (toResolve == typeVariable) {
+ return toResolve;
+ }
+
+ } else if (toResolve instanceof Class && ((Class>) toResolve).isArray()) {
+ Class> original = (Class>) toResolve;
+ Type componentType = original.getComponentType();
+ Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
+ return componentType == newComponentType
+ ? original
+ : arrayOf(newComponentType);
+
+ } else if (toResolve instanceof GenericArrayType) {
+ GenericArrayType original = (GenericArrayType) toResolve;
+ Type componentType = original.getGenericComponentType();
+ Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
+ return componentType == newComponentType
+ ? original
+ : arrayOf(newComponentType);
+
+ } else if (toResolve instanceof ParameterizedType) {
+ ParameterizedType original = (ParameterizedType) toResolve;
+ Type ownerType = original.getOwnerType();
+ Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);
+ boolean changed = newOwnerType != ownerType;
+
+ Type[] args = original.getActualTypeArguments();
+ for (int t = 0, length = args.length; t < length; t++) {
+ Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);
+ if (resolvedTypeArgument != args[t]) {
+ if (!changed) {
+ args = args.clone();
+ changed = true;
+ }
+ args[t] = resolvedTypeArgument;
+ }
+ }
+
+ return changed
+ ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)
+ : original;
+
+ } else if (toResolve instanceof WildcardType) {
+ WildcardType original = (WildcardType) toResolve;
+ Type[] originalLowerBound = original.getLowerBounds();
+ Type[] originalUpperBound = original.getUpperBounds();
+
+ if (originalLowerBound.length == 1) {
+ Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);
+ if (lowerBound != originalLowerBound[0]) {
+ return supertypeOf(lowerBound);
+ }
+ } else if (originalUpperBound.length == 1) {
+ Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);
+ if (upperBound != originalUpperBound[0]) {
+ return subtypeOf(upperBound);
+ }
+ }
+ return original;
+
+ } else {
+ return toResolve;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testRecursiveTypeVariablesResolve12() throws Exception {
+ TypeAdapter adapter = new Gson().getAdapter(TestType2.class);
+ assertNotNull(adapter);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Date read(JsonReader in) throws IOException {
+ if (in.peek() != JsonToken.STRING) {
+ throw new JsonParseException(""The date should be a string value"");
+ }
+ Date date = deserializeToDate(in.nextString());
+ if (dateType == Date.class) {
+ return date;
+ } else if (dateType == Timestamp.class) {
+ return new Timestamp(date.getTime());
+ } else if (dateType == java.sql.Date.class) {
+ return new java.sql.Date(date.getTime());
+ } else {
+ // This must never happen: dateType is guarded in the primary constructor
+ throw new AssertionError();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testUnexpectedToken() throws Exception {
+ try {
+ DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter(Date.class);
+ adapter.fromJson(""{}"");
+ fail(""Unexpected token should fail."");
+ } catch (IllegalStateException expected) { }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static Type getSupertype(Type context, Class> contextRawType, Class> supertype) {
+ // wildcards are useless for resolving supertypes. As the upper bound has the same raw type, use it instead
+ checkArgument(supertype.isAssignableFrom(contextRawType));
+ return resolve(context, contextRawType,
+ $Gson$Types.getGenericSupertype(context, contextRawType, supertype));
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1107() {
+ String json = ""{\n"" +
+ "" \""inBig\"": {\n"" +
+ "" \""key\"": [\n"" +
+ "" { \""inSmall\"": \""hello\"" }\n"" +
+ "" ]\n"" +
+ "" }\n"" +
+ ""}"";
+ BigClass bigClass = new Gson().fromJson(json, BigClass.class);
+ SmallClass small = bigClass.inBig.get(""key"").get(0);
+ assertNotNull(small);
+ assertEquals(""hello"", small.inSmall);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static TypeAdapterFactory newTypeHierarchyFactory(
+ final Class clazz, final TypeAdapter typeAdapter) {
+ return new TypeAdapterFactory() {
+ @SuppressWarnings(""unchecked"")
+ public TypeAdapter create(Gson gson, TypeToken typeToken) {
+ final Class super T2> requestedType = typeToken.getRawType();
+ if (!clazz.isAssignableFrom(requestedType)) {
+ return null;
+ }
+ return (TypeAdapter) typeAdapter;
+
+ }
+ @Override public String toString() {
+ return ""Factory[typeHierarchy="" + clazz.getName() + "",adapter="" + typeAdapter + ""]"";
+ }
+ };
+ }
+
+// Test Case
+[/INST]
+ public void testJsonElementTypeMismatch() {
+ try {
+ gson.fromJson(""\""abc\"""", JsonObject.class);
+ fail();
+ } catch (JsonSyntaxException expected) {
+ assertEquals(""Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive"",
+ expected.getMessage());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"") // use runtime checks to guarantee that 'T' is what it is
+ private ObjectConstructor newDefaultImplementationConstructor(
+ final Type type, Class super T> rawType) {
+ if (Collection.class.isAssignableFrom(rawType)) {
+ if (SortedSet.class.isAssignableFrom(rawType)) {
+ return new ObjectConstructor() {
+ @Override public T construct() {
+ return (T) new TreeSet"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testConcurrentMap() throws Exception {
+ Type typeOfMap = new TypeToken>() {}.getType();
+ ConcurrentMap map = gson.fromJson(""{\""123\"":\""456\""}"", typeOfMap);
+ assertEquals(1, map.size());
+ assertTrue(map.containsKey(123));
+ assertEquals(""456"", map.get(123));
+ String json = gson.toJson(map);
+ assertEquals(""{\""123\"":\""456\""}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JsonWriter open(int empty, String openBracket) throws IOException {
+ beforeValue(true);
+ push(empty);
+ out.write(openBracket);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter value(String value) throws IOException {
+ if (value == null) {
+ return nullValue();
+ }
+ writeDeferredName();
+ beforeValue(false);
+ string(value);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter jsonValue(String value) throws IOException {
+ if (value == null) {
+ return nullValue();
+ }
+ writeDeferredName();
+ beforeValue(false);
+ out.append(value);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter nullValue() throws IOException {
+ if (deferredName != null) {
+ if (serializeNulls) {
+ writeDeferredName();
+ } else {
+ deferredName = null;
+ return this; // skip the name and the value
+ }
+ }
+ beforeValue(false);
+ out.write(""null"");
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter value(boolean value) throws IOException {
+ writeDeferredName();
+ beforeValue(false);
+ out.write(value ? ""true"" : ""false"");
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ int doPeek() throws IOException {
+ int peekStack = stack[stackSize - 1];
+ if (peekStack == JsonScope.EMPTY_ARRAY) {
+ stack[stackSize - 1] = JsonScope.NONEMPTY_ARRAY;
+ } else if (peekStack == JsonScope.NONEMPTY_ARRAY) {
+ // Look for a comma before the next element.
+ int c = nextNonWhitespace(true);
+ switch (c) {
+ case ']':
+ return peeked = PEEKED_END_ARRAY;
+ case ';':
+ checkLenient(); // fall-through
+ case ',':
+ break;
+ default:
+ throw syntaxError(""Unterminated array"");
+ }
+ } else if (peekStack == JsonScope.EMPTY_OBJECT || peekStack == JsonScope.NONEMPTY_OBJECT) {
+ stack[stackSize - 1] = JsonScope.DANGLING_NAME;
+ // Look for a comma before the next element.
+ if (peekStack == JsonScope.NONEMPTY_OBJECT) {
+ int c = nextNonWhitespace(true);
+ switch (c) {
+ case '}':
+ return peeked = PEEKED_END_OBJECT;
+ case ';':
+ checkLenient(); // fall-through
+ case ',':
+ break;
+ default:
+ throw syntaxError(""Unterminated object"");
+ }
+ }
+ int c = nextNonWhitespace(true);
+ switch (c) {
+ case '""':
+ return peeked = PEEKED_DOUBLE_QUOTED_NAME;
+ case '\'':
+ checkLenient();
+ return peeked = PEEKED_SINGLE_QUOTED_NAME;
+ case '}':
+ if (peekStack != JsonScope.NONEMPTY_OBJECT) {
+ return peeked = PEEKED_END_OBJECT;
+ } else {
+ throw syntaxError(""Expected name"");
+ }
+ default:
+ checkLenient();
+ pos--; // Don't consume the first character in an unquoted string.
+ if (isLiteral((char) c)) {
+ return peeked = PEEKED_UNQUOTED_NAME;
+ } else {
+ throw syntaxError(""Expected name"");
+ }
+ }
+ } else if (peekStack == JsonScope.DANGLING_NAME) {
+ stack[stackSize - 1] = JsonScope.NONEMPTY_OBJECT;
+ // Look for a colon before the value.
+ int c = nextNonWhitespace(true);
+ switch (c) {
+ case ':':
+ break;
+ case '=':
+ checkLenient();
+ if ((pos < limit || fillBuffer(1)) && buffer[pos] == '>') {
+ pos++;
+ }
+ break;
+ default:
+ throw syntaxError(""Expected ':'"");
+ }
+ } else if (peekStack == JsonScope.EMPTY_DOCUMENT) {
+ if (lenient) {
+ consumeNonExecutePrefix();
+ }
+ stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT;
+ } else if (peekStack == JsonScope.NONEMPTY_DOCUMENT) {
+ int c = nextNonWhitespace(false);
+ if (c == -1) {
+ return peeked = PEEKED_EOF;
+ } else {
+ checkLenient();
+ pos--;
+ }
+ } else if (peekStack == JsonScope.CLOSED) {
+ throw new IllegalStateException(""JsonReader is closed"");
+ }
+
+ int c = nextNonWhitespace(true);
+ switch (c) {
+ case ']':
+ if (peekStack == JsonScope.EMPTY_ARRAY) {
+ return peeked = PEEKED_END_ARRAY;
+ }
+ // fall-through to handle "",]""
+ case ';':
+ case ',':
+ // In lenient mode, a 0-length literal in an array means 'null'.
+ if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) {
+ checkLenient();
+ pos--;
+ return peeked = PEEKED_NULL;
+ } else {
+ throw syntaxError(""Unexpected value"");
+ }
+ case '\'':
+ checkLenient();
+ return peeked = PEEKED_SINGLE_QUOTED;
+ case '""':
+ if (stackSize == 1) {
+ checkLenient();
+ }
+ return peeked = PEEKED_DOUBLE_QUOTED;
+ case '[':
+ return peeked = PEEKED_BEGIN_ARRAY;
+ case '{':
+ return peeked = PEEKED_BEGIN_OBJECT;
+ default:
+ pos--; // Don't consume the first character in a literal value.
+ }
+ if (stackSize == 1) {
+ checkLenient();
+ }
+
+ int result = peekKeyword();
+ if (result != PEEKED_NONE) {
+ return result;
+ }
+
+ result = peekNumber();
+ if (result != PEEKED_NONE) {
+ return result;
+ }
+
+ if (!isLiteral(buffer[pos])) {
+ throw syntaxError(""Expected value"");
+ }
+
+ checkLenient();
+ return peeked = PEEKED_UNQUOTED;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter value(double value) throws IOException {
+ if (Double.isNaN(value) || Double.isInfinite(value)) {
+ throw new IllegalArgumentException(""Numeric values must be finite, but was "" + value);
+ }
+ writeDeferredName();
+ beforeValue(false);
+ out.append(Double.toString(value));
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter value(long value) throws IOException {
+ writeDeferredName();
+ beforeValue(false);
+ out.write(Long.toString(value));
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonWriter value(Number value) throws IOException {
+ if (value == null) {
+ return nullValue();
+ }
+
+ writeDeferredName();
+ String string = value.toString();
+ if (!lenient
+ && (string.equals(""-Infinity"") || string.equals(""Infinity"") || string.equals(""NaN""))) {
+ throw new IllegalArgumentException(""Numeric values must be finite, but was "" + value);
+ }
+ beforeValue(false);
+ out.append(string);
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void beforeValue(boolean root) throws IOException {
+ switch (peek()) {
+ case NONEMPTY_DOCUMENT:
+ if (!lenient) {
+ throw new IllegalStateException(
+ ""JSON must have only one top-level value."");
+ }
+ // fall-through
+ case EMPTY_DOCUMENT: // first in document
+ if (!lenient && !root) {
+ throw new IllegalStateException(
+ ""JSON must start with an array or an object."");
+ }
+ replaceTop(NONEMPTY_DOCUMENT);
+ break;
+
+ case EMPTY_ARRAY: // first in array
+ replaceTop(NONEMPTY_ARRAY);
+ newline();
+ break;
+
+ case NONEMPTY_ARRAY: // another in array
+ out.append(',');
+ newline();
+ break;
+
+ case DANGLING_NAME: // value for name
+ out.append(separator);
+ replaceTop(NONEMPTY_OBJECT);
+ break;
+
+ default:
+ throw new IllegalStateException(""Nesting problem."");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testTopLevelValueTypeWithSkipValue() throws IOException {
+ JsonReader reader = new JsonReader(reader(""true""));
+ reader.skipValue();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static Date parse(String date, ParsePosition pos) throws ParseException {
+ Exception fail = null;
+ try {
+ int offset = pos.getIndex();
+
+ // extract year
+ int year = parseInt(date, offset, offset += 4);
+ if (checkOffset(date, offset, '-')) {
+ offset += 1;
+ }
+
+ // extract month
+ int month = parseInt(date, offset, offset += 2);
+ if (checkOffset(date, offset, '-')) {
+ offset += 1;
+ }
+
+ // extract day
+ int day = parseInt(date, offset, offset += 2);
+ // default time value
+ int hour = 0;
+ int minutes = 0;
+ int seconds = 0;
+ int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
+
+ // if the value has no time component (and no time zone), we are done
+ boolean hasT = checkOffset(date, offset, 'T');
+
+ if (!hasT && (date.length() <= offset)) {
+ Calendar calendar = new GregorianCalendar(year, month - 1, day);
+
+ pos.setIndex(offset);
+ return calendar.getTime();
+ }
+
+ if (hasT) {
+
+ // extract hours, minutes, seconds and milliseconds
+ hour = parseInt(date, offset += 1, offset += 2);
+ if (checkOffset(date, offset, ':')) {
+ offset += 1;
+ }
+
+ minutes = parseInt(date, offset, offset += 2);
+ if (checkOffset(date, offset, ':')) {
+ offset += 1;
+ }
+ // second and milliseconds can be optional
+ if (date.length() > offset) {
+ char c = date.charAt(offset);
+ if (c != 'Z' && c != '+' && c != '-') {
+ seconds = parseInt(date, offset, offset += 2);
+ if (seconds > 59 && seconds < 63) seconds = 59; // truncate up to 3 leap seconds
+ // milliseconds can be optional in the format
+ if (checkOffset(date, offset, '.')) {
+ offset += 1;
+ int endOffset = indexOfNonDigit(date, offset + 1); // assume at least one digit
+ int parseEndOffset = Math.min(endOffset, offset + 3); // parse up to 3 digits
+ int fraction = parseInt(date, offset, parseEndOffset);
+ // compensate for ""missing"" digits
+ switch (parseEndOffset - offset) { // number of digits parsed
+ case 2:
+ milliseconds = fraction * 10;
+ break;
+ case 1:
+ milliseconds = fraction * 100;
+ break;
+ default:
+ milliseconds = fraction;
+ }
+ offset = endOffset;
+ }
+ }
+ }
+ }
+
+ // extract timezone
+ if (date.length() <= offset) {
+ throw new IllegalArgumentException(""No time zone indicator"");
+ }
+
+ TimeZone timezone = null;
+ char timezoneIndicator = date.charAt(offset);
+
+ if (timezoneIndicator == 'Z') {
+ timezone = TIMEZONE_UTC;
+ offset += 1;
+ } else if (timezoneIndicator == '+' || timezoneIndicator == '-') {
+ String timezoneOffset = date.substring(offset);
+
+ // When timezone has no minutes, we should append it, valid timezones are, for example: +00:00, +0000 and +00
+
+ offset += timezoneOffset.length();
+ // 18-Jun-2015, tatu: Minor simplification, skip offset of ""+0000""/""+00:00""
+ if (""+0000"".equals(timezoneOffset) || ""+00:00"".equals(timezoneOffset)) {
+ timezone = TIMEZONE_UTC;
+ } else {
+ // 18-Jun-2015, tatu: Looks like offsets only work from GMT, not UTC...
+ // not sure why, but that's the way it looks. Further, Javadocs for
+ // `java.util.TimeZone` specifically instruct use of GMT as base for
+ // custom timezones... odd.
+ String timezoneId = ""GMT"" + timezoneOffset;
+// String timezoneId = ""UTC"" + timezoneOffset;
+
+ timezone = TimeZone.getTimeZone(timezoneId);
+
+ String act = timezone.getID();
+ if (!act.equals(timezoneId)) {
+ /* 22-Jan-2015, tatu: Looks like canonical version has colons, but we may be given
+ * one without. If so, don't sweat.
+ * Yes, very inefficient. Hopefully not hit often.
+ * If it becomes a perf problem, add 'loose' comparison instead.
+ */
+ String cleaned = act.replace("":"", """");
+ if (!cleaned.equals(timezoneId)) {
+ throw new IndexOutOfBoundsException(""Mismatching time zone indicator: ""+timezoneId+"" given, resolves to ""
+ +timezone.getID());
+ }
+ }
+ }
+ } else {
+ throw new IndexOutOfBoundsException(""Invalid time zone indicator '"" + timezoneIndicator+""'"");
+ }
+
+ Calendar calendar = new GregorianCalendar(timezone);
+ calendar.setLenient(false);
+ calendar.set(Calendar.YEAR, year);
+ calendar.set(Calendar.MONTH, month - 1);
+ calendar.set(Calendar.DAY_OF_MONTH, day);
+ calendar.set(Calendar.HOUR_OF_DAY, hour);
+ calendar.set(Calendar.MINUTE, minutes);
+ calendar.set(Calendar.SECOND, seconds);
+ calendar.set(Calendar.MILLISECOND, milliseconds);
+
+ pos.setIndex(offset);
+ return calendar.getTime();
+ // If we get a ParseException it'll already have the right message/offset.
+ // Other exception types can convert here.
+ } catch (IndexOutOfBoundsException e) {
+ fail = e;
+ } catch (NumberFormatException e) {
+ fail = e;
+ } catch (IllegalArgumentException e) {
+ fail = e;
+ }
+ String input = (date == null) ? null : ('""' + date + ""'"");
+ String msg = fail.getMessage();
+ if (msg == null || msg.isEmpty()) {
+ msg = ""(""+fail.getClass().getName()+"")"";
+ }
+ ParseException ex = new ParseException(""Failed to parse date ["" + input + ""]: "" + msg, pos.getIndex());
+ ex.initCause(fail);
+ throw ex;
+ }
+
+// Test Case
+[/INST]
+ public void testDateDeserializationISO8601() throws Exception {
+ DefaultDateTypeAdapter adapter = new DefaultDateTypeAdapter();
+ assertParsed(""1970-01-01T00:00:00.000Z"", adapter);
+ assertParsed(""1970-01-01T00:00Z"", adapter);
+ assertParsed(""1970-01-01T00:00:00+00:00"", adapter);
+ assertParsed(""1970-01-01T01:00:00+01:00"", adapter);
+ assertParsed(""1970-01-01T01:00:00+01"", adapter);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ static TypeAdapter> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
+ TypeToken> fieldType, JsonAdapter annotation) {
+ Class> value = annotation.value();
+ TypeAdapter> typeAdapter;
+ if (TypeAdapter.class.isAssignableFrom(value)) {
+ Class> typeAdapterClass = (Class>) value;
+ typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct();
+ } else if (TypeAdapterFactory.class.isAssignableFrom(value)) {
+ Class typeAdapterFactory = (Class) value;
+ typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory))
+ .construct()
+ .create(gson, fieldType);
+ } else {
+ throw new IllegalArgumentException(
+ ""@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference."");
+ }
+ typeAdapter = typeAdapter.nullSafe();
+ return typeAdapter;
+ }
+
+// Test Case
+[/INST]
+ public void testNullSafeBugDeserialize() throws Exception {
+ Device device = gson.fromJson(""{'id':'ec57803e2'}"", Device.class);
+ assertEquals(""ec57803e2"", device.id);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public long nextLong() throws IOException {
+ int p = peeked;
+ if (p == PEEKED_NONE) {
+ p = doPeek();
+ }
+
+ if (p == PEEKED_LONG) {
+ peeked = PEEKED_NONE;
+ pathIndices[stackSize - 1]++;
+ return peekedLong;
+ }
+
+ if (p == PEEKED_NUMBER) {
+ peekedString = new String(buffer, pos, peekedNumberLength);
+ pos += peekedNumberLength;
+ } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) {
+ peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '""');
+ try {
+ long result = Long.parseLong(peekedString);
+ peeked = PEEKED_NONE;
+ pathIndices[stackSize - 1]++;
+ return result;
+ } catch (NumberFormatException ignored) {
+ // Fall back to parse as a double below.
+ }
+ } else {
+ throw new IllegalStateException(""Expected a long but was "" + peek()
+ + "" at line "" + getLineNumber() + "" column "" + getColumnNumber() + "" path "" + getPath());
+ }
+
+ peeked = PEEKED_BUFFERED;
+ double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
+ long result = (long) asDouble;
+ if (result != asDouble) { // Make sure no precision was lost casting to 'long'.
+ throw new NumberFormatException(""Expected a long but was "" + peekedString
+ + "" at line "" + getLineNumber() + "" column "" + getColumnNumber() + "" path "" + getPath());
+ }
+ peekedString = null;
+ peeked = PEEKED_NONE;
+ pathIndices[stackSize - 1]++;
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testMapDeserializationWithUnquotedLongKeys() {
+ long longKey = 9876543210L;
+ String json = String.format(""{%d:\""456\""}"", longKey);
+ Type typeOfMap = new TypeToken"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int nextInt() throws IOException {
+ int p = peeked;
+ if (p == PEEKED_NONE) {
+ p = doPeek();
+ }
+
+ int result;
+ if (p == PEEKED_LONG) {
+ result = (int) peekedLong;
+ if (peekedLong != result) { // Make sure no precision was lost casting to 'int'.
+ throw new NumberFormatException(""Expected an int but was "" + peekedLong
+ + "" at line "" + getLineNumber() + "" column "" + getColumnNumber() + "" path "" + getPath());
+ }
+ peeked = PEEKED_NONE;
+ pathIndices[stackSize - 1]++;
+ return result;
+ }
+
+ if (p == PEEKED_NUMBER) {
+ peekedString = new String(buffer, pos, peekedNumberLength);
+ pos += peekedNumberLength;
+ } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) {
+ peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '""');
+ try {
+ result = Integer.parseInt(peekedString);
+ peeked = PEEKED_NONE;
+ pathIndices[stackSize - 1]++;
+ return result;
+ } catch (NumberFormatException ignored) {
+ // Fall back to parse as a double below.
+ }
+ } else {
+ throw new IllegalStateException(""Expected an int but was "" + peek()
+ + "" at line "" + getLineNumber() + "" column "" + getColumnNumber() + "" path "" + getPath());
+ }
+
+ peeked = PEEKED_BUFFERED;
+ double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException.
+ result = (int) asDouble;
+ if (result != asDouble) { // Make sure no precision was lost casting to 'int'.
+ throw new NumberFormatException(""Expected an int but was "" + peekedString
+ + "" at line "" + getLineNumber() + "" column "" + getColumnNumber() + "" path "" + getPath());
+ }
+ peekedString = null;
+ peeked = PEEKED_NONE;
+ pathIndices[stackSize - 1]++;
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testMapDeserializationWithUnquotedLongKeys() {
+ long longKey = 9876543210L;
+ String json = String.format(""{%d:\""456\""}"", longKey);
+ Type typeOfMap = new TypeToken"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static UnsafeAllocator create() {
+ // try JVM
+ // public class Unsafe {
+ // public Object allocateInstance(Class> type);
+ // }
+ try {
+ Class> unsafeClass = Class.forName(""sun.misc.Unsafe"");
+ Field f = unsafeClass.getDeclaredField(""theUnsafe"");
+ f.setAccessible(true);
+ final Object unsafe = f.get(null);
+ final Method allocateInstance = unsafeClass.getMethod(""allocateInstance"", Class.class);
+ return new UnsafeAllocator() {
+ @Override
+ @SuppressWarnings(""unchecked"")
+ public T newInstance(Class c) throws Exception {
+ return (T) allocateInstance.invoke(unsafe, c);
+ }
+ };
+ } catch (Exception ignored) {
+ }
+
+ // try dalvikvm, post-gingerbread
+ // public class ObjectStreamClass {
+ // private static native int getConstructorId(Class> c);
+ // private static native Object newInstance(Class> instantiationClass, int methodId);
+ // }
+ try {
+ Method getConstructorId = ObjectStreamClass.class
+ .getDeclaredMethod(""getConstructorId"", Class.class);
+ getConstructorId.setAccessible(true);
+ final int constructorId = (Integer) getConstructorId.invoke(null, Object.class);
+ final Method newInstance = ObjectStreamClass.class
+ .getDeclaredMethod(""newInstance"", Class.class, int.class);
+ newInstance.setAccessible(true);
+ return new UnsafeAllocator() {
+ @Override
+ @SuppressWarnings(""unchecked"")
+ public T newInstance(Class c) throws Exception {
+ return (T) newInstance.invoke(null, c, constructorId);
+ }
+ };
+ } catch (Exception ignored) {
+ }
+
+ // try dalvikvm, pre-gingerbread
+ // public class ObjectInputStream {
+ // private static native Object newInstance(
+ // Class> instantiationClass, Class> constructorClass);
+ // }
+ try {
+ final Method newInstance = ObjectInputStream.class
+ .getDeclaredMethod(""newInstance"", Class.class, Class.class);
+ newInstance.setAccessible(true);
+ return new UnsafeAllocator() {
+ @Override
+ @SuppressWarnings(""unchecked"")
+ public T newInstance(Class c) throws Exception {
+ return (T) newInstance.invoke(null, c, Object.class);
+ }
+ };
+ } catch (Exception ignored) {
+ }
+
+ // give up
+ return new UnsafeAllocator() {
+ @Override
+ public T newInstance(Class c) {
+ throw new UnsupportedOperationException(""Cannot allocate "" + c);
+ }
+ };
+ }
+
+// Test Case
+[/INST]
+ public void testInterfaceInstantiation() {
+ UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+ try {
+ unsafeAllocator.newInstance(Interface.class);
+ fail();
+ } catch (Exception e) {
+ assertEquals(e.getClass(), UnsupportedOperationException.class);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testInterfaceInstantiation() {
+ UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+ try {
+ unsafeAllocator.newInstance(Interface.class);
+ fail();
+ } catch (Exception e) {
+ assertEquals(e.getClass(), UnsupportedOperationException.class);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testInterfaceInstantiation() {
+ UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();
+ try {
+ unsafeAllocator.newInstance(Interface.class);
+ fail();
+ } catch (Exception e) {
+ assertEquals(e.getClass(), UnsupportedOperationException.class);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void write(JsonWriter out, Boolean value) throws IOException {
+ if (value == null) {
+ out.nullValue();
+ return;
+ }
+ out.value(value);
+ }
+
+// Test Case
+[/INST]
+ public void testBoxedBooleans() throws IOException {
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.beginArray();
+ jsonWriter.value((Boolean) true);
+ jsonWriter.value((Boolean) false);
+ jsonWriter.value((Boolean) null);
+ jsonWriter.endArray();
+ assertEquals(""[true,false,null]"", stringWriter.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testBoxedBooleans() throws IOException {
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.beginArray();
+ jsonWriter.value((Boolean) true);
+ jsonWriter.value((Boolean) false);
+ jsonWriter.value((Boolean) null);
+ jsonWriter.endArray();
+ assertEquals(""[true,false,null]"", stringWriter.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testBoxedBooleans() throws IOException {
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.beginArray();
+ jsonWriter.value((Boolean) true);
+ jsonWriter.value((Boolean) false);
+ jsonWriter.value((Boolean) null);
+ jsonWriter.endArray();
+ assertEquals(""[true,false,null]"", stringWriter.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static BigDecimal parseBigDecimal(String numStr) throws NumberFormatException
+ {
+ return new BigDecimal(numStr);
+ }
+
+// Test Case
+[/INST]
+ public void testAllowNaN() throws Exception {
+ _testAllowNaN(false);
+ _testAllowNaN(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static BigDecimal parseBigDecimal(char[] buffer, int offset, int len)
+ throws NumberFormatException
+ {
+ return new BigDecimal(buffer, offset, len);
+ }
+
+// Test Case
+[/INST]
+ public void testAllowNaN() throws Exception {
+ _testAllowNaN(false);
+ _testAllowNaN(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public BigDecimal contentsAsDecimal()
+ throws NumberFormatException
+ {
+ // Already got a pre-cut array?
+ if (_resultArray != null) {
+ return NumberInput.parseBigDecimal(_resultArray);
+ }
+ // Or a shared buffer?
+ if (_inputStart >= 0) {
+ return NumberInput.parseBigDecimal(_inputBuffer, _inputStart, _inputLen);
+ }
+ // Or if not, just a single buffer (the usual case)
+ if (_segmentSize == 0) {
+ return NumberInput.parseBigDecimal(_currentSegment, 0, _currentSize);
+ }
+ // If not, let's just get it aggregated...
+ return NumberInput.parseBigDecimal(contentsAsArray());
+ }
+
+// Test Case
+[/INST]
+ public void testAllowNaN() throws Exception {
+ _testAllowNaN(false);
+ _testAllowNaN(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int _findOffsetForAdd(int hash)
+ {
+ // first, check the primary:
+ int offset = _calcOffset(hash);
+ final int[] hashArea = _hashArea;
+ if (hashArea[offset+3] == 0) {
+//System.err.printf("" PRImary slot #%d, hash %X\n"", (offset>>2), hash & 0x7F);
+ return offset;
+ }
+ // then secondary
+ int offset2 = _secondaryStart + ((offset >> 3) << 2);
+ if (hashArea[offset2+3] == 0) {
+//System.err.printf("" SECondary slot #%d (start x%X), hash %X\n"",(offset >> 3), _secondaryStart, (hash & 0x7F));
+ return offset2;
+ }
+ // if not, tertiary?
+
+ offset2 = _tertiaryStart + ((offset >> (_tertiaryShift + 2)) << _tertiaryShift);
+ final int bucketSize = (1 << _tertiaryShift);
+ for (int end = offset2 + bucketSize; offset2 < end; offset2 += 4) {
+ if (hashArea[offset2+3] == 0) {
+//System.err.printf("" TERtiary slot x%X (from x%X, start x%X), hash %X.\n"", offset2, ((offset >> (_tertiaryShift + 2)) << _tertiaryShift), _tertiaryStart, (hash & 0x7F));
+ return offset2;
+ }
+ }
+
+ // and if even tertiary full, append at the end of spill area
+ offset = _spilloverEnd;
+ _spilloverEnd += 4;
+
+//System.err.printf("" SPIll-over at x%X; start x%X; end x%X, hash %X\n"", offset, _spilloverStart(), _hashArea.length, (hash & 0x7F));
+
+ // one caveat: in the unlikely event if spill-over filling up,
+ // check if that could be considered a DoS attack; handle appropriately
+ // (NOTE: approximate for now; we could verify details if that becomes necessary)
+ /* 31-Jul-2015, tatu: Note that spillover area does NOT end at end of array,
+ * since ""long names"" area follows. Instead, need to calculate from hash size.
+ */
+ if (_spilloverEnd >= hashArea.length) {
+ if (_failOnDoS) {
+ _reportTooManyCollisions();
+ }
+ // and if we didn't fail, we'll simply force rehash for next add
+ // (which, in turn, may double up or nuke contents, depending on size etc)
+ _needRehash = true;
+ }
+ return offset;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue207() throws Exception
+ {
+ ByteQuadsCanonicalizer nc = ByteQuadsCanonicalizer.createRoot(-523743345);
+ Field byteSymbolCanonicalizerField = JsonFactory.class.getDeclaredField(""_byteSymbolCanonicalizer"");
+ byteSymbolCanonicalizerField.setAccessible(true);
+ JsonFactory jsonF = new JsonFactory();
+ byteSymbolCanonicalizerField.set(jsonF, nc);
+
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append(""{\n"");
+ stringBuilder.append("" \""expectedGCperPosition\"": null"");
+ for (int i = 0; i < 60; ++i) {
+ stringBuilder.append("",\n \"""").append(i + 1).append(""\"": null"");
+ }
+ stringBuilder.append(""\n}"");
+
+ JsonParser p = jsonF.createParser(stringBuilder.toString().getBytes(""UTF-8""));
+ while (p.nextToken() != null) { }
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int calcHash(int q1)
+ {
+ int hash = q1 ^ _seed;
+ /* 29-Mar-2015, tatu: Earlier used 15 + 9 right shifts, which worked ok
+ * except for one specific problem case: numbers. So needed to make sure
+ * that all 4 least-significant bits participate in hash. Couple of ways
+ * to work it out, but this is the simplest, fast and seems to do ok.
+ */
+ hash += (hash >>> 16); // to xor hi- and low- 16-bits
+ hash ^= (hash >>> 12);
+ return hash;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue207() throws Exception
+ {
+ ByteQuadsCanonicalizer nc = ByteQuadsCanonicalizer.createRoot(-523743345);
+ Field byteSymbolCanonicalizerField = JsonFactory.class.getDeclaredField(""_byteSymbolCanonicalizer"");
+ byteSymbolCanonicalizerField.setAccessible(true);
+ JsonFactory jsonF = new JsonFactory();
+ byteSymbolCanonicalizerField.set(jsonF, nc);
+
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append(""{\n"");
+ stringBuilder.append("" \""expectedGCperPosition\"": null"");
+ for (int i = 0; i < 60; ++i) {
+ stringBuilder.append("",\n \"""").append(i + 1).append(""\"": null"");
+ }
+ stringBuilder.append(""\n}"");
+
+ JsonParser p = jsonF.createParser(stringBuilder.toString().getBytes(""UTF-8""));
+ while (p.nextToken() != null) { }
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void _verifySharing()
+ {
+ if (_hashShared) {
+ _hashArea = Arrays.copyOf(_hashArea, _hashArea.length);
+ _names = Arrays.copyOf(_names, _names.length);
+ _hashShared = false;
+ // 09-Sep-2015, tatu: As per [jackson-core#216], also need to ensure
+ // we rehash as needed, as need-rehash flag is not copied from parent
+ }
+ if (_needRehash) {
+ rehash();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSymbolTableExpansionBytes() throws Exception {
+ _testSymbolTableExpansion(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final JsonToken nextToken() throws IOException
+ {
+ /* First: field names are special -- we will always tokenize
+ * (part of) value along with field name to simplify
+ * state handling. If so, can and need to use secondary token:
+ */
+ if (_currToken == JsonToken.FIELD_NAME) {
+ return _nextAfterName();
+ }
+ // But if we didn't already have a name, and (partially?) decode number,
+ // need to ensure no numeric information is leaked
+ _numTypesValid = NR_UNKNOWN;
+ if (_tokenIncomplete) {
+ _skipString(); // only strings can be partial
+ }
+ int i = _skipWSOrEnd();
+ if (i < 0) { // end-of-input
+ /* 19-Feb-2009, tatu: Should actually close/release things
+ * like input source, symbol table and recyclable buffers now.
+ */
+ close();
+ return (_currToken = null);
+ }
+ // clear any data retained so far
+ _binaryValue = null;
+
+ // Closing scope?
+ if (i == INT_RBRACKET) {
+ _updateLocation();
+ if (!_parsingContext.inArray()) {
+ _reportMismatchedEndMarker(i, '}');
+ }
+ _parsingContext = _parsingContext.getParent();
+ return (_currToken = JsonToken.END_ARRAY);
+ }
+ if (i == INT_RCURLY) {
+ _updateLocation();
+ if (!_parsingContext.inObject()) {
+ _reportMismatchedEndMarker(i, ']');
+ }
+ _parsingContext = _parsingContext.getParent();
+ return (_currToken = JsonToken.END_OBJECT);
+ }
+
+ // Nope: do we then expect a comma?
+ if (_parsingContext.expectComma()) {
+ i = _skipComma(i);
+ }
+ _updateLocation();
+
+ /* And should we now have a name? Always true for Object contexts, since
+ * the intermediate 'expect-value' state is never retained.
+ */
+ boolean inObject = _parsingContext.inObject();
+ if (inObject) {
+ // First, field name itself:
+ String name = (i == INT_QUOTE) ? _parseName() : _handleOddName(i);
+ _parsingContext.setCurrentName(name);
+ _currToken = JsonToken.FIELD_NAME;
+ i = _skipColon();
+ }
+
+ // Ok: we must have a value... what is it?
+
+ JsonToken t;
+
+ switch (i) {
+ case '""':
+ _tokenIncomplete = true;
+ t = JsonToken.VALUE_STRING;
+ break;
+ case '[':
+ if (!inObject) {
+ _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
+ }
+ t = JsonToken.START_ARRAY;
+ break;
+ case '{':
+ if (!inObject) {
+ _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
+ }
+ t = JsonToken.START_OBJECT;
+ break;
+ case ']':
+ case '}':
+ // Error: neither is valid at this point; valid closers have
+ // been handled earlier
+ _reportUnexpectedChar(i, ""expected a value"");
+ case 't':
+ _matchTrue();
+ t = JsonToken.VALUE_TRUE;
+ break;
+ case 'f':
+ _matchFalse();
+ t = JsonToken.VALUE_FALSE;
+ break;
+ case 'n':
+ _matchNull();
+ t = JsonToken.VALUE_NULL;
+ break;
+
+ case '-':
+ /* Should we have separate handling for plus? Although
+ * it is not allowed per se, it may be erroneously used,
+ * and could be indicate by a more specific error message.
+ */
+ t = _parseNegNumber();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ t = _parsePosNumber(i);
+ break;
+ default:
+ t = _handleOddValue(i);
+ break;
+ }
+
+ if (inObject) {
+ _nextToken = t;
+ return _currToken;
+ }
+ _currToken = t;
+ return t;
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean nextFieldName(SerializableString sstr) throws IOException
+ {
+ // // // Note: most of code below is copied from nextToken()
+
+ _numTypesValid = NR_UNKNOWN;
+ if (_currToken == JsonToken.FIELD_NAME) {
+ _nextAfterName();
+ return false;
+ }
+ if (_tokenIncomplete) {
+ _skipString();
+ }
+ int i = _skipWSOrEnd();
+ if (i < 0) {
+ close();
+ _currToken = null;
+ return false;
+ }
+ _binaryValue = null;
+
+ if (i == INT_RBRACKET) {
+ _updateLocation();
+ if (!_parsingContext.inArray()) {
+ _reportMismatchedEndMarker(i, '}');
+ }
+ _parsingContext = _parsingContext.getParent();
+ _currToken = JsonToken.END_ARRAY;
+ return false;
+ }
+ if (i == INT_RCURLY) {
+ _updateLocation();
+ if (!_parsingContext.inObject()) {
+ _reportMismatchedEndMarker(i, ']');
+ }
+ _parsingContext = _parsingContext.getParent();
+ _currToken = JsonToken.END_OBJECT;
+ return false;
+ }
+ if (_parsingContext.expectComma()) {
+ i = _skipComma(i);
+ }
+ _updateLocation();
+
+ if (!_parsingContext.inObject()) {
+ _nextTokenNotInObject(i);
+ return false;
+ }
+
+ if (i == INT_QUOTE) {
+ // when doing literal match, must consider escaping:
+ char[] nameChars = sstr.asQuotedChars();
+ final int len = nameChars.length;
+
+ // Require 4 more bytes for faster skipping of colon that follows name
+ if ((_inputPtr + len + 4) < _inputEnd) { // maybe...
+ // first check length match by
+ final int end = _inputPtr+len;
+ if (_inputBuffer[end] == '""') {
+ int offset = 0;
+ int ptr = _inputPtr;
+ while (true) {
+ if (ptr == end) { // yes, match!
+ _parsingContext.setCurrentName(sstr.getValue());
+ _isNextTokenNameYes(_skipColonFast(ptr+1));
+ return true;
+ }
+ if (nameChars[offset] != _inputBuffer[ptr]) {
+ break;
+ }
+ ++offset;
+ ++ptr;
+ }
+ }
+ }
+ }
+ return _isNextTokenNameMaybe(i, sstr.getValue());
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String nextFieldName() throws IOException
+ {
+ // // // Note: this is almost a verbatim copy of nextToken() (minus comments)
+
+ _numTypesValid = NR_UNKNOWN;
+ if (_currToken == JsonToken.FIELD_NAME) {
+ _nextAfterName();
+ return null;
+ }
+ if (_tokenIncomplete) {
+ _skipString();
+ }
+ int i = _skipWSOrEnd();
+ if (i < 0) {
+ close();
+ _currToken = null;
+ return null;
+ }
+ _binaryValue = null;
+ if (i == INT_RBRACKET) {
+ _updateLocation();
+ if (!_parsingContext.inArray()) {
+ _reportMismatchedEndMarker(i, '}');
+ }
+ _parsingContext = _parsingContext.getParent();
+ _currToken = JsonToken.END_ARRAY;
+ return null;
+ }
+ if (i == INT_RCURLY) {
+ _updateLocation();
+ if (!_parsingContext.inObject()) {
+ _reportMismatchedEndMarker(i, ']');
+ }
+ _parsingContext = _parsingContext.getParent();
+ _currToken = JsonToken.END_OBJECT;
+ return null;
+ }
+ if (_parsingContext.expectComma()) {
+ i = _skipComma(i);
+ }
+ _updateLocation();
+ if (!_parsingContext.inObject()) {
+ _nextTokenNotInObject(i);
+ return null;
+ }
+
+ String name = (i == INT_QUOTE) ? _parseName() : _handleOddName(i);
+ _parsingContext.setCurrentName(name);
+ _currToken = JsonToken.FIELD_NAME;
+ i = _skipColon();
+
+ if (i == INT_QUOTE) {
+ _tokenIncomplete = true;
+ _nextToken = JsonToken.VALUE_STRING;
+ return name;
+ }
+
+ // Ok: we must have a value... what is it?
+
+ JsonToken t;
+
+ switch (i) {
+ case '-':
+ t = _parseNegNumber();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ t = _parsePosNumber(i);
+ break;
+ case 'f':
+ _matchFalse();
+ t = JsonToken.VALUE_FALSE;
+ break;
+ case 'n':
+ _matchNull();
+ t = JsonToken.VALUE_NULL;
+ break;
+ case 't':
+ _matchTrue();
+ t = JsonToken.VALUE_TRUE;
+ break;
+ case '[':
+ t = JsonToken.START_ARRAY;
+ break;
+ case '{':
+ t = JsonToken.START_OBJECT;
+ break;
+ default:
+ t = _handleOddValue(i);
+ break;
+ }
+ _nextToken = t;
+ return name;
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final void _isNextTokenNameYes(int i) throws IOException
+ {
+ _currToken = JsonToken.FIELD_NAME;
+
+ switch (i) {
+ case '""':
+ _tokenIncomplete = true;
+ _nextToken = JsonToken.VALUE_STRING;
+ return;
+ case '[':
+ _nextToken = JsonToken.START_ARRAY;
+ return;
+ case '{':
+ _nextToken = JsonToken.START_OBJECT;
+ return;
+ case 't':
+ _matchToken(""true"", 1);
+ _nextToken = JsonToken.VALUE_TRUE;
+ return;
+ case 'f':
+ _matchToken(""false"", 1);
+ _nextToken = JsonToken.VALUE_FALSE;
+ return;
+ case 'n':
+ _matchToken(""null"", 1);
+ _nextToken = JsonToken.VALUE_NULL;
+ return;
+ case '-':
+ _nextToken = _parseNegNumber();
+ return;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ _nextToken = _parsePosNumber(i);
+ return;
+ }
+ _nextToken = _handleOddValue(i);
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected boolean _isNextTokenNameMaybe(int i, String nameToMatch) throws IOException
+ {
+ // // // and this is back to standard nextToken()
+ String name = (i == INT_QUOTE) ? _parseName() : _handleOddName(i);
+ _parsingContext.setCurrentName(name);
+ _currToken = JsonToken.FIELD_NAME;
+ i = _skipColon();
+ if (i == INT_QUOTE) {
+ _tokenIncomplete = true;
+ _nextToken = JsonToken.VALUE_STRING;
+ return nameToMatch.equals(name);
+ }
+ // Ok: we must have a value... what is it?
+ JsonToken t;
+ switch (i) {
+ case '-':
+ t = _parseNegNumber();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ t = _parsePosNumber(i);
+ break;
+ case 'f':
+ _matchFalse();
+ t = JsonToken.VALUE_FALSE;
+ break;
+ case 'n':
+ _matchNull();
+ t = JsonToken.VALUE_NULL;
+ break;
+ case 't':
+ _matchTrue();
+ t = JsonToken.VALUE_TRUE;
+ break;
+ case '[':
+ t = JsonToken.START_ARRAY;
+ break;
+ case '{':
+ t = JsonToken.START_OBJECT;
+ break;
+ default:
+ t = _handleOddValue(i);
+ break;
+ }
+ _nextToken = t;
+ return nameToMatch.equals(name);
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonLocation getTokenLocation()
+ {
+ final Object src = _ioContext.getSourceReference();
+ return new JsonLocation(src,
+ -1L, getTokenCharacterOffset(),
+ getTokenLineNr(),
+ getTokenColumnNr());
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonLocation getTokenLocation()
+ {
+ final Object src = _ioContext.getSourceReference();
+ if (_currToken == JsonToken.FIELD_NAME) {
+ return new JsonLocation(src,
+ _nameInputTotal, -1L, _nameInputRow, _tokenInputCol);
+ }
+ return new JsonLocation(src,
+ getTokenCharacterOffset(), -1L, getTokenLineNr(),
+ getTokenColumnNr());
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithObjectFieldsUsingReader() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ char[] c = ""{\""f1\"":\""v1\"",\""f2\"":{\""f3\"":\""v3\""},\""f4\"":[true,false],\""f5\"":5}"".toCharArray();
+ // 1 6 11 16 17 22 28 33 34 39 46 51
+ JsonParser p = f.createParser(c);
+
+ assertEquals(JsonToken.START_OBJECT, p.nextToken());
+
+ assertEquals(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(1L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ assertEquals(6L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f2"", p.nextFieldName());
+ assertEquals(11L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_OBJECT, p.nextValue());
+ assertEquals(16L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(""f3"", p.nextFieldName());
+ assertEquals(17L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_STRING, p.nextValue());
+ assertEquals(22L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ assertEquals(""f4"", p.nextFieldName());
+ assertEquals(28L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.START_ARRAY, p.nextValue());
+ assertEquals(33L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_TRUE, p.nextValue());
+ assertEquals(34L, p.getTokenLocation().getCharOffset());
+
+ assertEquals(JsonToken.VALUE_FALSE, p.nextValue());
+ assertEquals(39L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_ARRAY, p.nextToken());
+
+ assertEquals(""f5"", p.nextFieldName());
+ assertEquals(46L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(51L, p.getTokenLocation().getCharOffset());
+ assertEquals(JsonToken.END_OBJECT, p.nextToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testFieldNameQuotingEnabled() throws IOException
+ {
+ // // First, test with default factory, with quoting enabled by default
+
+ // First, default, with quotes
+ _testFieldNameQuotingEnabled(JSON_F, true, true, ""{\""foo\"":1}"");
+ _testFieldNameQuotingEnabled(JSON_F, false, true, ""{\""foo\"":1}"");
+
+ // then without quotes
+ _testFieldNameQuotingEnabled(JSON_F, true, false, ""{foo:1}"");
+ _testFieldNameQuotingEnabled(JSON_F, false, false, ""{foo:1}"");
+
+ // // Then with alternatively configured factory
+
+ JsonFactory JF2 = new JsonFactory();
+ JF2.disable(JsonGenerator.Feature.QUOTE_FIELD_NAMES);
+
+ _testFieldNameQuotingEnabled(JF2, true, true, ""{\""foo\"":1}"");
+ _testFieldNameQuotingEnabled(JF2, false, true, ""{\""foo\"":1}"");
+
+ // then without quotes
+ _testFieldNameQuotingEnabled(JF2, true, false, ""{foo:1}"");
+ _testFieldNameQuotingEnabled(JF2, false, false, ""{foo:1}"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final void _verifyRelease(byte[] toRelease, byte[] src) {
+ // 07-Mar-2016, tatu: As per [core#255], only prevent shrinking of buffer
+ if ((toRelease != src) && (toRelease.length <= src.length)) { throw wrongBuf(); }
+ }
+
+// Test Case
+[/INST]
+ public void testAllocations() throws Exception
+ {
+ IOContext ctxt = new IOContext(new BufferRecycler(), ""N/A"", true);
+
+ /* I/O Read buffer */
+
+ // First succeeds:
+ assertNotNull(ctxt.allocReadIOBuffer());
+ // second fails
+ try {
+ ctxt.allocReadIOBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ // Also: can't succeed with different buffer
+ try {
+ ctxt.releaseReadIOBuffer(new byte[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ // but call with null is a NOP for convenience
+ ctxt.releaseReadIOBuffer(null);
+
+ /* I/O Write buffer */
+
+ assertNotNull(ctxt.allocWriteEncodingBuffer());
+ try {
+ ctxt.allocWriteEncodingBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseWriteEncodingBuffer(new byte[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseWriteEncodingBuffer(null);
+
+ /* Token (read) buffer */
+
+ assertNotNull(ctxt.allocTokenBuffer());
+ try {
+ ctxt.allocTokenBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseTokenBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseTokenBuffer(null);
+
+ /* Concat (write?) buffer */
+
+ assertNotNull(ctxt.allocConcatBuffer());
+ try {
+ ctxt.allocConcatBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseConcatBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseConcatBuffer(null);
+
+ /* NameCopy (write?) buffer */
+
+ assertNotNull(ctxt.allocNameCopyBuffer(100));
+ try {
+ ctxt.allocNameCopyBuffer(100);
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseNameCopyBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseNameCopyBuffer(null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final void _verifyRelease(char[] toRelease, char[] src) {
+ // 07-Mar-2016, tatu: As per [core#255], only prevent shrinking of buffer
+ if ((toRelease != src) && (toRelease.length <= src.length)) { throw wrongBuf(); }
+ }
+
+// Test Case
+[/INST]
+ public void testAllocations() throws Exception
+ {
+ IOContext ctxt = new IOContext(new BufferRecycler(), ""N/A"", true);
+
+ /* I/O Read buffer */
+
+ // First succeeds:
+ assertNotNull(ctxt.allocReadIOBuffer());
+ // second fails
+ try {
+ ctxt.allocReadIOBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ // Also: can't succeed with different buffer
+ try {
+ ctxt.releaseReadIOBuffer(new byte[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ // but call with null is a NOP for convenience
+ ctxt.releaseReadIOBuffer(null);
+
+ /* I/O Write buffer */
+
+ assertNotNull(ctxt.allocWriteEncodingBuffer());
+ try {
+ ctxt.allocWriteEncodingBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseWriteEncodingBuffer(new byte[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseWriteEncodingBuffer(null);
+
+ /* Token (read) buffer */
+
+ assertNotNull(ctxt.allocTokenBuffer());
+ try {
+ ctxt.allocTokenBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseTokenBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseTokenBuffer(null);
+
+ /* Concat (write?) buffer */
+
+ assertNotNull(ctxt.allocConcatBuffer());
+ try {
+ ctxt.allocConcatBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseConcatBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseConcatBuffer(null);
+
+ /* NameCopy (write?) buffer */
+
+ assertNotNull(ctxt.allocNameCopyBuffer(100));
+ try {
+ ctxt.allocNameCopyBuffer(100);
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseNameCopyBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseNameCopyBuffer(null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private IllegalArgumentException wrongBuf() {
+ // sanity check failed; trying to return different, smaller buffer.
+return new IllegalArgumentException(""Trying to release buffer not owned by the context"");
+ }
+
+// Test Case
+[/INST]
+ public void testAllocations() throws Exception
+ {
+ IOContext ctxt = new IOContext(new BufferRecycler(), ""N/A"", true);
+
+ /* I/O Read buffer */
+
+ // First succeeds:
+ assertNotNull(ctxt.allocReadIOBuffer());
+ // second fails
+ try {
+ ctxt.allocReadIOBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ // Also: can't succeed with different buffer
+ try {
+ ctxt.releaseReadIOBuffer(new byte[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ // but call with null is a NOP for convenience
+ ctxt.releaseReadIOBuffer(null);
+
+ /* I/O Write buffer */
+
+ assertNotNull(ctxt.allocWriteEncodingBuffer());
+ try {
+ ctxt.allocWriteEncodingBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseWriteEncodingBuffer(new byte[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseWriteEncodingBuffer(null);
+
+ /* Token (read) buffer */
+
+ assertNotNull(ctxt.allocTokenBuffer());
+ try {
+ ctxt.allocTokenBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseTokenBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseTokenBuffer(null);
+
+ /* Concat (write?) buffer */
+
+ assertNotNull(ctxt.allocConcatBuffer());
+ try {
+ ctxt.allocConcatBuffer();
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseConcatBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseConcatBuffer(null);
+
+ /* NameCopy (write?) buffer */
+
+ assertNotNull(ctxt.allocNameCopyBuffer(100));
+ try {
+ ctxt.allocNameCopyBuffer(100);
+ } catch (IllegalStateException e) {
+ verifyException(e, ""second time"");
+ }
+ try {
+ ctxt.releaseNameCopyBuffer(new char[1]);
+ } catch (IllegalArgumentException e) {
+ verifyException(e, ""smaller than original"");
+ }
+ ctxt.releaseNameCopyBuffer(null);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonToken nextToken() throws IOException
+ {
+ //Check for _allowMultipleMatches - false and atleast there is one token - which is _currToken
+ // check for no buffered context _exposedContext - null
+ //If all the conditions matches then check for scalar / non-scalar property
+ //if not scalar and ended successfully, then return null
+ //else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once
+ // then return null
+ // Anything buffered?
+ TokenFilterContext ctxt = _exposedContext;
+
+ if (ctxt != null) {
+ while (true) {
+ JsonToken t = ctxt.nextTokenToRead();
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ // all done with buffered stuff?
+ if (ctxt == _headContext) {
+ _exposedContext = null;
+ if (ctxt.inArray()) {
+ t = delegate.getCurrentToken();
+// Is this guaranteed to work without further checks?
+// if (t != JsonToken.START_ARRAY) {
+ _currToken = t;
+ return t;
+ }
+
+ // Almost! Most likely still have the current token;
+ // with the sole exception of
+ /*
+ t = delegate.getCurrentToken();
+ if (t != JsonToken.FIELD_NAME) {
+ _currToken = t;
+ return t;
+ }
+ */
+ break;
+ }
+ // If not, traverse down the context chain
+ ctxt = _headContext.findChildOf(ctxt);
+ _exposedContext = ctxt;
+ if (ctxt == null) { // should never occur
+ throw _constructError(""Unexpected problem: chain of filtered context broken"");
+ }
+ }
+ }
+
+ // If not, need to read more. If we got any:
+ JsonToken t = delegate.nextToken();
+ if (t == null) {
+ // no strict need to close, since we have no state here
+ return (_currToken = t);
+ }
+
+ // otherwise... to include or not?
+ TokenFilter f;
+
+ switch (t.id()) {
+ case ID_START_ARRAY:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ break;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ break;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartArray();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildArrayContext(f, false);
+
+ // Also: only need buffering if parent path to be included
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ break;
+
+ case ID_START_OBJECT:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ break;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ break;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartObject();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildObjectContext(f, false);
+ // Also: only need buffering if parent path to be included
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ // note: inclusion of surrounding Object handled separately via
+ // FIELD_NAME
+ break;
+
+ case ID_END_ARRAY:
+ case ID_END_OBJECT:
+ {
+ boolean returnEnd = _headContext.isStartHandled();
+ f = _headContext.getFilter();
+ if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
+ f.filterFinishArray();
+ }
+ _headContext = _headContext.getParent();
+ _itemFilter = _headContext.getFilter();
+ if (returnEnd) {
+ return (_currToken = t);
+ }
+ }
+ break;
+
+ case ID_FIELD_NAME:
+ {
+ final String name = delegate.getCurrentName();
+ // note: this will also set 'needToHandleName'
+ f = _headContext.setFieldName(name);
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _itemFilter = f;
+ if (!_includePath) {
+ // Minor twist here: if parent NOT included, may need to induce output of
+ // surrounding START_OBJECT/END_OBJECT
+ if (_includeImmediateParent && !_headContext.isStartHandled()) {
+ t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
+ _exposedContext = _headContext;
+ }
+ }
+ return (_currToken = t);
+ }
+ if (f == null) {
+ delegate.nextToken();
+ delegate.skipChildren();
+ break;
+ }
+ f = f.includeProperty(name);
+ if (f == null) {
+ delegate.nextToken();
+ delegate.skipChildren();
+ break;
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ if (_includePath) {
+ return (_currToken = t);
+ }
+ }
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ break;
+ }
+
+ default: // scalar value
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ return (_currToken = t);
+ }
+ if (f != null) {
+ f = _headContext.checkValue(f);
+ if ((f == TokenFilter.INCLUDE_ALL)
+ || ((f != null) && f.includeValue(delegate))) {
+ return (_currToken = t);
+ }
+ }
+ // Otherwise not included (leaves must be explicitly included)
+ break;
+ }
+
+ // We get here if token was not yet found; offlined handling
+ return _nextToken2();
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""resource"")
+ public void testNotAllowMultipleMatches() throws Exception
+ {
+ String jsonString = aposToQuotes(""{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'value':4,'b':true}"");
+ JsonParser p0 = JSON_F.createParser(jsonString);
+ JsonParser p = new FilteringParserDelegate(p0,
+ new NameMatchFilter(""value""),
+ false, // includePath
+ false // multipleMatches -false
+ );
+ String result = readAndWrite(JSON_F, p);
+ assertEquals(aposToQuotes(""3""), result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonParserSequence(JsonParser[] parsers)
+ {
+ super(parsers[0]);
+ _parsers = parsers;
+ _nextParser = 1;
+ }
+
+// Test Case
+[/INST]
+ public void testInitialized() throws Exception
+ {
+ JsonParser p1 = JSON_FACTORY.createParser(""1 2"");
+ JsonParser p2 = JSON_FACTORY.createParser(""3 false"");
+ // consume '1', move to '2'
+ assertToken(JsonToken.VALUE_NUMBER_INT, p1.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p1.nextToken());
+
+ JsonParserSequence seq = JsonParserSequence.createFlattened(p1, p2);
+ assertToken(JsonToken.VALUE_NUMBER_INT, seq.nextToken());
+ assertEquals(2, seq.getIntValue());
+ assertToken(JsonToken.VALUE_NUMBER_INT, seq.nextToken());
+ assertEquals(3, seq.getIntValue());
+ seq.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonToken nextToken() throws IOException, JsonParseException
+ {
+ JsonToken t = delegate.nextToken();
+ if (t != null) return t;
+ while (switchToNext()) {
+ t = delegate.nextToken();
+ if (t != null) return t;
+ }
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testInitialized() throws Exception
+ {
+ JsonParser p1 = JSON_FACTORY.createParser(""1 2"");
+ JsonParser p2 = JSON_FACTORY.createParser(""3 false"");
+ // consume '1', move to '2'
+ assertToken(JsonToken.VALUE_NUMBER_INT, p1.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p1.nextToken());
+
+ JsonParserSequence seq = JsonParserSequence.createFlattened(p1, p2);
+ assertToken(JsonToken.VALUE_NUMBER_INT, seq.nextToken());
+ assertEquals(2, seq.getIntValue());
+ assertToken(JsonToken.VALUE_NUMBER_INT, seq.nextToken());
+ assertEquals(3, seq.getIntValue());
+ seq.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testInitialized() throws Exception
+ {
+ JsonParser p1 = JSON_FACTORY.createParser(""1 2"");
+ JsonParser p2 = JSON_FACTORY.createParser(""3 false"");
+ // consume '1', move to '2'
+ assertToken(JsonToken.VALUE_NUMBER_INT, p1.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p1.nextToken());
+
+ JsonParserSequence seq = JsonParserSequence.createFlattened(p1, p2);
+ assertToken(JsonToken.VALUE_NUMBER_INT, seq.nextToken());
+ assertEquals(2, seq.getIntValue());
+ assertToken(JsonToken.VALUE_NUMBER_INT, seq.nextToken());
+ assertEquals(3, seq.getIntValue());
+ seq.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeRaw(String text, int offset, int len) throws IOException
+ {
+ final char[] buf = _charBuffer;
+
+ // minor optimization: see if we can just get and copy
+
+ // If not, need segmented approach. For speed, let's also use input buffer
+ // size that is guaranteed to fit in output buffer; each char can expand to
+ // at most 3 bytes, so at most 1/3 of buffer size.
+
+ while (len > 0) {
+ int len2 = Math.min(buf.length, len);
+ text.getChars(offset, offset+len2, buf, 0);
+ writeRaw(buf, 0, len2);
+ // If this is NOT the last segment and if the last character looks like
+ // split surrogate second half, drop it
+ offset += len2;
+ len -= len2;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testRawWithSurrogatesString() throws Exception {
+ _testRawWithSurrogatesString(false);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final int _outputRawMultiByteChar(int ch, char[] cbuf, int inputOffset, int inputEnd)
+ throws IOException
+ {
+ // Let's handle surrogates gracefully (as 4 byte output):
+ if (ch >= SURR1_FIRST) {
+ if (ch <= SURR2_LAST) { // yes, outside of BMP
+ // Do we have second part?
+ if (inputOffset >= inputEnd || cbuf == null) { // nope... have to note down
+ _reportError(""Split surrogate on writeRaw() input (last character)"");
+ }
+ _outputSurrogates(ch, cbuf[inputOffset]);
+ return inputOffset+1;
+ }
+ }
+ final byte[] bbuf = _outputBuffer;
+ bbuf[_outputTail++] = (byte) (0xe0 | (ch >> 12));
+ bbuf[_outputTail++] = (byte) (0x80 | ((ch >> 6) & 0x3f));
+ bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f));
+ return inputOffset;
+ }
+
+// Test Case
+[/INST]
+ public void testRawWithSurrogatesString() throws Exception {
+ _testRawWithSurrogatesString(false);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testRawWithSurrogatesString() throws Exception {
+ _testRawWithSurrogatesString(false);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected String _asString(BigDecimal value) throws IOException {
+ // 24-Aug-2016, tatu: [core#315] prevent possible DoS vector
+ return value.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testTooBigBigDecimal() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ f.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
+
+ // 24-Aug-2016, tatu: Initial check limits scale to [-9999,+9999]
+ BigDecimal BIG = new BigDecimal(""1E+9999"");
+ BigDecimal TOO_BIG = new BigDecimal(""1E+10000"");
+ BigDecimal SMALL = new BigDecimal(""1E-9999"");
+ BigDecimal TOO_SMALL = new BigDecimal(""1E-10000"");
+
+ for (boolean useBytes : new boolean[] { false, true } ) {
+ for (boolean asString : new boolean[] { false, true } ) {
+ JsonGenerator g;
+
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+
+ // first, ok cases:
+ g.writeStartArray();
+ g.writeNumber(BIG);
+ g.writeNumber(SMALL);
+ g.writeEndArray();
+ g.close();
+
+ // then invalid
+ for (BigDecimal input : new BigDecimal[] { TOO_BIG, TOO_SMALL }) {
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+ try {
+ g.writeNumber(input);
+ fail(""Should not have written without exception: ""+input);
+ } catch (JsonGenerationException e) {
+ verifyException(e, ""Attempt to write plain `java.math.BigDecimal`"");
+ verifyException(e, ""illegal scale"");
+ }
+ g.close();
+ }
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(BigDecimal value) throws IOException
+ {
+ // Don't really know max length for big decimal, no point checking
+ _verifyValueWrite(WRITE_NUMBER);
+ if (value == null) {
+ _writeNull();
+ } else if (_cfgNumbersAsStrings) {
+ String raw = isEnabled(Feature.WRITE_BIGDECIMAL_AS_PLAIN) ? value.toPlainString() : value.toString();
+ _writeQuotedRaw(raw);
+ } else if (isEnabled(Feature.WRITE_BIGDECIMAL_AS_PLAIN)) {
+ writeRaw(value.toPlainString());
+ } else {
+ writeRaw(_asString(value));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testTooBigBigDecimal() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ f.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
+
+ // 24-Aug-2016, tatu: Initial check limits scale to [-9999,+9999]
+ BigDecimal BIG = new BigDecimal(""1E+9999"");
+ BigDecimal TOO_BIG = new BigDecimal(""1E+10000"");
+ BigDecimal SMALL = new BigDecimal(""1E-9999"");
+ BigDecimal TOO_SMALL = new BigDecimal(""1E-10000"");
+
+ for (boolean useBytes : new boolean[] { false, true } ) {
+ for (boolean asString : new boolean[] { false, true } ) {
+ JsonGenerator g;
+
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+
+ // first, ok cases:
+ g.writeStartArray();
+ g.writeNumber(BIG);
+ g.writeNumber(SMALL);
+ g.writeEndArray();
+ g.close();
+
+ // then invalid
+ for (BigDecimal input : new BigDecimal[] { TOO_BIG, TOO_SMALL }) {
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+ try {
+ g.writeNumber(input);
+ fail(""Should not have written without exception: ""+input);
+ } catch (JsonGenerationException e) {
+ verifyException(e, ""Attempt to write plain `java.math.BigDecimal`"");
+ verifyException(e, ""illegal scale"");
+ }
+ g.close();
+ }
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(BigDecimal value) throws IOException
+ {
+ // Don't really know max length for big decimal, no point checking
+ _verifyValueWrite(WRITE_NUMBER);
+ if (value == null) {
+ _writeNull();
+ } else if (_cfgNumbersAsStrings) {
+ String raw = Feature.WRITE_BIGDECIMAL_AS_PLAIN.enabledIn(_features) ? value.toPlainString() : value.toString();
+ _writeQuotedRaw(raw);
+ } else if (Feature.WRITE_BIGDECIMAL_AS_PLAIN.enabledIn(_features)) {
+ writeRaw(value.toPlainString());
+ } else {
+ writeRaw(_asString(value));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testTooBigBigDecimal() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ f.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
+
+ // 24-Aug-2016, tatu: Initial check limits scale to [-9999,+9999]
+ BigDecimal BIG = new BigDecimal(""1E+9999"");
+ BigDecimal TOO_BIG = new BigDecimal(""1E+10000"");
+ BigDecimal SMALL = new BigDecimal(""1E-9999"");
+ BigDecimal TOO_SMALL = new BigDecimal(""1E-10000"");
+
+ for (boolean useBytes : new boolean[] { false, true } ) {
+ for (boolean asString : new boolean[] { false, true } ) {
+ JsonGenerator g;
+
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+
+ // first, ok cases:
+ g.writeStartArray();
+ g.writeNumber(BIG);
+ g.writeNumber(SMALL);
+ g.writeEndArray();
+ g.close();
+
+ // then invalid
+ for (BigDecimal input : new BigDecimal[] { TOO_BIG, TOO_SMALL }) {
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+ try {
+ g.writeNumber(input);
+ fail(""Should not have written without exception: ""+input);
+ } catch (JsonGenerationException e) {
+ verifyException(e, ""Attempt to write plain `java.math.BigDecimal`"");
+ verifyException(e, ""illegal scale"");
+ }
+ g.close();
+ }
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testTooBigBigDecimal() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ f.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
+
+ // 24-Aug-2016, tatu: Initial check limits scale to [-9999,+9999]
+ BigDecimal BIG = new BigDecimal(""1E+9999"");
+ BigDecimal TOO_BIG = new BigDecimal(""1E+10000"");
+ BigDecimal SMALL = new BigDecimal(""1E-9999"");
+ BigDecimal TOO_SMALL = new BigDecimal(""1E-10000"");
+
+ for (boolean useBytes : new boolean[] { false, true } ) {
+ for (boolean asString : new boolean[] { false, true } ) {
+ JsonGenerator g;
+
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+
+ // first, ok cases:
+ g.writeStartArray();
+ g.writeNumber(BIG);
+ g.writeNumber(SMALL);
+ g.writeEndArray();
+ g.close();
+
+ // then invalid
+ for (BigDecimal input : new BigDecimal[] { TOO_BIG, TOO_SMALL }) {
+ if (useBytes) {
+ g = f.createGenerator(new ByteArrayOutputStream());
+ } else {
+ g = f.createGenerator(new StringWriter());
+ }
+ if (asString) {
+ g.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
+ }
+ try {
+ g.writeNumber(input);
+ fail(""Should not have written without exception: ""+input);
+ } catch (JsonGenerationException e) {
+ verifyException(e, ""Attempt to write plain `java.math.BigDecimal`"");
+ verifyException(e, ""illegal scale"");
+ }
+ g.close();
+ }
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final JsonToken _parseNumber2(boolean neg, int startPtr) throws IOException
+ {
+ _inputPtr = neg ? (startPtr+1) : startPtr;
+ char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
+ int outPtr = 0;
+
+ // Need to prepend sign?
+ if (neg) {
+ outBuf[outPtr++] = '-';
+ }
+
+ // This is the place to do leading-zero check(s) too:
+ int intLen = 0;
+ char c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++] : getNextChar(""No digit following minus sign"");
+ if (c == '0') {
+ c = _verifyNoLeadingZeroes();
+ }
+ boolean eof = false;
+
+ // Ok, first the obligatory integer part:
+ int_loop:
+ while (c >= '0' && c <= '9') {
+ ++intLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ // EOF is legal for main level int values
+ c = CHAR_NULL;
+ eof = true;
+ break int_loop;
+ }
+ c = _inputBuffer[_inputPtr++];
+ }
+ // Also, integer part is not optional
+ if (intLen == 0) {
+ return _handleInvalidNumberStart(c, neg);
+ }
+
+ int fractLen = 0;
+ // And then see if we get other parts
+ if (c == '.') { // yes, fraction
+ outBuf[outPtr++] = c;
+
+ fract_loop:
+ while (true) {
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break fract_loop;
+ }
+ c = _inputBuffer[_inputPtr++];
+ if (c < INT_0 || c > INT_9) {
+ break fract_loop;
+ }
+ ++fractLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (fractLen == 0) {
+ reportUnexpectedNumberChar(c, ""Decimal point not followed by a digit"");
+ }
+ }
+
+ int expLen = 0;
+ if (c == 'e' || c == 'E') { // exponent?
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ // Not optional, can require that we get one more char
+ c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++]
+ : getNextChar(""expected a digit for number exponent"");
+ // Sign indicator?
+ if (c == '-' || c == '+') {
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ // Likewise, non optional:
+ c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++]
+ : getNextChar(""expected a digit for number exponent"");
+ }
+
+ exp_loop:
+ while (c <= INT_9 && c >= INT_0) {
+ ++expLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break exp_loop;
+ }
+ c = _inputBuffer[_inputPtr++];
+ }
+ // must be followed by sequence of ints, one minimum
+ if (expLen == 0) {
+ reportUnexpectedNumberChar(c, ""Exponent indicator not followed by a digit"");
+ }
+ }
+
+ // Ok; unless we hit end-of-input, need to push last char read back
+ if (!eof) {
+ --_inputPtr;
+ if (_parsingContext.inRoot()) {
+ _verifyRootSpace(c);
+ }
+ }
+ _textBuffer.setCurrentLength(outPtr);
+ // And there we have it!
+ return reset(neg, intLen, fractLen, expLen);
+ }
+
+// Test Case
+[/INST]
+ public void testLongerFloatingPoint() throws Exception
+ {
+ StringBuilder input = new StringBuilder();
+ for (int i = 1; i < 201; i++) {
+ input.append(1);
+ }
+ input.append("".0"");
+ final String DOC = input.toString();
+
+ // test out with both Reader and ByteArrayInputStream
+ JsonParser p;
+
+ p = FACTORY.createParser(new StringReader(DOC));
+ _testLongerFloat(p, DOC);
+ p.close();
+
+ p = FACTORY.createParser(new ByteArrayInputStream(DOC.getBytes(""UTF-8"")));
+ _testLongerFloat(p, DOC);
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final JsonToken _parseFloat(char[] outBuf, int outPtr, int c,
+ boolean negative, int integerPartLength) throws IOException
+ {
+ int fractLen = 0;
+ boolean eof = false;
+
+ // And then see if we get other parts
+ if (c == INT_PERIOD) { // yes, fraction
+ outBuf[outPtr++] = (char) c;
+
+ fract_loop:
+ while (true) {
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break fract_loop;
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ if (c < INT_0 || c > INT_9) {
+ break fract_loop;
+ }
+ ++fractLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (fractLen == 0) {
+ reportUnexpectedNumberChar(c, ""Decimal point not followed by a digit"");
+ }
+ }
+
+ int expLen = 0;
+ if (c == INT_e || c == INT_E) { // exponent?
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ // Not optional, can require that we get one more char
+ if (_inputPtr >= _inputEnd) {
+ loadMoreGuaranteed();
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ // Sign indicator?
+ if (c == '-' || c == '+') {
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ // Likewise, non optional:
+ if (_inputPtr >= _inputEnd) {
+ loadMoreGuaranteed();
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ }
+
+ exp_loop:
+ while (c <= INT_9 && c >= INT_0) {
+ ++expLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break exp_loop;
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (expLen == 0) {
+ reportUnexpectedNumberChar(c, ""Exponent indicator not followed by a digit"");
+ }
+ }
+
+ // Ok; unless we hit end-of-input, need to push last char read back
+ if (!eof) {
+ --_inputPtr;
+ // As per [core#105], need separating space between root values; check here
+ if (_parsingContext.inRoot()) {
+ _verifyRootSpace(c);
+ }
+ }
+ _textBuffer.setCurrentLength(outPtr);
+
+ // And there we have it!
+ return resetFloat(negative, integerPartLength, fractLen, expLen);
+ }
+
+// Test Case
+[/INST]
+ public void testLongerFloatingPoint() throws Exception
+ {
+ StringBuilder input = new StringBuilder();
+ for (int i = 1; i < 201; i++) {
+ input.append(1);
+ }
+ input.append("".0"");
+ final String DOC = input.toString();
+
+ // test out with both Reader and ByteArrayInputStream
+ JsonParser p;
+
+ p = FACTORY.createParser(new StringReader(DOC));
+ _testLongerFloat(p, DOC);
+ p.close();
+
+ p = FACTORY.createParser(new ByteArrayInputStream(DOC.getBytes(""UTF-8"")));
+ _testLongerFloat(p, DOC);
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonToken _parseNumber(int ch) throws IOException
+ {
+ /* Although we will always be complete with respect to textual
+ * representation (that is, all characters will be parsed),
+ * actual conversion to a number is deferred. Thus, need to
+ * note that no representations are valid yet
+ */
+ boolean negative = (ch == INT_MINUS);
+ int ptr = _inputPtr;
+ int startPtr = ptr-1; // to include sign/digit already read
+ final int inputLen = _inputEnd;
+
+ dummy_loop:
+ do { // dummy loop, to be able to break out
+ if (negative) { // need to read the next digit
+ if (ptr >= _inputEnd) {
+ break dummy_loop;
+ }
+ ch = _inputBuffer[ptr++];
+ // First check: must have a digit to follow minus sign
+ if (ch > INT_9 || ch < INT_0) {
+ _inputPtr = ptr;
+ return _handleInvalidNumberStart(ch, true);
+ }
+ /* (note: has been checked for non-negative already, in
+ * the dispatching code that determined it should be
+ * a numeric value)
+ */
+ }
+ // One special case, leading zero(es):
+ if (ch == INT_0) {
+ break dummy_loop;
+ }
+
+ /* First, let's see if the whole number is contained within
+ * the input buffer unsplit. This should be the common case;
+ * and to simplify processing, we will just reparse contents
+ * in the alternative case (number split on buffer boundary)
+ */
+
+ int intLen = 1; // already got one
+
+ // First let's get the obligatory integer part:
+
+ int_loop:
+ while (true) {
+ if (ptr >= _inputEnd) {
+ break dummy_loop;
+ }
+ ch = (int) _inputBuffer[ptr++];
+ if (ch < INT_0 || ch > INT_9) {
+ break int_loop;
+ }
+ ++intLen;
+ }
+
+ int fractLen = 0;
+
+ // And then see if we get other parts
+ if (ch == '.') { // yes, fraction
+ fract_loop:
+ while (true) {
+ if (ptr >= inputLen) {
+ break dummy_loop;
+ }
+ ch = (int) _inputBuffer[ptr++];
+ if (ch < INT_0 || ch > INT_9) {
+ break fract_loop;
+ }
+ ++fractLen;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (fractLen == 0) {
+ reportUnexpectedNumberChar(ch, ""Decimal point not followed by a digit"");
+ }
+ }
+
+ int expLen = 0;
+ if (ch == 'e' || ch == 'E') { // and/or exponent
+ if (ptr >= inputLen) {
+ break dummy_loop;
+ }
+ // Sign indicator?
+ ch = (int) _inputBuffer[ptr++];
+ if (ch == INT_MINUS || ch == INT_PLUS) { // yup, skip for now
+ if (ptr >= inputLen) {
+ break dummy_loop;
+ }
+ ch = (int) _inputBuffer[ptr++];
+ }
+ while (ch <= INT_9 && ch >= INT_0) {
+ ++expLen;
+ if (ptr >= inputLen) {
+ break dummy_loop;
+ }
+ ch = (int) _inputBuffer[ptr++];
+ }
+ // must be followed by sequence of ints, one minimum
+ if (expLen == 0) {
+ reportUnexpectedNumberChar(ch, ""Exponent indicator not followed by a digit"");
+ }
+ }
+ // Got it all: let's add to text buffer for parsing, access
+ --ptr; // need to push back following separator
+ _inputPtr = ptr;
+ // As per #105, need separating space between root values; check here
+ int len = ptr-startPtr;
+ _textBuffer.resetWithShared(_inputBuffer, startPtr, len);
+ return reset(negative, intLen, fractLen, expLen);
+ } while (false);
+
+ _inputPtr = negative ? (startPtr+1) : startPtr;
+ return _parseNumber2(negative);
+ }
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JsonToken _parseNumber2(boolean negative) throws IOException
+ {
+ char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
+ int outPtr = 0;
+
+ // Need to prepend sign?
+ if (negative) {
+ outBuf[outPtr++] = '-';
+ }
+
+ // This is the place to do leading-zero check(s) too:
+ int intLen = 0;
+ char c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++] : getNextChar(""No digit following minus sign"");
+ if (c == '0') {
+ c = _verifyNoLeadingZeroes();
+ }
+ boolean eof = false;
+
+ // Ok, first the obligatory integer part:
+ int_loop:
+ while (c >= '0' && c <= '9') {
+ ++intLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ // EOF is legal for main level int values
+ c = CHAR_NULL;
+ eof = true;
+ break int_loop;
+ }
+ c = _inputBuffer[_inputPtr++];
+ }
+ // Also, integer part is not optional
+ if (intLen == 0) {
+ reportInvalidNumber(""Missing integer part (next char ""+_getCharDesc(c)+"")"");
+ }
+
+ int fractLen = 0;
+ // And then see if we get other parts
+ if (c == '.') { // yes, fraction
+ outBuf[outPtr++] = c;
+
+ fract_loop:
+ while (true) {
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break fract_loop;
+ }
+ c = _inputBuffer[_inputPtr++];
+ if (c < INT_0 || c > INT_9) {
+ break fract_loop;
+ }
+ ++fractLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (fractLen == 0) {
+ reportUnexpectedNumberChar(c, ""Decimal point not followed by a digit"");
+ }
+ }
+
+ int expLen = 0;
+ if (c == 'e' || c == 'E') { // exponent?
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ // Not optional, can require that we get one more char
+ c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++]
+ : getNextChar(""expected a digit for number exponent"");
+ // Sign indicator?
+ if (c == '-' || c == '+') {
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ // Likewise, non optional:
+ c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++]
+ : getNextChar(""expected a digit for number exponent"");
+ }
+
+ exp_loop:
+ while (c <= INT_9 && c >= INT_0) {
+ ++expLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = c;
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break exp_loop;
+ }
+ c = _inputBuffer[_inputPtr++];
+ }
+ // must be followed by sequence of ints, one minimum
+ if (expLen == 0) {
+ reportUnexpectedNumberChar(c, ""Exponent indicator not followed by a digit"");
+ }
+ }
+
+ // Ok; unless we hit end-of-input, need to push last char read back
+ if (!eof) {
+ --_inputPtr;
+ }
+ _textBuffer.setCurrentLength(outPtr);
+ // And there we have it!
+ return reset(negative, intLen, fractLen, expLen);
+ }
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonToken _parseNumber(int c)
+ throws IOException, JsonParseException
+ {
+ char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
+ int outPtr = 0;
+ boolean negative = (c == INT_MINUS);
+
+ // Need to prepend sign?
+ if (negative) {
+ outBuf[outPtr++] = '-';
+ // Must have something after sign too
+ if (_inputPtr >= _inputEnd) {
+ loadMoreGuaranteed();
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ // Note: must be followed by a digit
+ if (c < INT_0 || c > INT_9) {
+ return _handleInvalidNumberStart(c, true);
+ }
+ }
+
+ // One special case: if first char is 0, must not be followed by a digit
+ if (c == INT_0) {
+ c = _verifyNoLeadingZeroes();
+ }
+
+ // Ok: we can first just add digit we saw first:
+ outBuf[outPtr++] = (char) c;
+ int intLen = 1;
+
+ // And then figure out how far we can read without further checks:
+ int end = _inputPtr + outBuf.length;
+ if (end > _inputEnd) {
+ end = _inputEnd;
+ }
+
+ // With this, we have a nice and tight loop:
+ while (true) {
+ if (_inputPtr >= end) {
+ // Long enough to be split across boundary, so:
+ return _parserNumber2(outBuf, outPtr, negative, intLen);
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ if (c < INT_0 || c > INT_9) {
+ break;
+ }
+ ++intLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ }
+ if (c == '.' || c == 'e' || c == 'E') {
+ return _parseFloat(outBuf, outPtr, c, negative, intLen);
+ }
+
+ --_inputPtr; // to push back trailing char (comma etc)
+ _textBuffer.setCurrentLength(outPtr);
+ // As per #105, need separating space between root values; check here
+
+ // And there we have it!
+ return resetInt(negative, intLen);
+ }
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JsonToken _parserNumber2(char[] outBuf, int outPtr, boolean negative,
+ int intPartLength)
+ throws IOException, JsonParseException
+ {
+ // Ok, parse the rest
+ while (true) {
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ _textBuffer.setCurrentLength(outPtr);
+ return resetInt(negative, intPartLength);
+ }
+ int c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ if (c > INT_9 || c < INT_0) {
+ if (c == '.' || c == 'e' || c == 'E') {
+ return _parseFloat(outBuf, outPtr, c, negative, intPartLength);
+ }
+ break;
+ }
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ ++intPartLength;
+ }
+ --_inputPtr; // to push back trailing char (comma etc)
+ _textBuffer.setCurrentLength(outPtr);
+ // As per #105, need separating space between root values; check here
+
+ // And there we have it!
+ return resetInt(negative, intPartLength);
+
+ }
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JsonToken _parseFloat(char[] outBuf, int outPtr, int c,
+ boolean negative, int integerPartLength)
+ throws IOException, JsonParseException
+ {
+ int fractLen = 0;
+ boolean eof = false;
+
+ // And then see if we get other parts
+ if (c == '.') { // yes, fraction
+ outBuf[outPtr++] = (char) c;
+
+ fract_loop:
+ while (true) {
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break fract_loop;
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ if (c < INT_0 || c > INT_9) {
+ break fract_loop;
+ }
+ ++fractLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (fractLen == 0) {
+ reportUnexpectedNumberChar(c, ""Decimal point not followed by a digit"");
+ }
+ }
+
+ int expLen = 0;
+ if (c == 'e' || c == 'E') { // exponent?
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ // Not optional, can require that we get one more char
+ if (_inputPtr >= _inputEnd) {
+ loadMoreGuaranteed();
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ // Sign indicator?
+ if (c == '-' || c == '+') {
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ // Likewise, non optional:
+ if (_inputPtr >= _inputEnd) {
+ loadMoreGuaranteed();
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ }
+
+ exp_loop:
+ while (c <= INT_9 && c >= INT_0) {
+ ++expLen;
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ outBuf[outPtr++] = (char) c;
+ if (_inputPtr >= _inputEnd && !loadMore()) {
+ eof = true;
+ break exp_loop;
+ }
+ c = (int) _inputBuffer[_inputPtr++] & 0xFF;
+ }
+ // must be followed by sequence of ints, one minimum
+ if (expLen == 0) {
+ reportUnexpectedNumberChar(c, ""Exponent indicator not followed by a digit"");
+ }
+ }
+
+ // Ok; unless we hit end-of-input, need to push last char read back
+ if (!eof) {
+ --_inputPtr;
+ // As per #105, need separating space between root values; check here
+ }
+ _textBuffer.setCurrentLength(outPtr);
+
+ // And there we have it!
+ return resetFloat(negative, integerPartLength, fractLen, expLen);
+ }
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private int _skipWSOrEnd() throws IOException
+ {
+ final int[] codes = _icWS;
+ while ((_inputPtr < _inputEnd) || loadMore()) {
+ final int i = _inputBuffer[_inputPtr++] & 0xFF;
+ switch (codes[i]) {
+ case 0: // done!
+ return i;
+ case 1: // skip
+ continue;
+ case 2: // 2-byte UTF
+ _skipUtf8_2(i);
+ break;
+ case 3: // 3-byte UTF
+ _skipUtf8_3(i);
+ break;
+ case 4: // 4-byte UTF
+ _skipUtf8_4(i);
+ break;
+ case INT_LF:
+ ++_currInputRow;
+ _currInputRowStart = _inputPtr;
+ break;
+ case INT_CR:
+ _skipCR();
+ break;
+ case '/':
+ _skipComment();
+ break;
+ case '#':
+ if (!_skipYAMLComment()) {
+ return i;
+ }
+ break;
+ default: // e.g. -1
+ if (i < 32) {
+ _throwInvalidSpace(i);
+ }
+ _reportInvalidChar(i);
+ }
+ }
+ // We ran out of input...
+ _handleEOF();
+ return -1;
+ }
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMangledNumbersBytes() throws Exception {
+ _testMangledNumbers(true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void writeEmbeddedObject(Object object) throws IOException {
+ // 01-Sep-2016, tatu: As per [core#318], handle small number of cases
+ throw new JsonGenerationException(""No native support for writing embedded objects"",
+ this);
+ }
+
+// Test Case
+[/INST]
+ public void testBinaryAsEmbeddedObject() throws Exception
+ {
+ JsonGenerator g;
+
+ StringWriter sw = new StringWriter();
+ g = JSON_F.createGenerator(sw);
+ g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
+ g.close();
+ assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), sw.toString());
+
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream(100);
+ g = JSON_F.createGenerator(bytes);
+ g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
+ g.close();
+ assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), bytes.toString(""UTF-8""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonToken nextToken() throws IOException
+ {
+ // 23-May-2017, tatu: To be honest, code here is rather hairy and I don't like all
+ // conditionals; and it seems odd to return `null` but NOT considering input
+ // as closed... would love a rewrite to simplify/clear up logic here.
+
+ // Check for _allowMultipleMatches - false and at least there is one token - which is _currToken
+ // check for no buffered context _exposedContext - null
+ // If all the conditions matches then check for scalar / non-scalar property
+ if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {
+ //if not scalar and ended successfully, and !includePath, then return null
+ if (_currToken.isStructEnd()) {
+ if (_headContext.isStartHandled()) {
+ return (_currToken = null);
+ }
+ } else if (_currToken.isScalarValue()) {
+ //else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once
+ // then return null
+ if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {
+ return (_currToken = null);
+ }
+ }
+ }
+ // Anything buffered?
+ TokenFilterContext ctxt = _exposedContext;
+
+ if (ctxt != null) {
+ while (true) {
+ JsonToken t = ctxt.nextTokenToRead();
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ // all done with buffered stuff?
+ if (ctxt == _headContext) {
+ _exposedContext = null;
+ if (ctxt.inArray()) {
+ t = delegate.getCurrentToken();
+// Is this guaranteed to work without further checks?
+// if (t != JsonToken.START_ARRAY) {
+ _currToken = t;
+ return t;
+ }
+
+ // Almost! Most likely still have the current token;
+ // with the sole exception of
+ /*
+ t = delegate.getCurrentToken();
+ if (t != JsonToken.FIELD_NAME) {
+ _currToken = t;
+ return t;
+ }
+ */
+ break;
+ }
+ // If not, traverse down the context chain
+ ctxt = _headContext.findChildOf(ctxt);
+ _exposedContext = ctxt;
+ if (ctxt == null) { // should never occur
+ throw _constructError(""Unexpected problem: chain of filtered context broken"");
+ }
+ }
+ }
+
+ // If not, need to read more. If we got any:
+ JsonToken t = delegate.nextToken();
+ if (t == null) {
+ // no strict need to close, since we have no state here
+ _currToken = t;
+ return t;
+ }
+
+ // otherwise... to include or not?
+ TokenFilter f;
+
+ switch (t.id()) {
+ case ID_START_ARRAY:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ break;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ break;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartArray();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildArrayContext(f, false);
+
+ // Also: only need buffering if parent path to be included
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ break;
+
+ case ID_START_OBJECT:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ break;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ break;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartObject();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildObjectContext(f, false);
+ // Also: only need buffering if parent path to be included
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ // note: inclusion of surrounding Object handled separately via
+ // FIELD_NAME
+ break;
+
+ case ID_END_ARRAY:
+ case ID_END_OBJECT:
+ {
+ boolean returnEnd = _headContext.isStartHandled();
+ f = _headContext.getFilter();
+ if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
+ f.filterFinishArray();
+ }
+ _headContext = _headContext.getParent();
+ _itemFilter = _headContext.getFilter();
+ if (returnEnd) {
+ return (_currToken = t);
+ }
+ }
+ break;
+
+ case ID_FIELD_NAME:
+ {
+ final String name = delegate.getCurrentName();
+ // note: this will also set 'needToHandleName'
+ f = _headContext.setFieldName(name);
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _itemFilter = f;
+ if (!_includePath) {
+ // Minor twist here: if parent NOT included, may need to induce output of
+ // surrounding START_OBJECT/END_OBJECT
+ if (_includeImmediateParent && !_headContext.isStartHandled()) {
+ t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
+ _exposedContext = _headContext;
+ }
+ }
+ return (_currToken = t);
+ }
+ if (f == null) {
+ delegate.nextToken();
+ delegate.skipChildren();
+ break;
+ }
+ f = f.includeProperty(name);
+ if (f == null) {
+ delegate.nextToken();
+ delegate.skipChildren();
+ break;
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ if (_includePath) {
+ return (_currToken = t);
+ }
+ }
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ break;
+ }
+
+ default: // scalar value
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ return (_currToken = t);
+ }
+ if (f != null) {
+ f = _headContext.checkValue(f);
+ if ((f == TokenFilter.INCLUDE_ALL)
+ || ((f != null) && f.includeValue(delegate))) {
+ return (_currToken = t);
+ }
+ }
+ // Otherwise not included (leaves must be explicitly included)
+ break;
+ }
+
+ // We get here if token was not yet found; offlined handling
+ return _nextToken2();
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""resource"")
+ public void testTokensSingleMatchWithPath() throws Exception
+ {
+ JsonParser p0 = JSON_F.createParser(SIMPLE);
+ JsonParser p = new FilteringParserDelegate(p0,
+ new NameMatchFilter(""value""),
+ true, // includePath
+ false // multipleMatches
+ );
+
+ assertFalse(p.hasCurrentToken());
+ assertNull(p.getCurrentToken());
+ assertEquals(JsonTokenId.ID_NO_TOKEN, p.getCurrentTokenId());
+ assertFalse(p.isExpectedStartObjectToken());
+ assertFalse(p.isExpectedStartArrayToken());
+
+// {'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}
+// String result = readAndWrite(JSON_F, p);
+// assertEquals(aposToQuotes(""{'ob':{'value':3}}""), result);
+
+ assertToken(JsonToken.START_OBJECT, p.nextToken());
+ assertEquals(JsonToken.START_OBJECT, p.getCurrentToken());
+ assertTrue(p.isExpectedStartObjectToken());
+ assertFalse(p.isExpectedStartArrayToken());
+
+ assertToken(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(JsonToken.FIELD_NAME, p.getCurrentToken());
+ assertEquals(""ob"", p.getCurrentName());
+// assertEquals(""ob"", p.getText());
+
+ assertToken(JsonToken.START_OBJECT, p.nextToken());
+ assertEquals(""ob"", p.getCurrentName());
+
+ assertToken(JsonToken.FIELD_NAME, p.nextToken());
+ assertEquals(""value"", p.getCurrentName());
+ assertEquals(""value"", p.getText());
+
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(JsonToken.VALUE_NUMBER_INT, p.getCurrentToken());
+ assertEquals(NumberType.INT, p.getNumberType());
+ assertEquals(3, p.getIntValue());
+ assertEquals(""value"", p.getCurrentName());
+
+ assertToken(JsonToken.END_OBJECT, p.nextToken());
+ assertEquals(JsonToken.END_OBJECT, p.getCurrentToken());
+
+ assertToken(JsonToken.END_OBJECT, p.nextToken());
+ assertEquals(JsonToken.END_OBJECT, p.getCurrentToken());
+
+ p.clearCurrentToken();
+ assertNull(p.getCurrentToken());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonToken nextToken() throws IOException
+ {
+ // 23-May-2017, tatu: To be honest, code here is rather hairy and I don't like all
+ // conditionals; and it seems odd to return `null` but NOT considering input
+ // as closed... would love a rewrite to simplify/clear up logic here.
+
+ // Check for _allowMultipleMatches - false and at least there is one token - which is _currToken
+ // check for no buffered context _exposedContext - null
+ // If all the conditions matches then check for scalar / non-scalar property
+
+ if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {
+ // if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL
+ // matched once, return null
+ if (_currToken.isScalarValue() && !_headContext.isStartHandled() && !_includePath
+ && (_itemFilter == TokenFilter.INCLUDE_ALL)) {
+ return (_currToken = null);
+ }
+ }
+ // Anything buffered?
+ TokenFilterContext ctxt = _exposedContext;
+
+ if (ctxt != null) {
+ while (true) {
+ JsonToken t = ctxt.nextTokenToRead();
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ // all done with buffered stuff?
+ if (ctxt == _headContext) {
+ _exposedContext = null;
+ if (ctxt.inArray()) {
+ t = delegate.getCurrentToken();
+// Is this guaranteed to work without further checks?
+// if (t != JsonToken.START_ARRAY) {
+ _currToken = t;
+ return t;
+ }
+
+ // Almost! Most likely still have the current token;
+ // with the sole exception of
+ /*
+ t = delegate.getCurrentToken();
+ if (t != JsonToken.FIELD_NAME) {
+ _currToken = t;
+ return t;
+ }
+ */
+ break;
+ }
+ // If not, traverse down the context chain
+ ctxt = _headContext.findChildOf(ctxt);
+ _exposedContext = ctxt;
+ if (ctxt == null) { // should never occur
+ throw _constructError(""Unexpected problem: chain of filtered context broken"");
+ }
+ }
+ }
+
+ // If not, need to read more. If we got any:
+ JsonToken t = delegate.nextToken();
+ if (t == null) {
+ // no strict need to close, since we have no state here
+ _currToken = t;
+ return t;
+ }
+
+ // otherwise... to include or not?
+ TokenFilter f;
+
+ switch (t.id()) {
+ case ID_START_ARRAY:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ break;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ break;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartArray();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildArrayContext(f, false);
+
+ // Also: only need buffering if parent path to be included
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ break;
+
+ case ID_START_OBJECT:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ break;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ break;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartObject();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildObjectContext(f, false);
+ // Also: only need buffering if parent path to be included
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ // note: inclusion of surrounding Object handled separately via
+ // FIELD_NAME
+ break;
+
+ case ID_END_ARRAY:
+ case ID_END_OBJECT:
+ {
+ boolean returnEnd = _headContext.isStartHandled();
+ f = _headContext.getFilter();
+ if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
+ f.filterFinishArray();
+ }
+ _headContext = _headContext.getParent();
+ _itemFilter = _headContext.getFilter();
+ if (returnEnd) {
+ return (_currToken = t);
+ }
+ }
+ break;
+
+ case ID_FIELD_NAME:
+ {
+ final String name = delegate.getCurrentName();
+ // note: this will also set 'needToHandleName'
+ f = _headContext.setFieldName(name);
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _itemFilter = f;
+ if (!_includePath) {
+ // Minor twist here: if parent NOT included, may need to induce output of
+ // surrounding START_OBJECT/END_OBJECT
+ if (_includeImmediateParent && !_headContext.isStartHandled()) {
+ t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
+ _exposedContext = _headContext;
+ }
+ }
+ return (_currToken = t);
+ }
+ if (f == null) {
+ delegate.nextToken();
+ delegate.skipChildren();
+ break;
+ }
+ f = f.includeProperty(name);
+ if (f == null) {
+ delegate.nextToken();
+ delegate.skipChildren();
+ break;
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ if (_includePath) {
+ return (_currToken = t);
+ }
+ }
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ break;
+ }
+
+ default: // scalar value
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ return (_currToken = t);
+ }
+ if (f != null) {
+ f = _headContext.checkValue(f);
+ if ((f == TokenFilter.INCLUDE_ALL)
+ || ((f != null) && f.includeValue(delegate))) {
+ return (_currToken = t);
+ }
+ }
+ // Otherwise not included (leaves must be explicitly included)
+ break;
+ }
+
+ // We get here if token was not yet found; offlined handling
+ return _nextToken2();
+ }
+
+// Test Case
+[/INST]
+ public void testSingleMatchFilteringWithPath() throws Exception
+ {
+ String jsonString = aposToQuotes(""{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"");
+ JsonParser p0 = JSON_F.createParser(jsonString);
+ FilteringParserDelegate p = new FilteringParserDelegate(p0,
+ new NameMatchFilter(""a""),
+ true, // includePath
+ false // multipleMatches
+ );
+ String result = readAndWrite(JSON_F, p);
+ assertEquals(aposToQuotes(""{'a':123}""), result);
+ assertEquals(1, p.getMatchCount());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final JsonToken _nextToken2() throws IOException
+ {
+ main_loop:
+ while (true) {
+ JsonToken t = delegate.nextToken();
+ if (t == null) { // is this even legal?
+ _currToken = t;
+ return t;
+ }
+ TokenFilter f;
+
+ switch (t.id()) {
+ case ID_START_ARRAY:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartArray();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildArrayContext(f, false);
+ // but if we didn't figure it out yet, need to buffer possible events
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ continue main_loop;
+
+ case ID_START_OBJECT:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartObject();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return (_currToken = t);
+ }
+ _headContext = _headContext.createChildObjectContext(f, false);
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ continue main_loop;
+
+ case ID_END_ARRAY:
+ case ID_END_OBJECT:
+ {
+ boolean returnEnd = _headContext.isStartHandled();
+ f = _headContext.getFilter();
+ if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
+ f.filterFinishArray();
+ }
+ _headContext = _headContext.getParent();
+ _itemFilter = _headContext.getFilter();
+ if (returnEnd) {
+ return (_currToken = t);
+ }
+ }
+ continue main_loop;
+
+ case ID_FIELD_NAME:
+ {
+ final String name = delegate.getCurrentName();
+ f = _headContext.setFieldName(name);
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _itemFilter = f;
+ return (_currToken = t);
+ }
+ if (f == null) { // filter out the value
+ delegate.nextToken();
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ f = f.includeProperty(name);
+ if (f == null) { // filter out the value
+ delegate.nextToken();
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ if (_includePath) {
+ return (_currToken = t);
+ }
+// if (_includeImmediateParent) { ...
+ continue main_loop;
+ }
+ if (_includePath) {
+ t = _nextTokenWithBuffering(_headContext);
+ if (t != null) {
+ _currToken = t;
+ return t;
+ }
+ }
+ }
+ continue main_loop;
+
+ default: // scalar value
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ return (_currToken = t);
+ }
+ if (f != null) {
+ f = _headContext.checkValue(f);
+ if ((f == TokenFilter.INCLUDE_ALL)
+ || ((f != null) && f.includeValue(delegate))) {
+ return (_currToken = t);
+ }
+ }
+ // Otherwise not included (leaves must be explicitly included)
+ break;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSingleMatchFilteringWithPath() throws Exception
+ {
+ String jsonString = aposToQuotes(""{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"");
+ JsonParser p0 = JSON_F.createParser(jsonString);
+ FilteringParserDelegate p = new FilteringParserDelegate(p0,
+ new NameMatchFilter(""a""),
+ true, // includePath
+ false // multipleMatches
+ );
+ String result = readAndWrite(JSON_F, p);
+ assertEquals(aposToQuotes(""{'a':123}""), result);
+ assertEquals(1, p.getMatchCount());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final JsonToken _nextTokenWithBuffering(final TokenFilterContext buffRoot)
+ throws IOException
+ {
+ main_loop:
+ while (true) {
+ JsonToken t = delegate.nextToken();
+ if (t == null) { // is this even legal?
+ return t;
+ }
+ TokenFilter f;
+
+ // One simplification here: we know for a fact that the item filter is
+ // neither null nor 'include all', for most cases; the only exception
+ // being FIELD_NAME handling
+
+ switch (t.id()) {
+ case ID_START_ARRAY:
+ f = _headContext.checkValue(_itemFilter);
+ if (f == null) {
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartArray();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildArrayContext(f, true);
+ return _nextBuffered(buffRoot);
+ }
+ _headContext = _headContext.createChildArrayContext(f, false);
+ continue main_loop;
+
+ case ID_START_OBJECT:
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return t;
+ }
+ if (f == null) { // does this occur?
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ // Otherwise still iffy, need to check
+ f = _headContext.checkValue(f);
+ if (f == null) {
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ if (f != TokenFilter.INCLUDE_ALL) {
+ f = f.filterStartObject();
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _headContext = _headContext.createChildObjectContext(f, true);
+ return _nextBuffered(buffRoot);
+ }
+ _headContext = _headContext.createChildObjectContext(f, false);
+ continue main_loop;
+
+ case ID_END_ARRAY:
+ case ID_END_OBJECT:
+ {
+ // Unlike with other loops, here we know that content was NOT
+ // included (won't get this far otherwise)
+ f = _headContext.getFilter();
+ if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
+ f.filterFinishArray();
+ }
+ boolean gotEnd = (_headContext == buffRoot);
+ boolean returnEnd = gotEnd && _headContext.isStartHandled();
+
+ _headContext = _headContext.getParent();
+ _itemFilter = _headContext.getFilter();
+
+ if (returnEnd) {
+ return t;
+ }
+ // Hmmh. Do we need both checks, or should above suffice?
+ if (gotEnd || (_headContext == buffRoot)) {
+ return null;
+ }
+ }
+ continue main_loop;
+
+ case ID_FIELD_NAME:
+ {
+ final String name = delegate.getCurrentName();
+ f = _headContext.setFieldName(name);
+ if (f == TokenFilter.INCLUDE_ALL) {
+ _itemFilter = f;
+ return _nextBuffered(buffRoot);
+ }
+ if (f == null) { // filter out the value
+ delegate.nextToken();
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ f = f.includeProperty(name);
+ if (f == null) { // filter out the value
+ delegate.nextToken();
+ delegate.skipChildren();
+ continue main_loop;
+ }
+ _itemFilter = f;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ return _nextBuffered(buffRoot);
+ }
+ }
+ continue main_loop;
+
+ default: // scalar value
+ f = _itemFilter;
+ if (f == TokenFilter.INCLUDE_ALL) {
+ return _nextBuffered(buffRoot);
+ }
+ if (f != null) {
+ f = _headContext.checkValue(f);
+ if ((f == TokenFilter.INCLUDE_ALL)
+ || ((f != null) && f.includeValue(delegate))) {
+ return _nextBuffered(buffRoot);
+ }
+ }
+ // Otherwise not included (leaves must be explicitly included)
+ continue main_loop;
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSingleMatchFilteringWithPath() throws Exception
+ {
+ String jsonString = aposToQuotes(""{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"");
+ JsonParser p0 = JSON_F.createParser(jsonString);
+ FilteringParserDelegate p = new FilteringParserDelegate(p0,
+ new NameMatchFilter(""a""),
+ true, // includePath
+ false // multipleMatches
+ );
+ String result = readAndWrite(JSON_F, p);
+ assertEquals(aposToQuotes(""{'a':123}""), result);
+ assertEquals(1, p.getMatchCount());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testSingleMatchFilteringWithPath() throws Exception
+ {
+ String jsonString = aposToQuotes(""{'a':123,'array':[1,2],'ob':{'value0':2,'value':3,'value2':4},'b':true}"");
+ JsonParser p0 = JSON_F.createParser(jsonString);
+ FilteringParserDelegate p = new FilteringParserDelegate(p0,
+ new NameMatchFilter(""a""),
+ true, // includePath
+ false // multipleMatches
+ );
+ String result = readAndWrite(JSON_F, p);
+ assertEquals(aposToQuotes(""{'a':123}""), result);
+ assertEquals(1, p.getMatchCount());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public DefaultPrettyPrinter createInstance() {
+ return new DefaultPrettyPrinter(this);
+ }
+
+// Test Case
+[/INST]
+ public void testInvalidSubClass() throws Exception
+ {
+ DefaultPrettyPrinter pp = new MyPrettyPrinter();
+ try {
+ pp.createInstance();
+ fail(""Should not pass"");
+ } catch (IllegalStateException e) {
+ verifyException(e, ""does not override"");
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void reportOverflowInt(String numDesc) throws IOException {
+ _reportError(String.format(""Numeric value (%s) out of range of int (%d - %s)"",
+ _longIntegerDesc(numDesc), Integer.MIN_VALUE, Integer.MAX_VALUE));
+ }
+
+// Test Case
+[/INST]
+ public void testToLongFailing() throws Exception
+ {
+ AsyncReaderWrapper p;
+
+ // BigInteger -> error
+ BigInteger big = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN);
+ p = createParser(String.valueOf(big));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ assertEquals(big, p.getBigIntegerValue());
+ assertEquals(big, p.getNumberValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ BigInteger small = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.TEN);
+ p = createParser(String.valueOf(small));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(small, p.getBigIntegerValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void reportOverflowLong(String numDesc) throws IOException {
+ _reportError(String.format(""Numeric value (%s) out of range of long (%d - %s)"",
+ _longIntegerDesc(numDesc), Long.MIN_VALUE, Long.MAX_VALUE));
+ }
+
+// Test Case
+[/INST]
+ public void testToLongFailing() throws Exception
+ {
+ AsyncReaderWrapper p;
+
+ // BigInteger -> error
+ BigInteger big = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN);
+ p = createParser(String.valueOf(big));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ assertEquals(big, p.getBigIntegerValue());
+ assertEquals(big, p.getNumberValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ BigInteger small = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.TEN);
+ p = createParser(String.valueOf(small));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(small, p.getBigIntegerValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _reportTooLongIntegral(int expType, String rawNum) throws IOException
+ {
+ final String numDesc = _longIntegerDesc(rawNum);
+ _reportError(""Numeric value (%s) out of range of %s"", numDesc,
+ (expType == NR_LONG) ? ""long"" : ""int"");
+ }
+
+// Test Case
+[/INST]
+ public void testToLongFailing() throws Exception
+ {
+ AsyncReaderWrapper p;
+
+ // BigInteger -> error
+ BigInteger big = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN);
+ p = createParser(String.valueOf(big));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ assertEquals(big, p.getBigIntegerValue());
+ assertEquals(big, p.getNumberValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ BigInteger small = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.TEN);
+ p = createParser(String.valueOf(small));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(small, p.getBigIntegerValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void convertNumberToInt() throws IOException
+ {
+ // First, converting from long ought to be easy
+ if ((_numTypesValid & NR_LONG) != 0) {
+ // Let's verify it's lossless conversion by simple roundtrip
+ int result = (int) _numberLong;
+ if (((long) result) != _numberLong) {
+ _reportError(""Numeric value (""+getText()+"") out of range of int"");
+ }
+ _numberInt = result;
+ } else if ((_numTypesValid & NR_BIGINT) != 0) {
+ if (BI_MIN_INT.compareTo(_numberBigInt) > 0
+ || BI_MAX_INT.compareTo(_numberBigInt) < 0) {
+ reportOverflowInt();
+ }
+ _numberInt = _numberBigInt.intValue();
+ } else if ((_numTypesValid & NR_DOUBLE) != 0) {
+ // Need to check boundaries
+ if (_numberDouble < MIN_INT_D || _numberDouble > MAX_INT_D) {
+ reportOverflowInt();
+ }
+ _numberInt = (int) _numberDouble;
+ } else if ((_numTypesValid & NR_BIGDECIMAL) != 0) {
+ if (BD_MIN_INT.compareTo(_numberBigDecimal) > 0
+ || BD_MAX_INT.compareTo(_numberBigDecimal) < 0) {
+ reportOverflowInt();
+ }
+ _numberInt = _numberBigDecimal.intValue();
+ } else {
+ _throwInternal();
+ }
+ _numTypesValid |= NR_INT;
+ }
+
+// Test Case
+[/INST]
+ public void testToLongFailing() throws Exception
+ {
+ AsyncReaderWrapper p;
+
+ // BigInteger -> error
+ BigInteger big = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN);
+ p = createParser(String.valueOf(big));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ assertEquals(big, p.getBigIntegerValue());
+ assertEquals(big, p.getNumberValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ BigInteger small = BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.TEN);
+ p = createParser(String.valueOf(small));
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(small, p.getBigIntegerValue());
+ try {
+ p.getLongValue();
+ fail(""Should not pass"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""out of range of long"");
+ assertEquals(JsonToken.VALUE_NUMBER_INT, e.getInputType());
+ assertEquals(Long.TYPE, e.getTargetType());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException
+ {
+ _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr));
+ char[] outBuf = _textBuffer.getCurrentSegment();
+ int outPtr = _textBuffer.getCurrentSegmentSize();
+ final int maxCode = codes.length;
+
+ while (true) {
+ if (_inputPtr >= _inputEnd) {
+ if (!_loadMore()) { // acceptable for now (will error out later)
+ break;
+ }
+ }
+ char c = _inputBuffer[_inputPtr];
+ int i = (int) c;
+ if (i <= maxCode) {
+ if (codes[i] != 0) {
+ break;
+ }
+ } else if (!Character.isJavaIdentifierPart(c)) {
+ break;
+ }
+ ++_inputPtr;
+ hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i;
+ // Ok, let's add char to output:
+ outBuf[outPtr++] = c;
+
+ // Need more room?
+ if (outPtr >= outBuf.length) {
+ outBuf = _textBuffer.finishCurrentSegment();
+ outPtr = 0;
+ }
+ }
+ _textBuffer.setCurrentLength(outPtr);
+ {
+ TextBuffer tb = _textBuffer;
+ char[] buf = tb.getTextBuffer();
+ int start = tb.getTextOffset();
+ int len = tb.size();
+
+ return _symbols.findSymbol(buf, start, len, hash);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testUnquotedIssue510() throws Exception
+ {
+ // NOTE! Requires longer input buffer to trigger longer codepath
+ char[] fullChars = new char[4001];
+ for (int i = 0; i < 3998; i++) {
+ fullChars[i] = ' ';
+ }
+ fullChars[3998] = '{';
+ fullChars[3999] = 'a';
+ fullChars[4000] = 256;
+
+ JsonParser p = UNQUOTED_FIELDS_F.createParser(new java.io.StringReader(new String(fullChars)));
+ assertToken(JsonToken.START_OBJECT, p.nextToken());
+ try {
+ p.nextToken();
+ fail(""Should not pass"");
+ } catch (JsonParseException e) {
+ ; // should fail here
+ }
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void feedInput(byte[] buf, int start, int end) throws IOException
+ {
+ // Must not have remaining input
+ if (_inputPtr < _inputEnd) {
+ _reportError(""Still have %d undecoded bytes, should not call 'feedInput'"", _inputEnd - _inputPtr);
+ }
+ if (end < start) {
+ _reportError(""Input end (%d) may not be before start (%d)"", end, start);
+ }
+ // and shouldn't have been marked as end-of-input
+ if (_endOfInput) {
+ _reportError(""Already closed, can not feed more input"");
+ }
+ // Time to update pointers first
+ _currInputProcessed += _origBufferLen;
+
+ // Also need to adjust row start, to work as if it extended into the past wrt new buffer
+ _currInputRowStart = start - (_inputEnd - _currInputRowStart);
+
+ // And then update buffer settings
+ _inputBuffer = buf;
+ _inputPtr = start;
+ _inputEnd = end;
+ _origBufferLen = end - start;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationOffsets() throws Exception
+ {
+ JsonParser parser = DEFAULT_F.createNonBlockingByteArrayParser();
+ ByteArrayFeeder feeder = (ByteArrayFeeder) parser.getNonBlockingInputFeeder();
+
+ byte[] input = utf8Bytes(""[[["");
+
+ feeder.feedInput(input, 2, 3);
+ assertEquals(JsonToken.START_ARRAY, parser.nextToken());
+ assertEquals(1, parser.getCurrentLocation().getByteOffset());
+ assertEquals(1, parser.getTokenLocation().getByteOffset());
+ assertEquals(1, parser.getCurrentLocation().getLineNr());
+ assertEquals(1, parser.getTokenLocation().getLineNr());
+ assertEquals(2, parser.getCurrentLocation().getColumnNr());
+ assertEquals(1, parser.getTokenLocation().getColumnNr());
+
+ feeder.feedInput(input, 0, 1);
+ assertEquals(JsonToken.START_ARRAY, parser.nextToken());
+ assertEquals(2, parser.getCurrentLocation().getByteOffset());
+ assertEquals(2, parser.getTokenLocation().getByteOffset());
+ assertEquals(1, parser.getCurrentLocation().getLineNr());
+ assertEquals(1, parser.getTokenLocation().getLineNr());
+ assertEquals(3, parser.getCurrentLocation().getColumnNr());
+ assertEquals(2, parser.getTokenLocation().getColumnNr());
+ parser.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in,
+ ObjectCodec codec, BytesToNameCanonicalizer sym,
+ byte[] inputBuffer, int start, int end,
+ boolean bufferRecyclable)
+ {
+ super(ctxt, features);
+ _inputStream = in;
+ _objectCodec = codec;
+ _symbols = sym;
+ _inputBuffer = inputBuffer;
+ _inputPtr = start;
+ _inputEnd = end;
+ // If we have offset, need to omit that from byte offset, so:
+ _bufferRecyclable = bufferRecyclable;
+ }
+
+// Test Case
+[/INST]
+ public void testOffsetWithInputOffset() throws Exception
+ {
+ final JsonFactory f = new JsonFactory();
+ JsonLocation loc;
+ JsonParser p;
+ // 3 spaces before, 2 after, just for padding
+ byte[] b = "" { } "".getBytes(""UTF-8"");
+
+ // and then peel them off
+ p = f.createParser(b, 3, b.length-5);
+ assertToken(JsonToken.START_OBJECT, p.nextToken());
+
+ loc = p.getTokenLocation();
+ assertEquals(0L, loc.getByteOffset());
+ assertEquals(-1L, loc.getCharOffset());
+ assertEquals(1, loc.getLineNr());
+ assertEquals(1, loc.getColumnNr());
+
+ loc = p.getCurrentLocation();
+ assertEquals(1L, loc.getByteOffset());
+ assertEquals(-1L, loc.getCharOffset());
+ assertEquals(1, loc.getLineNr());
+ assertEquals(2, loc.getColumnNr());
+
+ p.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public char[] expandCurrentSegment()
+ {
+ final char[] curr = _currentSegment;
+ // Let's grow by 50% by default
+ final int len = curr.length;
+ // but above intended maximum, slow to increase by 25%
+ int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1));
+ return (_currentSegment = Arrays.copyOf(curr, newLen));
+ }
+
+// Test Case
+[/INST]
+ public void testExpand()
+ {
+ TextBuffer tb = new TextBuffer(new BufferRecycler());
+ char[] buf = tb.getCurrentSegment();
+
+ while (buf.length < 500 * 1000) {
+ char[] old = buf;
+ buf = tb.expandCurrentSegment();
+ if (old.length >= buf.length) {
+ fail(""Expected buffer of ""+old.length+"" to expand, did not, length now ""+buf.length);
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final static int _parseIndex(String str) {
+ final int len = str.length();
+ // [Issue#133]: beware of super long indexes; assume we never
+ // have arrays over 2 billion entries so ints are fine.
+ if (len == 0 || len > 10) {
+ return -1;
+ }
+ for (int i = 0; i < len; ++i) {
+ char c = str.charAt(i++);
+ if (c > '9' || c < '0') {
+ return -1;
+ }
+ }
+ if (len == 10) {
+ long l = NumberInput.parseLong(str);
+ if (l > Integer.MAX_VALUE) {
+ return -1;
+ }
+ }
+ return NumberInput.parseInt(str);
+ }
+
+// Test Case
+[/INST]
+ public void testWonkyNumber173() throws Exception
+ {
+ JsonPointer ptr = JsonPointer.compile(""/1e0"");
+ assertFalse(ptr.matches());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final static int _parseIndex(String str) {
+ final int len = str.length();
+ // [core#133]: beware of super long indexes; assume we never
+ // have arrays over 2 billion entries so ints are fine.
+ if (len == 0 || len > 10) {
+ return -1;
+ }
+ // [core#176]: no leading zeroes allowed
+ for (int i = 0; i < len; ++i) {
+ char c = str.charAt(i);
+ if (c > '9' || c < '0') {
+ return -1;
+ }
+ }
+ if (len == 10) {
+ long l = NumberInput.parseLong(str);
+ if (l > Integer.MAX_VALUE) {
+ return -1;
+ }
+ }
+ return NumberInput.parseInt(str);
+ }
+
+// Test Case
+[/INST]
+ public void testIZeroIndex() throws Exception
+ {
+ JsonPointer ptr = JsonPointer.compile(""/0"");
+ assertEquals(0, ptr.getMatchingIndex());
+ ptr = JsonPointer.compile(""/00"");
+ assertEquals(-1, ptr.getMatchingIndex());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public int writeValue() {
+ // Most likely, object:
+ if (_type == TYPE_OBJECT) {
+ _gotName = false;
+ ++_index;
+ return STATUS_OK_AFTER_COLON;
+ }
+
+ // Ok, array?
+ if (_type == TYPE_ARRAY) {
+ int ix = _index;
+ ++_index;
+ return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;
+ }
+
+ // Nope, root context
+ // No commas within root context, but need space
+ ++_index;
+ return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE;
+ }
+
+// Test Case
+[/INST]
+ public void testFailOnWritingStringNotFieldNameBytes() throws Exception {
+ _testFailOnWritingStringNotFieldName(F, false);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public char[] getTextBuffer()
+ {
+ // Are we just using shared input buffer?
+ if (_inputStart >= 0) return _inputBuffer;
+ if (_resultArray != null) return _resultArray;
+ if (_resultString != null) {
+ return (_resultArray = _resultString.toCharArray());
+ }
+ // Nope; but does it fit in just one segment?
+ if (!_hasSegments) return _currentSegment;
+ // Nope, need to have/create a non-segmented array and return it
+ return contentsAsArray();
+ }
+
+// Test Case
+[/INST]
+ public void testEmpty() {
+ TextBuffer tb = new TextBuffer(new BufferRecycler());
+ tb.resetWithEmpty();
+
+ assertTrue(tb.getTextBuffer().length == 0);
+ tb.contentsAsString();
+ assertTrue(tb.getTextBuffer().length == 0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public char[] getTextBuffer()
+ {
+ // Are we just using shared input buffer?
+ if (_inputStart >= 0) return _inputBuffer;
+ if (_resultArray != null) return _resultArray;
+ if (_resultString != null) {
+ return (_resultArray = _resultString.toCharArray());
+ }
+ // Nope; but does it fit in just one segment?
+ if (!_hasSegments) return _currentSegment;
+ // Nope, need to have/create a non-segmented array and return it
+ return contentsAsArray();
+ }
+
+// Test Case
+[/INST]
+ public void testEmpty() {
+ TextBuffer tb = new TextBuffer(new BufferRecycler());
+ tb.resetWithEmpty();
+
+ assertTrue(tb.getTextBuffer().length == 0);
+ tb.contentsAsString();
+ assertTrue(tb.getTextBuffer().length == 0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public final String getValueAsString() throws IOException
+ {
+ if (_currToken == JsonToken.VALUE_STRING) {
+ if (_tokenIncomplete) {
+ _tokenIncomplete = false;
+ _finishString(); // only strings can be incomplete
+ }
+ return _textBuffer.contentsAsString();
+ }
+ return super.getValueAsString(null);
+ }
+
+// Test Case
+[/INST]
+ public void testGetValueAsTextBytes() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ _testGetValueAsText(f, true, false);
+ _testGetValueAsText(f, true, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public final String getValueAsString(String defValue) throws IOException {
+ if (_currToken == JsonToken.VALUE_STRING) {
+ if (_tokenIncomplete) {
+ _tokenIncomplete = false;
+ _finishString(); // only strings can be incomplete
+ }
+ return _textBuffer.contentsAsString();
+ }
+ return super.getValueAsString(defValue);
+ }
+
+// Test Case
+[/INST]
+ public void testGetValueAsTextBytes() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ _testGetValueAsText(f, true, false);
+ _testGetValueAsText(f, true, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String getValueAsString() throws IOException
+ {
+ if (_currToken == JsonToken.VALUE_STRING) {
+ if (_tokenIncomplete) {
+ _tokenIncomplete = false;
+ return _finishAndReturnString(); // only strings can be incomplete
+ }
+ return _textBuffer.contentsAsString();
+ }
+ return super.getValueAsString(null);
+ }
+
+// Test Case
+[/INST]
+ public void testGetValueAsTextBytes() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ _testGetValueAsText(f, true, false);
+ _testGetValueAsText(f, true, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String getValueAsString(String defValue) throws IOException
+ {
+ if (_currToken == JsonToken.VALUE_STRING) {
+ if (_tokenIncomplete) {
+ _tokenIncomplete = false;
+ return _finishAndReturnString(); // only strings can be incomplete
+ }
+ return _textBuffer.contentsAsString();
+ }
+ return super.getValueAsString(defValue);
+ }
+
+// Test Case
+[/INST]
+ public void testGetValueAsTextBytes() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ _testGetValueAsText(f, true, false);
+ _testGetValueAsText(f, true, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String getValueAsString() throws IOException {
+ if (_currToken == JsonToken.VALUE_STRING) {
+ return getText();
+ }
+ return getValueAsString(null);
+ }
+
+// Test Case
+[/INST]
+ public void testGetValueAsTextBytes() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ _testGetValueAsText(f, true, false);
+ _testGetValueAsText(f, true, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String getValueAsString(String defaultValue) throws IOException {
+ if (_currToken == JsonToken.VALUE_STRING) {
+ return getText();
+ }
+ if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) {
+ return defaultValue;
+ }
+ return getText();
+ }
+
+// Test Case
+[/INST]
+ public void testGetValueAsTextBytes() throws Exception
+ {
+ JsonFactory f = new JsonFactory();
+ _testGetValueAsText(f, true, false);
+ _testGetValueAsText(f, true, true);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)
+ throws Exception
+ {
+ Object value = get(bean);
+ if (value == null) { // nulls need specialized handling
+ if (_nullSerializer != null) {
+ _nullSerializer.serialize(null, jgen, prov);
+ } else { // can NOT suppress entries in tabular output
+ jgen.writeNull();
+ }
+ }
+ // otherwise find serializer to use
+ JsonSerializer ser = _serializer;
+ if (ser == null) {
+ Class> cls = value.getClass();
+ PropertySerializerMap map = _dynamicSerializers;
+ ser = map.serializerFor(cls);
+ if (ser == null) {
+ ser = _findAndAddDynamic(map, cls, prov);
+ }
+ }
+ // and then see if we must suppress certain values (default, empty)
+ if (_suppressableValue != null) {
+ if (MARKER_FOR_EMPTY == _suppressableValue) {
+ if (ser.isEmpty(value)) { // can NOT suppress entries in tabular output
+ serializeAsPlaceholder(bean, jgen, prov);
+ return;
+ }
+ } else if (_suppressableValue.equals(value)) { // can NOT suppress entries in tabular output
+ serializeAsPlaceholder(bean, jgen, prov);
+ return;
+ }
+ }
+ // For non-nulls: simple check for direct cycles
+ if (value == bean) {
+ _handleSelfReference(bean, ser);
+ }
+ if (_typeSerializer == null) {
+ ser.serialize(value, jgen, prov);
+ } else {
+ ser.serializeWithType(value, jgen, prov, _typeSerializer);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNullColumn() throws Exception
+ {
+ assertEquals(""[null,\""bar\""]"", MAPPER.writeValueAsString(new TwoStringsBean()));
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ public AnyGetterWriter(BeanProperty property,
+ AnnotatedMember accessor, MapSerializer serializer)
+ {
+ _accessor = accessor;
+ _property = property;
+ _mapSerializer = (MapSerializer) serializer;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue705() throws Exception
+ {
+ Issue705Bean input = new Issue705Bean(""key"", ""value"");
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(""{\""stuff\"":\""[key/value]\""}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void getAndSerialize(Object bean, JsonGenerator gen, SerializerProvider provider)
+ throws Exception
+ {
+ Object value = _accessor.getValue(bean);
+ if (value == null) {
+ return;
+ }
+ if (!(value instanceof Map,?>)) {
+ throw new JsonMappingException(""Value returned by 'any-getter' (""
+ +_accessor.getName()+""()) not java.util.Map but ""+value.getClass().getName());
+ }
+ // 23-Feb-2015, tatu: Nasty, but has to do (for now)
+ if (_mapSerializer != null) {
+ _mapSerializer.serializeFields((Map,?>) value, gen, provider);
+ return;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIssue705() throws Exception
+ {
+ Issue705Bean input = new Issue705Bean(""key"", ""value"");
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(""{\""stuff\"":\""[key/value]\""}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void getAndFilter(Object bean, JsonGenerator gen, SerializerProvider provider,
+ PropertyFilter filter)
+ throws Exception
+ {
+ Object value = _accessor.getValue(bean);
+ if (value == null) {
+ return;
+ }
+ if (!(value instanceof Map,?>)) {
+ throw new JsonMappingException(""Value returned by 'any-getter' (""
+ +_accessor.getName()+""()) not java.util.Map but ""+value.getClass().getName());
+ }
+ // 19-Oct-2014, tatu: Should we try to support @JsonInclude options here?
+ if (_mapSerializer != null) {
+ _mapSerializer.serializeFilteredFields((Map,?>) value, gen, provider, filter, null);
+ return;
+ }
+ // ... not sure how custom handler would do it
+ }
+
+// Test Case
+[/INST]
+ public void testIssue705() throws Exception
+ {
+ Issue705Bean input = new Issue705Bean(""key"", ""value"");
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(""{\""stuff\"":\""[key/value]\""}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ public void resolve(SerializerProvider provider) throws JsonMappingException
+ {
+ // 05-Sep-2013, tatu: I _think_ this can be considered a primary property...
+ _mapSerializer = (MapSerializer) provider.handlePrimaryContextualization(_mapSerializer, _property);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue705() throws Exception
+ {
+ Issue705Bean input = new Issue705Bean(""key"", ""value"");
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(""{\""stuff\"":\""[key/value]\""}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ protected JsonSerializer constructBeanSerializer(SerializerProvider prov,
+ BeanDescription beanDesc)
+ throws JsonMappingException
+ {
+ // 13-Oct-2010, tatu: quick sanity check: never try to create bean serializer for plain Object
+ // 05-Jul-2012, tatu: ... but we should be able to just return ""unknown type"" serializer, right?
+ if (beanDesc.getBeanClass() == Object.class) {
+ return prov.getUnknownTypeSerializer(Object.class);
+// throw new IllegalArgumentException(""Can not create bean serializer for Object.class"");
+ }
+ final SerializationConfig config = prov.getConfig();
+ BeanSerializerBuilder builder = constructBeanSerializerBuilder(beanDesc);
+ builder.setConfig(config);
+
+ // First: any detectable (auto-detect, annotations) properties to serialize?
+ List props = findBeanProperties(prov, beanDesc, builder);
+ if (props == null) {
+ props = new ArrayList();
+ }
+ // [databind#638]: Allow injection of ""virtual"" properties:
+ prov.getAnnotationIntrospector().findAndAddVirtualProperties(config, beanDesc.getClassInfo(), props);
+
+ // [JACKSON-440] Need to allow modification bean properties to serialize:
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ props = mod.changeProperties(config, beanDesc, props);
+ }
+ }
+
+ // Any properties to suppress?
+ props = filterBeanProperties(config, beanDesc, props);
+
+ // [JACKSON-440] Need to allow reordering of properties to serialize
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ props = mod.orderProperties(config, beanDesc, props);
+ }
+ }
+
+ /* And if Object Id is needed, some preparation for that as well: better
+ * do before view handling, mostly for the custom id case which needs
+ * access to a property
+ */
+ builder.setObjectIdWriter(constructObjectIdHandler(prov, beanDesc, props));
+
+ builder.setProperties(props);
+ builder.setFilterId(findFilterId(config, beanDesc));
+
+ AnnotatedMember anyGetter = beanDesc.findAnyGetter();
+ if (anyGetter != null) {
+ if (config.canOverrideAccessModifiers()) {
+ anyGetter.fixAccess();
+ }
+ JavaType type = anyGetter.getType(beanDesc.bindingsForBeanType());
+ // copied from BasicSerializerFactory.buildMapSerializer():
+ boolean staticTyping = config.isEnabled(MapperFeature.USE_STATIC_TYPING);
+ JavaType valueType = type.getContentType();
+ TypeSerializer typeSer = createTypeSerializer(config, valueType);
+ // last 2 nulls; don't know key, value serializers (yet)
+ // 23-Feb-2015, tatu: As per [#705], need to support custom serializers
+ MapSerializer anySer = MapSerializer.construct(null, type, staticTyping, typeSer, null, null, null);
+ // TODO: support '@JsonIgnoreProperties' with any setter?
+ // TODO: can we find full PropertyName?
+ PropertyName name = new PropertyName(anyGetter.getName());
+ BeanProperty.Std anyProp = new BeanProperty.Std(name, valueType, null,
+ beanDesc.getClassAnnotations(), anyGetter, PropertyMetadata.STD_OPTIONAL);
+ builder.setAnyGetter(new AnyGetterWriter(anyProp, anyGetter, anySer));
+ }
+ // Next: need to gather view information, if any:
+ processViews(config, builder);
+
+ // Finally: let interested parties mess with the result bit more...
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ builder = mod.updateBuilder(config, beanDesc, builder);
+ }
+ }
+
+ JsonSerializer ser = (JsonSerializer) builder.build();
+
+ if (ser == null) {
+ // If we get this far, there were no properties found, so no regular BeanSerializer
+ // would be constructed. But, couple of exceptions.
+ // First: if there are known annotations, just create 'empty bean' serializer
+ if (beanDesc.hasKnownClassAnnotations()) {
+ return builder.createDummy();
+ }
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue705() throws Exception
+ {
+ Issue705Bean input = new Issue705Bean(""key"", ""value"");
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(""{\""stuff\"":\""[key/value]\""}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public byte[] getBinaryValue(Base64Variant b64variant)
+ throws IOException, JsonParseException
+ {
+ // Multiple possibilities...
+ JsonNode n = currentNode();
+ if (n != null) {
+ // [databind#2096]: although `binaryValue()` works for real binary node
+ // and embedded ""POJO"" node, coercion from TextNode may require variant, so:
+ byte[] data = n.binaryValue();
+ if (data != null) {
+ return data;
+ }
+ if (n.isPojo()) {
+ Object ob = ((POJONode) n).getPojo();
+ if (ob instanceof byte[]) {
+ return (byte[]) ob;
+ }
+ }
+ }
+ // otherwise return null to mark we have no binary content
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testBase64Text() throws Exception
+ {
+ // let's actually iterate over sets of encoding modes, lengths
+
+ final int[] LENS = { 1, 2, 3, 4, 7, 9, 32, 33, 34, 35 };
+ final Base64Variant[] VARIANTS = {
+ Base64Variants.MIME,
+ Base64Variants.MIME_NO_LINEFEEDS,
+ Base64Variants.MODIFIED_FOR_URL,
+ Base64Variants.PEM
+ };
+
+ for (int len : LENS) {
+ byte[] input = new byte[len];
+ for (int i = 0; i < input.length; ++i) {
+ input[i] = (byte) i;
+ }
+ for (Base64Variant variant : VARIANTS) {
+ TextNode n = new TextNode(variant.encode(input));
+ byte[] data = null;
+ try {
+ data = n.getBinaryValue(variant);
+ } catch (Exception e) {
+ fail(""Failed (variant ""+variant+"", data length ""+len+""): ""+e.getMessage());
+ }
+ assertNotNull(data);
+ assertArrayEquals(data, input);
+
+ // 15-Aug-2018, tatu: [databind#2096] requires another test
+ JsonParser p = new TreeTraversingParser(n);
+ assertEquals(JsonToken.VALUE_STRING, p.nextToken());
+ try {
+ data = p.getBinaryValue(variant);
+ } catch (Exception e) {
+ fail(""Failed (variant ""+variant+"", data length ""+len+""): ""+e.getMessage());
+ }
+ assertNotNull(data);
+ assertArrayEquals(data, input);
+ p.close();
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt)
+ throws IOException
+ {
+ // 01-Dec-2016, tatu: Note: This IS legal to call, but only when unwrapped
+ // value itself is NOT passed via `CreatorProperty` (which isn't supported).
+ // Ok however to pass via setter or field.
+
+ final PropertyBasedCreator creator = _propertyBasedCreator;
+ PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
+
+ TokenBuffer tokens = new TokenBuffer(p, ctxt);
+ tokens.writeStartObject();
+
+ JsonToken t = p.getCurrentToken();
+ for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
+ String propName = p.getCurrentName();
+ p.nextToken(); // to point to value
+ // creator property?
+ SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
+ if (creatorProp != null) {
+ // Last creator property to set?
+ if (buffer.assignParameter(creatorProp,
+ _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
+ t = p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
+ Object bean;
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ bean = wrapInstantiationProblem(e, ctxt);
+ }
+ // [databind#631]: Assign current value, to be accessible by custom serializers
+ p.setCurrentValue(bean);
+ // if so, need to copy all remaining tokens into buffer
+ while (t == JsonToken.FIELD_NAME) {
+ // NOTE: do NOT skip name as it needs to be copied; `copyCurrentStructure` does that
+ p.nextToken();
+ tokens.copyCurrentStructure(p);
+ t = p.nextToken();
+ }
+ // 28-Aug-2018, tatu: Let's add sanity check here, easier to catch off-by-some
+ // problems if we maintain invariants
+ tokens.writeEndObject();
+ if (bean.getClass() != _beanType.getRawClass()) {
+ // !!! 08-Jul-2011, tatu: Could probably support; but for now
+ // it's too complicated, so bail out
+ ctxt.reportInputMismatch(creatorProp,
+ ""Cannot create polymorphic instances with unwrapped values"");
+ return null;
+ }
+ return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
+ }
+ continue;
+ }
+ // Object Id property?
+ if (buffer.readIdProperty(propName)) {
+ continue;
+ }
+ // regular property? needs buffering
+ SettableBeanProperty prop = _beanProperties.find(propName);
+ if (prop != null) {
+ buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));
+ continue;
+ }
+ // Things marked as ignorable should not be passed to any setter
+ if (_ignorableProps != null && _ignorableProps.contains(propName)) {
+ handleIgnoredProperty(p, ctxt, handledType(), propName);
+ continue;
+ }
+ // 29-Nov-2016, tatu: probably should try to avoid sending content
+ // both to any setter AND buffer... but, for now, the only thing
+ // we can do.
+ // how about any setter? We'll get copies but...
+ if (_anySetter == null) {
+ // but... others should be passed to unwrapped property deserializers
+ tokens.writeFieldName(propName);
+ tokens.copyCurrentStructure(p);
+ } else {
+ // Need to copy to a separate buffer first
+ TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);
+ tokens.writeFieldName(propName);
+ tokens.append(b2);
+ try {
+ buffer.bufferAnyProperty(_anySetter, propName,
+ _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));
+ } catch (Exception e) {
+ wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
+ }
+ continue;
+ }
+ }
+
+ // We hit END_OBJECT, so:
+ Object bean;
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ wrapInstantiationProblem(e, ctxt);
+ return null; // never gets here
+ }
+ return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue2088UnwrappedFieldsAfterLastCreatorProp() throws Exception
+ {
+ Issue2088Bean bean = MAPPER.readValue(""{\""x\"":1,\""a\"":2,\""y\"":3,\""b\"":4}"", Issue2088Bean.class);
+ assertEquals(1, bean.x);
+ assertEquals(2, bean.w.a);
+ assertEquals(3, bean.y);
+ assertEquals(4, bean.w.b);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonSerializer> createContextual(SerializerProvider serializers,
+ BeanProperty property) throws JsonMappingException
+ {
+ // Note! Should not skip if `property` null since that'd skip check
+ // for config overrides, in case of root value
+ if (property == null) {
+ return this;
+ }
+ JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
+ if (format == null) {
+ return this;
+ }
+ // Simple case first: serialize as numeric timestamp?
+ JsonFormat.Shape shape = format.getShape();
+ if (shape.isNumeric()) {
+ return withFormat(Boolean.TRUE, null);
+ }
+
+ // 08-Jun-2017, tatu: With [databind#1648], this gets bit tricky..
+ // First: custom pattern will override things
+ if (format.hasPattern()) {
+ final Locale loc = format.hasLocale()
+ ? format.getLocale()
+ : serializers.getLocale();
+ SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);
+ TimeZone tz = format.hasTimeZone() ? format.getTimeZone()
+ : serializers.getTimeZone();
+ df.setTimeZone(tz);
+ return withFormat(Boolean.FALSE, df);
+ }
+
+ // Otherwise, need one of these changes:
+ final boolean hasLocale = format.hasLocale();
+ final boolean hasTZ = format.hasTimeZone();
+ final boolean asString = (shape == JsonFormat.Shape.STRING);
+
+ if (!hasLocale && !hasTZ && !asString) {
+ return this;
+ }
+
+ DateFormat df0 = serializers.getConfig().getDateFormat();
+ // Jackson's own `StdDateFormat` is quite easy to deal with...
+ if (df0 instanceof StdDateFormat) {
+ StdDateFormat std = (StdDateFormat) df0;
+ if (format.hasLocale()) {
+ std = std.withLocale(format.getLocale());
+ }
+ if (format.hasTimeZone()) {
+ std = std.withTimeZone(format.getTimeZone());
+ }
+ return withFormat(Boolean.FALSE, std);
+ }
+
+ // 08-Jun-2017, tatu: Unfortunately there's no generally usable
+ // mechanism for changing `DateFormat` instances (or even clone()ing)
+ // So: require it be `SimpleDateFormat`; can't config other types
+ if (!(df0 instanceof SimpleDateFormat)) {
+ serializers.reportBadDefinition(handledType(), String.format(
+""Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`"",
+df0.getClass().getName()));
+ }
+ SimpleDateFormat df = (SimpleDateFormat) df0;
+ if (hasLocale) {
+ // Ugh. No way to change `Locale`, create copy; must re-crete completely:
+ df = new SimpleDateFormat(df.toPattern(), format.getLocale());
+ } else {
+ df = (SimpleDateFormat) df.clone();
+ }
+ TimeZone newTz = format.getTimeZone();
+ boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());
+ if (changeTZ) {
+ df.setTimeZone(newTz);
+ }
+ return withFormat(Boolean.FALSE, df);
+ }
+
+// Test Case
+[/INST]
+ public void testSqlDateConfigOverride() throws Exception
+ {
+ ObjectMapper mapper = newObjectMapper();
+ mapper.configOverride(java.sql.Date.class)
+ .setFormat(JsonFormat.Value.forPattern(""yyyy+MM+dd""));
+ assertEquals(""\""1980+04+14\"""",
+ mapper.writeValueAsString(java.sql.Date.valueOf(""1980-04-14"")));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected BeanPropertyWriter buildWriter(SerializerProvider prov,
+ BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer> ser,
+ TypeSerializer typeSer, TypeSerializer contentTypeSer,
+ AnnotatedMember am, boolean defaultUseStaticTyping)
+ throws JsonMappingException
+ {
+ // do we have annotation that forces type to use (to declared type or its super type)?
+ JavaType serializationType;
+ try {
+ serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
+ } catch (JsonMappingException e) {
+ if (propDef == null) {
+ return prov.reportBadDefinition(declaredType, e.getMessage());
+ }
+ return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());
+ }
+
+ // Container types can have separate type serializers for content (value / element) type
+ if (contentTypeSer != null) {
+ // 04-Feb-2010, tatu: Let's force static typing for collection, if there is
+ // type information for contents. Should work well (for JAXB case); can be
+ // revisited if this causes problems.
+ if (serializationType == null) {
+// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
+ serializationType = declaredType;
+ }
+ JavaType ct = serializationType.getContentType();
+ // Not exactly sure why, but this used to occur; better check explicitly:
+ if (ct == null) {
+ prov.reportBadPropertyDefinition(_beanDesc, propDef,
+ ""serialization type ""+serializationType+"" has no content"");
+ }
+ serializationType = serializationType.withContentTypeHandler(contentTypeSer);
+ ct = serializationType.getContentType();
+ }
+
+ Object valueToSuppress = null;
+ boolean suppressNulls = false;
+
+ // 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
+ JavaType actualType = (serializationType == null) ? declaredType : serializationType;
+
+ // 17-Mar-2017: [databind#1522] Allow config override per property type
+ AnnotatedMember accessor = propDef.getAccessor();
+ if (accessor == null) {
+ // neither Setter nor ConstructorParameter are expected here
+ return prov.reportBadPropertyDefinition(_beanDesc, propDef,
+ ""could not determine property type"");
+ }
+ Class> rawPropertyType = accessor.getRawType();
+
+ // 17-Aug-2016, tatu: Default inclusion covers global default (for all types), as well
+ // as type-default for enclosing POJO. What we need, then, is per-type default (if any)
+ // for declared property type... and finally property annotation overrides
+ JsonInclude.Value inclV = _config.getDefaultInclusion(actualType.getRawClass(),
+ rawPropertyType, _defaultInclusion);
+
+ // property annotation override
+
+ inclV = inclV.withOverrides(propDef.findInclusion());
+
+ JsonInclude.Include inclusion = inclV.getValueInclusion();
+ if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
+ inclusion = JsonInclude.Include.ALWAYS;
+ }
+ switch (inclusion) {
+ case NON_DEFAULT:
+ // 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
+ // so that if enclosing class has this, we may need to access values of property,
+ // whereas for global defaults OR per-property overrides, we have more
+ // static definition. Sigh.
+ // First: case of class/type specifying it; try to find POJO property defaults
+ Object defaultBean;
+
+ // 16-Oct-2016, tatu: Note: if we cannot for some reason create ""default instance"",
+ // revert logic to the case of general/per-property handling, so both
+ // type-default AND null are to be excluded.
+ // (as per [databind#1417]
+ if (_useRealPropertyDefaults && (defaultBean = getDefaultBean()) != null) {
+ // 07-Sep-2016, tatu: may also need to front-load access forcing now
+ if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {
+ am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
+ }
+ try {
+ valueToSuppress = am.getValue(defaultBean);
+ } catch (Exception e) {
+ _throwWrapped(e, propDef.getName(), defaultBean);
+ }
+ } else {
+ valueToSuppress = BeanUtil.getDefaultValue(actualType);
+ suppressNulls = true;
+ }
+ if (valueToSuppress == null) {
+ suppressNulls = true;
+ } else {
+ if (valueToSuppress.getClass().isArray()) {
+ valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
+ }
+ }
+ break;
+ case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
+ // always suppress nulls
+ suppressNulls = true;
+ // and for referential types, also ""empty"", which in their case means ""absent""
+ if (actualType.isReferenceType()) {
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ }
+ break;
+ case NON_EMPTY:
+ // always suppress nulls
+ suppressNulls = true;
+ // but possibly also 'empty' values:
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ break;
+ case CUSTOM: // new with 2.9
+ valueToSuppress = prov.includeFilterInstance(propDef, inclV.getValueFilter());
+ if (valueToSuppress == null) { // is this legal?
+ suppressNulls = true;
+ } else {
+ suppressNulls = prov.includeFilterSuppressNulls(valueToSuppress);
+ }
+ break;
+ case NON_NULL:
+ suppressNulls = true;
+ // fall through
+ case ALWAYS: // default
+ default:
+ // we may still want to suppress empty collections
+ if (actualType.isContainerType()
+ && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ }
+ break;
+ }
+ Class>[] views = propDef.findViews();
+ if (views == null) {
+ views = _beanDesc.findDefaultViews();
+ }
+ BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
+ am, _beanDesc.getClassAnnotations(), declaredType,
+ ser, typeSer, serializationType, suppressNulls, valueToSuppress, views);
+
+ // How about custom null serializer?
+ Object serDef = _annotationIntrospector.findNullSerializer(am);
+ if (serDef != null) {
+ bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
+ }
+ // And then, handling of unwrapping
+ NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
+ if (unwrapper != null) {
+ bpw = bpw.unwrappingWriter(unwrapper);
+ }
+ return bpw;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object deserializeKey(String key, DeserializationContext ctxt)
+ throws IOException
+ {
+ if (key == null) { // is this even legal call?
+ return null;
+ }
+ try {
+ Object result = _parse(key, ctxt);
+ if (result != null) {
+ return result;
+ }
+ } catch (Exception re) {
+ return ctxt.handleWeirdKey(_keyClass, key, ""not a valid representation, problem: (%s) %s"",
+ re.getClass().getName(),
+ re.getMessage());
+ }
+ if (_keyClass.isEnum() && ctxt.getConfig().isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
+ return null;
+ }
+ return ctxt.handleWeirdKey(_keyClass, key, ""not a valid representation"");
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean includeFilterSuppressNulls(Object filter) throws JsonMappingException
+ {
+ if (filter == null) {
+ return true;
+ }
+ // should let filter decide what to do with nulls:
+ // But just case, let's handle unexpected (from our perspective) problems explicitly
+ try {
+ return filter.equals(null);
+ } catch (Throwable t) {
+ String msg = String.format(
+""Problem determining whether filter of type '%s' should filter out `null` values: (%s) %s"",
+filter.getClass().getName(), t.getClass().getName(), t.getMessage());
+ reportBadDefinition(filter.getClass(), msg, t);
+ return false; // never gets here
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JavaType resolveSubType(JavaType baseType, String subClass)
+ throws JsonMappingException
+ {
+ // 30-Jan-2010, tatu: Most ids are basic class names; so let's first
+ // check if any generics info is added; and only then ask factory
+ // to do translation when necessary
+ if (subClass.indexOf('<') > 0) {
+ // note: may want to try combining with specialization (esp for EnumMap)?
+ // 17-Aug-2017, tatu: As per [databind#1735] need to ensure assignment
+ // compatibility -- needed later anyway, and not doing so may open
+ // security issues.
+ JavaType t = getTypeFactory().constructFromCanonical(subClass);
+ if (t.isTypeOrSubTypeOf(baseType.getRawClass())) {
+ return t;
+ }
+ } else {
+ Class> cls;
+ try {
+ cls = getTypeFactory().findClass(subClass);
+ } catch (ClassNotFoundException e) { // let caller handle this problem
+ return null;
+ } catch (Exception e) {
+ throw invalidTypeIdException(baseType, subClass, String.format(
+ ""problem: (%s) %s"",
+ e.getClass().getName(),
+ e.getMessage()));
+ }
+ if (baseType.isTypeOrSuperTypeOf(cls)) {
+ return getTypeFactory().constructSpecializedType(baseType, cls);
+ }
+ }
+ throw invalidTypeIdException(baseType, subClass, ""Not a subtype"");
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _throwAsIOE(Exception e, Object propName, Object value)
+ throws IOException
+ {
+ if (e instanceof IllegalArgumentException) {
+ String actType = ClassUtil.classNameOf(value);
+ StringBuilder msg = new StringBuilder(""Problem deserializing \""any\"" property '"").append(propName);
+ msg.append(""' of class ""+getClassName()+"" (expected type: "").append(_type);
+ msg.append(""; actual type: "").append(actType).append("")"");
+ String origMsg = e.getMessage();
+ if (origMsg != null) {
+ msg.append("", problem: "").append(origMsg);
+ } else {
+ msg.append("" (no error message provided)"");
+ }
+ throw new JsonMappingException(null, msg.toString(), e);
+ }
+ ClassUtil.throwIfIOE(e);
+ ClassUtil.throwIfRTE(e);
+ // let's wrap the innermost problem
+ Throwable t = ClassUtil.getRootCause(e);
+ throw new JsonMappingException(null, t.getMessage(), t);
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ public JsonDeserializer buildBeanDeserializer(DeserializationContext ctxt,
+ JavaType type, BeanDescription beanDesc)
+ throws JsonMappingException
+ {
+ // First: check what creators we can use, if any
+ ValueInstantiator valueInstantiator;
+ /* 04-Jun-2015, tatu: To work around [databind#636], need to catch the
+ * issue, defer; this seems like a reasonable good place for now.
+ * Note, however, that for non-Bean types (Collections, Maps) this
+ * probably won't work and needs to be added elsewhere.
+ */
+ try {
+ valueInstantiator = findValueInstantiator(ctxt, beanDesc);
+ } catch (NoClassDefFoundError error) {
+ return new ErrorThrowingDeserializer(error);
+ } catch (IllegalArgumentException e) {
+ // 05-Apr-2017, tatu: Although it might appear cleaner to require collector
+ // to throw proper exception, it doesn't actually have reference to this
+ // instance so...
+ throw InvalidDefinitionException.from(ctxt.getParser(),
+ e.getMessage(),
+ beanDesc, null);
+ }
+ BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc);
+ builder.setValueInstantiator(valueInstantiator);
+ // And then setters for deserializing from JSON Object
+ addBeanProps(ctxt, beanDesc, builder);
+ addObjectIdReader(ctxt, beanDesc, builder);
+
+ // managed/back reference fields/setters need special handling... first part
+ addBackReferenceProperties(ctxt, beanDesc, builder);
+ addInjectables(ctxt, beanDesc, builder);
+
+ final DeserializationConfig config = ctxt.getConfig();
+ if (_factoryConfig.hasDeserializerModifiers()) {
+ for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
+ builder = mod.updateBuilder(config, beanDesc, builder);
+ }
+ }
+ JsonDeserializer> deserializer;
+
+ if (type.isAbstract() && !valueInstantiator.canInstantiate()) {
+ deserializer = builder.buildAbstract();
+ } else {
+ deserializer = builder.build();
+ }
+ // may have modifier(s) that wants to modify or replace serializer we just built
+ // (note that `resolve()` and `createContextual()` called later on)
+ if (_factoryConfig.hasDeserializerModifiers()) {
+ for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
+ deserializer = mod.modifyDeserializer(config, beanDesc, deserializer);
+ }
+ }
+ return (JsonDeserializer) deserializer;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonDeserializer _createAndCache2(DeserializationContext ctxt,
+ DeserializerFactory factory, JavaType type)
+ throws JsonMappingException
+ {
+ JsonDeserializer deser;
+ try {
+ deser = _createDeserializer(ctxt, factory, type);
+ } catch (IllegalArgumentException iae) {
+ // We better only expose checked exceptions, since those
+ // are what caller is expected to handle
+ throw JsonMappingException.from(ctxt, iae.getMessage(), iae);
+ }
+ if (deser == null) {
+ return null;
+ }
+ /* cache resulting deserializer? always true for ""plain"" BeanDeserializer
+ * (but can be re-defined for sub-classes by using @JsonCachable!)
+ */
+ // 27-Mar-2015, tatu: As per [databind#735], avoid caching types with custom value desers
+ boolean addToCache = !_hasCustomHandlers(type) && deser.isCachable();
+
+ /* we will temporarily hold on to all created deserializers (to
+ * handle cyclic references, and possibly reuse non-cached
+ * deserializers (list, map))
+ */
+ /* 07-Jun-2010, tatu: Danger: [JACKSON-296] was caused by accidental
+ * resolution of a reference -- couple of ways to prevent this;
+ * either not add Lists or Maps, or clear references eagerly.
+ * Let's actually do both; since both seem reasonable.
+ */
+ /* Need to resolve? Mostly done for bean deserializers; required for
+ * resolving cyclic references.
+ */
+ if (deser instanceof ResolvableDeserializer) {
+ _incompleteDeserializers.put(type, deser);
+ ((ResolvableDeserializer)deser).resolve(ctxt);
+ _incompleteDeserializers.remove(type);
+ }
+ if (addToCache) {
+ _cachedDeserializers.put(type, deser);
+ }
+ return deser;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object _weirdKey(DeserializationContext ctxt, String key, Exception e) throws IOException {
+ return ctxt.handleWeirdKey(_keyClass, key, ""problem: %s"",
+ e.getMessage());
+ }
+
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ protected JsonDeserializer buildBuilderBasedDeserializer(
+ DeserializationContext ctxt, JavaType valueType, BeanDescription builderDesc)
+ throws JsonMappingException
+ {
+ // Creators, anyone? (to create builder itself)
+ ValueInstantiator valueInstantiator;
+ try {
+ valueInstantiator = findValueInstantiator(ctxt, builderDesc);
+ } catch (NoClassDefFoundError error) {
+ return new ErrorThrowingDeserializer(error);
+ } catch (IllegalArgumentException e) {
+ // 05-Apr-2017, tatu: Although it might appear cleaner to require collector
+ // to throw proper exception, it doesn't actually have reference to this
+ // instance so...
+ throw InvalidDefinitionException.from(ctxt.getParser(),
+ e.getMessage(),
+ builderDesc, null);
+ }
+ final DeserializationConfig config = ctxt.getConfig();
+ BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, builderDesc);
+ builder.setValueInstantiator(valueInstantiator);
+ // And then ""with methods"" for deserializing from JSON Object
+ addBeanProps(ctxt, builderDesc, builder);
+ addObjectIdReader(ctxt, builderDesc, builder);
+
+ // managed/back reference fields/setters need special handling... first part
+ addBackReferenceProperties(ctxt, builderDesc, builder);
+ addInjectables(ctxt, builderDesc, builder);
+
+ JsonPOJOBuilder.Value builderConfig = builderDesc.findPOJOBuilderConfig();
+ final String buildMethodName = (builderConfig == null) ?
+ JsonPOJOBuilder.DEFAULT_BUILD_METHOD : builderConfig.buildMethodName;
+
+ // and lastly, find build method to use:
+ AnnotatedMethod buildMethod = builderDesc.findMethod(buildMethodName, null);
+ if (buildMethod != null) { // note: can't yet throw error; may be given build method
+ if (config.canOverrideAccessModifiers()) {
+ ClassUtil.checkAndFixAccess(buildMethod.getMember(), config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
+ }
+ }
+ builder.setPOJOBuilder(buildMethod, builderConfig);
+ // this may give us more information...
+ if (_factoryConfig.hasDeserializerModifiers()) {
+ for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
+ builder = mod.updateBuilder(config, builderDesc, builder);
+ }
+ }
+ JsonDeserializer> deserializer = builder.buildBuilderBased(
+ valueType, buildMethodName);
+
+ // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built:
+ if (_factoryConfig.hasDeserializerModifiers()) {
+ for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
+ deserializer = mod.modifyDeserializer(config, builderDesc, deserializer);
+ }
+ }
+ return (JsonDeserializer) deserializer;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static JsonMappingException fromUnexpectedIOE(IOException src) {
+ return new JsonMappingException(null,
+ String.format(""Unexpected IOException (of type %s): %s"",
+ src.getClass().getName(),
+ src.getMessage()));
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object instantiateBean(boolean fixAccess) {
+ AnnotatedConstructor ac = _classInfo.getDefaultConstructor();
+ if (ac == null) {
+ return null;
+ }
+ if (fixAccess) {
+ ac.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
+ }
+ try {
+ return ac.getAnnotated().newInstance();
+ } catch (Exception e) {
+ Throwable t = e;
+ while (t.getCause() != null) {
+ t = t.getCause();
+ }
+ ClassUtil.throwIfError(t);
+ ClassUtil.throwIfRTE(t);
+ throw new IllegalArgumentException(""Failed to instantiate bean of type ""
+ +_classInfo.getAnnotated().getName()+"": (""+t.getClass().getName()+"") ""
+ +t.getMessage(), t);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""resource"")
+ public static JsonMappingException wrapWithPath(Throwable src, Reference ref)
+ {
+ JsonMappingException jme;
+ if (src instanceof JsonMappingException) {
+ jme = (JsonMappingException) src;
+ } else {
+ // [databind#2128]: try to avoid duplication
+ String msg = src.getMessage();
+ // Let's use a more meaningful placeholder if all we have is null
+ if (msg == null || msg.length() == 0) {
+ msg = ""(was ""+src.getClass().getName()+"")"";
+ }
+ // 17-Aug-2015, tatu: Let's also pass the processor (parser/generator) along
+ Closeable proc = null;
+ if (src instanceof JsonProcessingException) {
+ Object proc0 = ((JsonProcessingException) src).getProcessor();
+ if (proc0 instanceof Closeable) {
+ proc = (Closeable) proc0;
+ }
+ }
+ jme = new JsonMappingException(proc, msg, src);
+ }
+ jme.prependPath(ref);
+ return jme;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Deprecated // since 2.7
+ protected JsonMappingException wrapException(Throwable t)
+ {
+ // 05-Nov-2015, tatu: This used to always unwrap the whole exception, but now only
+ // does so if and until `JsonMappingException` is found.
+ for (Throwable curr = t; curr != null; curr = curr.getCause()) {
+ if (curr instanceof JsonMappingException) {
+ return (JsonMappingException) curr;
+ }
+ }
+ return new JsonMappingException(null,
+ ""Instantiation of ""+getValueTypeDesc()+"" value failed: ""+t.getMessage(), t);
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private IOException _wrapAsIOE(JsonGenerator g, Exception e) {
+ if (e instanceof IOException) {
+ return (IOException) e;
+ }
+ String msg = e.getMessage();
+ if (msg == null) {
+ msg = ""[no message for ""+e.getClass().getName()+""]"";
+ }
+ return new JsonMappingException(g, msg, e);
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected java.util.Date _parseDate(String value, DeserializationContext ctxt)
+ throws IOException
+ {
+ try {
+ // Take empty Strings to mean 'empty' Value, usually 'null':
+ if (_isEmptyOrTextualNull(value)) {
+ return (java.util.Date) getNullValue(ctxt);
+ }
+ return ctxt.parseDate(value);
+ } catch (IllegalArgumentException iae) {
+ return (java.util.Date) ctxt.handleWeirdStringValue(_valueClass, value,
+ ""not a valid representation (error: %s)"",
+ iae.getMessage());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _throwAsIOE(JsonParser p, Exception e, Object value) throws IOException
+ {
+ if (e instanceof IllegalArgumentException) {
+ String actType = ClassUtil.classNameOf(value);
+ StringBuilder msg = new StringBuilder(""Problem deserializing property '"")
+ .append(getName())
+ .append(""' (expected type: "")
+ .append(getType())
+ .append(""; actual type: "")
+ .append(actType).append("")"");
+ String origMsg = e.getMessage();
+ if (origMsg != null) {
+ msg.append("", problem: "")
+ .append(origMsg);
+ } else {
+ msg.append("" (no error message provided)"");
+ }
+ throw JsonMappingException.from(p, msg.toString(), e);
+ }
+ _throwAsIOE(p, e);
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected IOException _throwAsIOE(JsonParser p, Exception e) throws IOException
+ {
+ ClassUtil.throwIfIOE(e);
+ ClassUtil.throwIfRTE(e);
+ // let's wrap the innermost problem
+ Throwable th = ClassUtil.getRootCause(e);
+ throw JsonMappingException.from(p, th.getMessage(), th);
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Date parseDate(String dateStr) throws IllegalArgumentException
+ {
+ try {
+ DateFormat df = getDateFormat();
+ return df.parse(dateStr);
+ } catch (ParseException e) {
+ throw new IllegalArgumentException(String.format(
+ ""Failed to parse Date value '%s': %s"", dateStr,
+ e.getMessage()));
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer _createAndCacheUntypedSerializer(Class> rawType)
+ throws JsonMappingException
+ {
+ JavaType fullType = _config.constructType(rawType);
+ JsonSerializer ser;
+ try {
+ ser = _createUntypedSerializer(fullType);
+ } catch (IllegalArgumentException iae) {
+ // We better only expose checked exceptions, since those
+ // are what caller is expected to handle
+ ser = null; // doesn't matter but compiler whines otherwise
+ reportMappingProblem(iae, iae.getMessage());
+ }
+
+ if (ser != null) {
+ // 21-Dec-2015, tatu: Best to cache for both raw and full-type key
+ _serializerCache.addAndResolveNonTypedSerializer(rawType, fullType, ser, this);
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer _createAndCacheUntypedSerializer(JavaType type)
+ throws JsonMappingException
+ {
+ JsonSerializer ser;
+ try {
+ ser = _createUntypedSerializer(type);
+ } catch (IllegalArgumentException iae) {
+ // We better only expose checked exceptions, since those
+ // are what caller is expected to handle
+ ser = null;
+ reportMappingProblem(iae, iae.getMessage());
+ }
+
+ if (ser != null) {
+ // 21-Dec-2015, tatu: Should we also cache using raw key?
+ _serializerCache.addAndResolveNonTypedSerializer(type, ser, this);
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public TypeDeserializer findTypeDeserializer(DeserializationConfig config,
+ JavaType baseType)
+ throws JsonMappingException
+ {
+ BeanDescription bean = config.introspectClassAnnotations(baseType.getRawClass());
+ AnnotatedClass ac = bean.getClassInfo();
+ AnnotationIntrospector ai = config.getAnnotationIntrospector();
+ TypeResolverBuilder> b = ai.findTypeResolver(config, ac, baseType);
+
+ // Ok: if there is no explicit type info handler, we may want to
+ // use a default. If so, config object knows what to use.
+ Collection subtypes = null;
+ if (b == null) {
+ b = config.getDefaultTyper(baseType);
+ if (b == null) {
+ return null;
+ }
+ } else {
+ subtypes = config.getSubtypeResolver().collectAndResolveSubtypesByTypeId(config, ac);
+ }
+ // May need to figure out default implementation, if none found yet
+ // (note: check for abstract type is not 100% mandatory, more of an optimization)
+ if ((b.getDefaultImpl() == null) && baseType.isAbstract()) {
+ JavaType defaultType = mapAbstractType(config, baseType);
+ if ((defaultType != null) && !defaultType.hasRawClass(baseType.getRawClass())) {
+ b = b.defaultImpl(defaultType.getRawClass());
+ }
+ }
+ // 05-Apt-2018, tatu: Since we get non-mapping exception due to various limitations,
+ // map to better type here
+ try {
+ return b.buildTypeDeserializer(config, baseType, subtypes);
+ } catch (IllegalArgumentException e0) {
+ InvalidDefinitionException e = InvalidDefinitionException.from((JsonParser) null,
+ e0.getMessage(), baseType);
+ e.initCause(e0);
+ throw e;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonMappingException instantiationException(Class> instClass, Throwable cause) {
+ // Most likely problem with Creator definition, right?
+ final JavaType type = constructType(instClass);
+ String excMsg;
+ if (cause == null) {
+ excMsg = ""N/A"";
+ } else if ((excMsg = cause.getMessage()) == null) {
+ excMsg = ClassUtil.nameOf(cause.getClass());
+ }
+ String msg = String.format(""Cannot construct instance of %s, problem: %s"",
+ ClassUtil.nameOf(instClass), excMsg);
+ InvalidDefinitionException e = InvalidDefinitionException.from(_parser, msg, type);
+ e.initCause(cause);
+ return e;
+ }
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testLocationAddition() throws Exception
+ {
+ try {
+ /*Map,?> map =*/ MAPPER.readValue(""{\""value\"":\""foo\""}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _format(TimeZone tz, Locale loc, Date date,
+ StringBuffer buffer)
+ {
+ Calendar cal = _getCalendar(tz);
+ cal.setTime(date);
+ // [databind#2167]: handle range beyond [1, 9999]
+ final int year = cal.get(Calendar.YEAR);
+
+ // Assuming GregorianCalendar, special handling needed for BCE (aka BC)
+ // 22-Nov-2018, tatu: Handling beyond 4-digits is not well specified wrt ISO-8601, but
+ // it seems that plus prefix IS mandated. Padding is an open question, but since agreeement
+ // for max length would be needed, we ewould need to limit to arbitrary length
+ // like five digits (erroring out if beyond or padding to that as minimum).
+ // Instead, let's just print number out as is and let decoder try to make sense of it.
+ pad4(buffer, year);
+ buffer.append('-');
+ pad2(buffer, cal.get(Calendar.MONTH) + 1);
+ buffer.append('-');
+ pad2(buffer, cal.get(Calendar.DAY_OF_MONTH));
+ buffer.append('T');
+ pad2(buffer, cal.get(Calendar.HOUR_OF_DAY));
+ buffer.append(':');
+ pad2(buffer, cal.get(Calendar.MINUTE));
+ buffer.append(':');
+ pad2(buffer, cal.get(Calendar.SECOND));
+ buffer.append('.');
+ pad3(buffer, cal.get(Calendar.MILLISECOND));
+
+ int offset = tz.getOffset(cal.getTimeInMillis());
+ if (offset != 0) {
+ int hours = Math.abs((offset / (60 * 1000)) / 60);
+ int minutes = Math.abs((offset / (60 * 1000)) % 60);
+ buffer.append(offset < 0 ? '-' : '+');
+ pad2(buffer, hours);
+ if( _tzSerializedWithColon ) {
+ buffer.append(':');
+ }
+ pad2(buffer, minutes);
+ } else {
+ // 24-Jun-2017, tatu: While `Z` would be conveniently short, older specs
+ // mandate use of full `+0000`
+// formatted.append('Z');
+ if( _tzSerializedWithColon ) {
+ buffer.append(""+00:00"");
+ }
+ else {
+ buffer.append(""+0000"");
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDateISO8601_10k() throws IOException
+ {
+ ObjectWriter w = MAPPER.writer()
+ .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ serialize(w, judate(10204, 1, 1, 00, 00, 00, 0, ""UTC""), ""+10204-01-01T00:00:00.000+0000"");
+ // and although specification lacks for beyond 5 digits (well, actually even 5...), let's do our best:
+ serialize(w, judate(123456, 1, 1, 00, 00, 00, 0, ""UTC""), ""+123456-01-01T00:00:00.000+0000"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private static void pad4(StringBuffer buffer, int value) {
+ int h = value / 100;
+ if (h == 0) {
+ buffer.append('0').append('0');
+ } else {
+ pad2(buffer, h);
+ value -= (100 * h);
+ }
+ pad2(buffer, value);
+ }
+
+// Test Case
+[/INST]
+ public void testDateISO8601_10k() throws IOException
+ {
+ ObjectWriter w = MAPPER.writer()
+ .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ serialize(w, judate(10204, 1, 1, 00, 00, 00, 0, ""UTC""), ""+10204-01-01T00:00:00.000+0000"");
+ // and although specification lacks for beyond 5 digits (well, actually even 5...), let's do our best:
+ serialize(w, judate(123456, 1, 1, 00, 00, 00, 0, ""UTC""), ""+123456-01-01T00:00:00.000+0000"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testDateISO8601_10k() throws IOException
+ {
+ ObjectWriter w = MAPPER.writer()
+ .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ serialize(w, judate(10204, 1, 1, 00, 00, 00, 0, ""UTC""), ""+10204-01-01T00:00:00.000+0000"");
+ // and although specification lacks for beyond 5 digits (well, actually even 5...), let's do our best:
+ serialize(w, judate(123456, 1, 1, 00, 00, 00, 0, ""UTC""), ""+123456-01-01T00:00:00.000+0000"");
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static JsonDeserializer> find(Class> rawType, String clsName)
+ {
+ if (_classNames.contains(clsName)) {
+ JsonDeserializer> d = FromStringDeserializer.findDeserializer(rawType);
+ if (d != null) {
+ return d;
+ }
+ if (rawType == UUID.class) {
+ return new UUIDDeserializer();
+ }
+ if (rawType == StackTraceElement.class) {
+ return new StackTraceElementDeserializer();
+ }
+ if (rawType == AtomicBoolean.class) {
+ // (note: AtomicInteger/Long work due to single-arg constructor. For now?
+ return new AtomicBooleanDeserializer();
+ }
+ if (rawType == ByteBuffer.class) {
+ return new ByteBufferDeserializer();
+ }
+ }
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testVoidDeser() throws Exception
+ {
+ VoidBean bean = MAPPER.readValue(aposToQuotes(""{'value' : 123 }""),
+ VoidBean.class);
+ assertNull(bean.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testVoidDeser() throws Exception
+ {
+ VoidBean bean = MAPPER.readValue(aposToQuotes(""{'value' : 123 }""),
+ VoidBean.class);
+ assertNull(bean.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public int getIntValue() throws IOException {
+ final NumericNode node = (NumericNode) currentNumericNode();
+ return node.intValue();
+ }
+
+// Test Case
+[/INST]
+ public void testNumberOverflowLong() throws IOException
+ {
+ final BigInteger tooBig = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
+ try (final JsonParser p = MAPPER.readTree(""[ ""+tooBig+"" ]"").traverse()) {
+ assertToken(JsonToken.START_ARRAY, p.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ try {
+ p.getLongValue();
+ fail(""Expected failure for `long` overflow"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""Numeric value (""+tooBig+"") out of range of long"");
+ }
+ }
+ try (final JsonParser p = MAPPER.readTree(""{ \""value\"" : ""+tooBig+"" }"").traverse()) {
+ assertToken(JsonToken.START_OBJECT, p.nextToken());
+ assertToken(JsonToken.FIELD_NAME, p.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ try {
+ p.getLongValue();
+ fail(""Expected failure for `long` overflow"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""Numeric value (""+tooBig+"") out of range of long"");
+ }
+ }
+ // But also from floating-point
+ final String tooBig2 = ""1.0e30"";
+ try (final JsonParser p = MAPPER.readTree(""[ ""+tooBig2+"" ]"").traverse()) {
+ assertToken(JsonToken.START_ARRAY, p.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());
+ assertEquals(NumberType.DOUBLE, p.getNumberType());
+ try {
+ p.getLongValue();
+ fail(""Expected failure for `long` overflow"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""Numeric value (""+tooBig2+"") out of range of long"");
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public long getLongValue() throws IOException {
+ final NumericNode node = (NumericNode) currentNumericNode();
+ return node.longValue();
+ }
+
+// Test Case
+[/INST]
+ public void testNumberOverflowLong() throws IOException
+ {
+ final BigInteger tooBig = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE);
+ try (final JsonParser p = MAPPER.readTree(""[ ""+tooBig+"" ]"").traverse()) {
+ assertToken(JsonToken.START_ARRAY, p.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ try {
+ p.getLongValue();
+ fail(""Expected failure for `long` overflow"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""Numeric value (""+tooBig+"") out of range of long"");
+ }
+ }
+ try (final JsonParser p = MAPPER.readTree(""{ \""value\"" : ""+tooBig+"" }"").traverse()) {
+ assertToken(JsonToken.START_OBJECT, p.nextToken());
+ assertToken(JsonToken.FIELD_NAME, p.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
+ assertEquals(NumberType.BIG_INTEGER, p.getNumberType());
+ try {
+ p.getLongValue();
+ fail(""Expected failure for `long` overflow"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""Numeric value (""+tooBig+"") out of range of long"");
+ }
+ }
+ // But also from floating-point
+ final String tooBig2 = ""1.0e30"";
+ try (final JsonParser p = MAPPER.readTree(""[ ""+tooBig2+"" ]"").traverse()) {
+ assertToken(JsonToken.START_ARRAY, p.nextToken());
+ assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());
+ assertEquals(NumberType.DOUBLE, p.getNumberType());
+ try {
+ p.getLongValue();
+ fail(""Expected failure for `long` overflow"");
+ } catch (InputCoercionException e) {
+ verifyException(e, ""Numeric value (""+tooBig2+"") out of range of long"");
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,
+ String typeId) throws IOException
+ {
+ JsonDeserializer deser = _deserializers.get(typeId);
+ if (deser == null) {
+ /* As per [databind#305], need to provide contextual info. But for
+ * backwards compatibility, let's start by only supporting this
+ * for base class, not via interface. Later on we can add this
+ * to the interface, assuming deprecation at base class helps.
+ */
+ JavaType type = _idResolver.typeFromId(ctxt, typeId);
+ if (type == null) {
+ // use the default impl if no type id available:
+ deser = _findDefaultImplDeserializer(ctxt);
+ if (deser == null) {
+ // 10-May-2016, tatu: We may get some help...
+ JavaType actual = _handleUnknownTypeId(ctxt, typeId);
+ if (actual == null) { // what should this be taken to mean?
+ // 17-Jan-2019, tatu: As per [databind#2221], better NOT return `null` but...
+ return null;
+ }
+ // ... would this actually work?
+ deser = ctxt.findContextualValueDeserializer(actual, _property);
+ }
+ } else {
+ /* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
+ * we actually now need to explicitly narrow from base type (which may have parameterization)
+ * using raw type.
+ *
+ * One complication, though; cannot change 'type class' (simple type to container); otherwise
+ * we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
+ * type in process (getting SimpleType of Map.class which will not work as expected)
+ */
+ if ((_baseType != null)
+ && _baseType.getClass() == type.getClass()) {
+ /* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
+ * but it appears to check that JavaType impl class is the same which is
+ * important for some reason?
+ * Disabling the check will break 2 Enum-related tests.
+ */
+ // 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
+ // generic type with custom type resolvers. If so, should try to retain them.
+ // Whether this is sufficient to avoid problems remains to be seen, but for
+ // now it should improve things.
+ if (!type.hasGenericTypes()) {
+ type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());
+ }
+ }
+ deser = ctxt.findContextualValueDeserializer(type, _property);
+ }
+ _deserializers.put(typeId, deser);
+ }
+ return deser;
+ }
+
+// Test Case
+[/INST]
+ public void testWithDeserializationProblemHandler() throws Exception {
+ final ObjectMapper mapper = new ObjectMapper()
+ .enableDefaultTyping();
+ mapper.addHandler(new DeserializationProblemHandler() {
+ @Override
+ public JavaType handleUnknownTypeId(DeserializationContext ctxt, JavaType baseType, String subTypeId, TypeIdResolver idResolver, String failureMsg) throws IOException {
+// System.out.println(""Print out a warning here"");
+ return ctxt.constructType(Void.class);
+ }
+ });
+ GenericContent processableContent = mapper.readValue(JSON, GenericContent.class);
+ assertNotNull(processableContent.getInnerObjects());
+ assertEquals(2, processableContent.getInnerObjects().size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public T readTree(JsonParser p) throws IOException {
+ return (T) _bindAsTree(p);
+ }
+
+
+// Test Case
+[/INST]
+ public void testNullFromEOFWithParserAndReader() throws Exception
+ {
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY0)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY1)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(new StringReader(EMPTY0))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(new StringReader(EMPTY1))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY0_BYTES)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY1_BYTES)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY1_BYTES, 0, EMPTY1_BYTES.length)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+
+ try (JsonParser p = MAPPER.getFactory().createParser(new ByteArrayInputStream(EMPTY0_BYTES))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(new ByteArrayInputStream(EMPTY1_BYTES))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testNullFromEOFWithParserAndReader() throws Exception
+ {
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY0)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY1)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(new StringReader(EMPTY0))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(new StringReader(EMPTY1))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY0_BYTES)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY1_BYTES)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(EMPTY1_BYTES, 0, EMPTY1_BYTES.length)) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+
+ try (JsonParser p = MAPPER.getFactory().createParser(new ByteArrayInputStream(EMPTY0_BYTES))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ try (JsonParser p = MAPPER.getFactory().createParser(new ByteArrayInputStream(EMPTY1_BYTES))) {
+ _assertNullTree(MAPPER.reader().readTree(p));
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonSerializer> createContextual(SerializerProvider prov,
+ BeanProperty property) throws JsonMappingException
+ {
+ JsonFormat.Value format = findFormatOverrides(prov, property, handledType());
+ if (format != null) {
+ switch (format.getShape()) {
+ case STRING:
+ // [databind#2264]: Need special handling for `BigDecimal`
+ return ToStringSerializer.instance;
+ default:
+ }
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testBigIntegerAsPlainTest() throws Exception
+ {
+ final String NORM_VALUE = ""0.0000000005"";
+ final BigDecimal BD_VALUE = new BigDecimal(NORM_VALUE);
+ final BigDecimalAsString INPUT = new BigDecimalAsString(BD_VALUE);
+ // by default, use the default `toString()`
+ assertEquals(""{\""value\"":\""""+BD_VALUE.toString()+""\""}"", MAPPER.writeValueAsString(INPUT));
+
+ // but can force to ""plain"" notation
+ final ObjectMapper m = jsonMapperBuilder()
+ .enable(StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN)
+ .build();
+ assertEquals(""{\""value\"":\""""+NORM_VALUE+""\""}"", m.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonSerializer> createContextual(SerializerProvider prov,
+ BeanProperty property) throws JsonMappingException
+ {
+ JsonFormat.Value format = findFormatOverrides(prov, property, handledType());
+ if (format != null) {
+ switch (format.getShape()) {
+ case STRING:
+ return ToStringSerializer.instance;
+ default:
+ }
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testBigIntegerAsPlainTest() throws Exception
+ {
+ final String NORM_VALUE = ""0.0000000005"";
+ final BigDecimal BD_VALUE = new BigDecimal(NORM_VALUE);
+ final BigDecimalAsString INPUT = new BigDecimalAsString(BD_VALUE);
+ // by default, use the default `toString()`
+ assertEquals(""{\""value\"":\""""+BD_VALUE.toString()+""\""}"", MAPPER.writeValueAsString(INPUT));
+
+ // but can force to ""plain"" notation
+ final ObjectMapper m = jsonMapperBuilder()
+ .enable(StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN)
+ .build();
+ assertEquals(""{\""value\"":\""""+NORM_VALUE+""\""}"", m.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType _fromVariable(TypeVariable> type, TypeBindings context)
+ {
+ final String name = type.getName();
+ // 19-Mar-2015: Without context, all we can check are bounds.
+ if (context == null) {
+ // And to prevent infinite loops, now need this:
+ return _unknownType();
+ } else {
+ // Ok: here's where context might come in handy!
+ /* 19-Mar-2015, tatu: As per [databind#609], may need to allow
+ * unresolved type variables to handle some cases where bounds
+ * are enough. Let's hope it does not hide real fail cases.
+ */
+ JavaType actualType = context.findType(name);
+ if (actualType != null) {
+ return actualType;
+ }
+ }
+
+ /* 29-Jan-2010, tatu: We used to throw exception here, if type was
+ * bound: but the problem is that this can occur for generic ""base""
+ * method, overridden by sub-class. If so, we will want to ignore
+ * current type (for method) since it will be masked.
+ */
+ Type[] bounds = type.getBounds();
+
+ // With type variables we must use bound information.
+ // Theoretically this gets tricky, as there may be multiple
+ // bounds (""... extends A & B""); and optimally we might
+ // want to choose the best match. Also, bounds are optional;
+ // but here we are lucky in that implicit ""Object"" is
+ // added as bounds if so.
+ // Either way let's just use the first bound, for now, and
+ // worry about better match later on if there is need.
+
+ /* 29-Jan-2010, tatu: One more problem are recursive types
+ * (T extends Comparable). Need to add ""placeholder""
+ * for resolution to catch those.
+ */
+ context._addPlaceholder(name);
+ return _constructType(bounds[0], context);
+ }
+
+// Test Case
+[/INST]
+ public void testLocalType728() throws Exception
+ {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ Method m = Issue728.class.getMethod(""method"", CharSequence.class);
+ assertNotNull(m);
+
+ // Start with return type
+ // first type-erased
+ JavaType t = tf.constructType(m.getReturnType());
+ assertEquals(CharSequence.class, t.getRawClass());
+ // then generic
+ t = tf.constructType(m.getGenericReturnType());
+ assertEquals(CharSequence.class, t.getRawClass());
+
+ // then parameter type
+ t = tf.constructType(m.getParameterTypes()[0]);
+ assertEquals(CharSequence.class, t.getRawClass());
+ t = tf.constructType(m.getGenericParameterTypes()[0]);
+ assertEquals(CharSequence.class, t.getRawClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static JsonDeserializer> findForCollection(DeserializationContext ctxt,
+ JavaType type)
+ throws JsonMappingException
+ {
+ JavaUtilCollectionsConverter conv;
+
+ // 10-Jan-2017, tatu: Some types from `java.util.Collections`/`java.util.Arrays` need bit of help...
+ if (type.hasRawClass(CLASS_AS_ARRAYS_LIST)) {
+ conv = converter(TYPE_AS_LIST, type, List.class);
+ } else if (type.hasRawClass(CLASS_SINGLETON_LIST)) {
+ conv = converter(TYPE_SINGLETON_LIST, type, List.class);
+ } else if (type.hasRawClass(CLASS_SINGLETON_SET)) {
+ conv = converter(TYPE_SINGLETON_SET, type, Set.class);
+ // [databind#2265]: we may have another impl type for unmodifiable Lists, check both
+ } else if (type.hasRawClass(CLASS_UNMODIFIABLE_LIST)) {
+ conv = converter(TYPE_UNMODIFIABLE_LIST, type, List.class);
+ } else if (type.hasRawClass(CLASS_UNMODIFIABLE_SET)) {
+ conv = converter(TYPE_UNMODIFIABLE_SET, type, Set.class);
+ } else {
+ return null;
+ }
+ return new StdDelegatingDeserializer(conv);
+ }
+
+// Test Case
+[/INST]
+ public void testUnmodifiableListFromLinkedList() throws Exception {
+ final List input = new LinkedList<>();
+ input.add(""first"");
+ input.add(""second"");
+
+ // Can't use simple ""_verifyCollection"" as type may change; instead use
+ // bit more flexible check:
+ Collection> act = _writeReadCollection(Collections.unmodifiableList(input));
+ assertEquals(input, act);
+
+ // and this check may be bit fragile (may need to revisit), but is good enough for now:
+ assertEquals(Collections.unmodifiableList(new ArrayList<>(input)).getClass(), act.getClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public AtomicReference getNullValue(DeserializationContext ctxt) throws JsonMappingException {
+ return new AtomicReference();
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public SettableBeanProperty withValueDeserializer(JsonDeserializer> deser) {
+ if (_valueDeserializer == deser) {
+ return this;
+ }
+ // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were
+ return new ObjectIdReferenceProperty(this, deser, _nullProvider);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public SettableBeanProperty withValueDeserializer(JsonDeserializer> deser) {
+ if (_valueDeserializer == deser) {
+ return this;
+ }
+ // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were
+ return new ObjectIdValueProperty(this, deser, _nullProvider);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public SettableBeanProperty withValueDeserializer(JsonDeserializer> deser) {
+ if (_valueDeserializer == deser) {
+ return this;
+ }
+ // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were
+ return new SetterlessProperty(this, deser, _nullProvider);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public SettableBeanProperty withValueDeserializer(JsonDeserializer> deser) {
+ if (_valueDeserializer == deser) {
+ return this;
+ }
+ // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were
+ return new MethodProperty(this, deser, _nullProvider);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public SettableBeanProperty withValueDeserializer(JsonDeserializer> deser) {
+ if (_valueDeserializer == deser) {
+ return this;
+ }
+ // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were
+ return new FieldProperty(this, deser, _nullProvider);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public SettableBeanProperty withValueDeserializer(JsonDeserializer> deser) {
+ if (_valueDeserializer == deser) {
+ return this;
+ }
+ // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were
+ return new CreatorProperty(this, deser, _nullProvider);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object setAndReturn(Object instance, Object value) throws IOException
+ {
+ set(instance, value);
+ return instance;
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Object readResolve() {
+ return new FieldProperty(this);
+ }
+
+// Test Case
+[/INST]
+ public void testNullWithinNested() throws Exception
+ {
+ final ObjectReader r = MAPPER.readerFor(MyBean2303.class);
+ MyBean2303 intRef = r.readValue("" {\""refRef\"": 2 } "");
+ assertNotNull(intRef.refRef);
+ assertNotNull(intRef.refRef.get());
+ assertEquals(intRef.refRef.get().get(), new Integer(2));
+
+ MyBean2303 nullRef = r.readValue("" {\""refRef\"": null } "");
+ assertNotNull(nullRef.refRef);
+ assertNotNull(nullRef.refRef.get());
+ assertNull(nullRef.refRef.get().get());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonDeserializer> createContextual(DeserializationContext ctxt,
+ BeanProperty property) throws JsonMappingException
+ {
+ // May need to resolve types for delegate-based creators:
+ JsonDeserializer delegate = null;
+ if (_valueInstantiator != null) {
+ // [databind#2324]: check both array-delegating and delegating
+ AnnotatedWithParams delegateCreator = _valueInstantiator.getDelegateCreator();
+ if (delegateCreator != null) {
+ JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
+ delegate = findDeserializer(ctxt, delegateType, property);
+ }
+ }
+ JsonDeserializer> valueDeser = _valueDeserializer;
+ final JavaType valueType = _containerType.getContentType();
+ if (valueDeser == null) {
+ // [databind#125]: May have a content converter
+ valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);
+ if (valueDeser == null) {
+ // And we may also need to get deserializer for String
+ valueDeser = ctxt.findContextualValueDeserializer(valueType, property);
+ }
+ } else { // if directly assigned, probably not yet contextual, so:
+ valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType);
+ }
+ // 11-Dec-2015, tatu: Should we pass basic `Collection.class`, or more refined? Mostly
+ // comes down to ""List vs Collection"" I suppose... for now, pass Collection
+ Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,
+ JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser);
+ if (isDefaultDeserializer(valueDeser)) {
+ valueDeser = null;
+ }
+ return withResolved(delegate, valueDeser, nuller, unwrapSingle);
+ }
+
+// Test Case
+[/INST]
+ public void testDeserializeBagOfStrings() throws Exception {
+ WithBagOfStrings result = MAPPER.readerFor(WithBagOfStrings.class)
+ .readValue(""{\""strings\"": [ \""a\"", \""b\"", \""c\""]}"");
+ assertEquals(3, result.getStrings().size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean isCachable() {
+ /* As per [databind#735], existence of value or key deserializer (only passed
+ * if annotated to use non-standard one) should also prevent caching.
+ */
+ return (_valueTypeDeserializer == null)
+ && (_ignorableProperties == null);
+ }
+
+// Test Case
+[/INST]
+ public void testCustomMapValueDeser735() throws Exception {
+ String json = ""{\""map1\"":{\""a\"":1},\""map2\"":{\""a\"":1}}"";
+ TestMapBean735 bean = MAPPER.readValue(json, TestMapBean735.class);
+
+ assertEquals(100, bean.map1.get(""a"").intValue());
+ assertEquals(1, bean.map2.get(""a"").intValue());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object deserializeSetAndReturn(JsonParser jp,
+ DeserializationContext ctxt, Object instance) throws IOException
+ {
+ // note: no null checks (unlike usually); deserializer should fail if one found
+ Object id = _valueDeserializer.deserialize(jp, ctxt);
+
+ /* 02-Apr-2015, tatu: Actually, as per [databind#742], let it be;
+ * missing or null id is needed for some cases, such as cases where id
+ * will be generated externally, at a later point, and is not available
+ * quite yet. Typical use case is with DB inserts.
+ */
+
+ ReadableObjectId roid = ctxt.findObjectId(id, _objectIdReader.generator, _objectIdReader.resolver);
+ roid.bindItem(instance);
+ // also: may need to set a property value as well
+ SettableBeanProperty idProp = _objectIdReader.idProperty;
+ if (idProp != null) {
+ return idProp.setAndReturn(instance, id);
+ }
+ return instance;
+ }
+
+// Test Case
+[/INST]
+ public void testNullObjectId() throws Exception
+ {
+ // Ok, so missing Object Id is ok, but so is null.
+
+ Identifiable value = MAPPER.readValue
+ (aposToQuotes(""{'value':3, 'next':null, 'id':null}""), Identifiable.class);
+ assertNotNull(value);
+ assertEquals(3, value.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public ReadableObjectId findObjectId(Object id, ObjectIdGenerator> gen, ObjectIdResolver resolverType)
+ {
+ /* 02-Apr-2015, tatu: As per [databind#742] should allow 'null', similar to how
+ * missing id already works.
+ */
+
+ final ObjectIdGenerator.IdKey key = gen.key(id);
+
+ if (_objectIds == null) {
+ _objectIds = new LinkedHashMap();
+ } else {
+ ReadableObjectId entry = _objectIds.get(key);
+ if (entry != null) {
+ return entry;
+ }
+ }
+
+ // Not seen yet, must create entry and configure resolver.
+ ObjectIdResolver resolver = null;
+
+ if (_objectIdResolvers == null) {
+ _objectIdResolvers = new ArrayList(8);
+ } else {
+ for (ObjectIdResolver res : _objectIdResolvers) {
+ if (res.canUseFor(resolverType)) {
+ resolver = res;
+ break;
+ }
+ }
+ }
+
+ if (resolver == null) {
+ resolver = resolverType.newForDeserialization(this);
+ // 19-Dec-2014, tatu: For final 2.5.0, remove temporary (2.4.x) work-around
+ // needed to clear state between calls.
+ // !!! 18-Jun-2014, pgelinas: Temporary fix for [#490] until real
+ // fix (for jackson-annotations, SimpleObjectIdResolver) can be added.
+ /*
+ if (resolverType.getClass() == SimpleObjectIdResolver.class) {
+ resolver = new SimpleObjectIdResolver();
+ }
+ */
+ _objectIdResolvers.add(resolver);
+ }
+
+ ReadableObjectId entry = new ReadableObjectId(key);
+ entry.setResolver(resolver);
+ _objectIds.put(key, entry);
+ return entry;
+ }
+
+// Test Case
+[/INST]
+ public void testNullObjectId() throws Exception
+ {
+ // Ok, so missing Object Id is ok, but so is null.
+
+ Identifiable value = MAPPER.readValue
+ (aposToQuotes(""{'value':3, 'next':null, 'id':null}""), Identifiable.class);
+ assertNotNull(value);
+ assertEquals(3, value.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonNode _bindAsTree(JsonParser jp) throws IOException
+ {
+ JsonNode result;
+ JsonToken t = _initForReading(jp);
+ if (t == JsonToken.VALUE_NULL || t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
+ result = NullNode.instance;
+ } else {
+ DeserializationContext ctxt = createDeserializationContext(jp, _config);
+ JsonDeserializer deser = _findRootDeserializer(ctxt, JSON_NODE_TYPE);
+ if (_unwrapRoot) {
+ result = (JsonNode) _unwrapAndDeserialize(jp, ctxt, JSON_NODE_TYPE, deser);
+ } else {
+ result = (JsonNode) deser.deserialize(jp, ctxt);
+ }
+ }
+ // Need to consume the token too
+ jp.clearCurrentToken();
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue744() throws IOException
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ SimpleModule module = new SimpleModule();
+ module.addDeserializer(DataA.class, new DataADeserializer());
+ mapper.registerModule(module);
+
+ DataB db = new DataB();
+ db.da.i = 11;
+ db.k = 13;
+ String jsonBString = mapper.writeValueAsString(db);
+ JsonNode jsonBNode = mapper.valueToTree(db);
+
+ // create parent
+ DataB dbNewViaString = mapper.readValue(jsonBString, DataB.class);
+ assertEquals(5, dbNewViaString.da.i);
+ assertEquals(13, dbNewViaString.k);
+
+ DataB dbNewViaNode = mapper.treeToValue(jsonBNode, DataB.class);
+ assertEquals(5, dbNewViaNode.da.i);
+ assertEquals(13, dbNewViaNode.k);
+
+ // update parent
+ DataB dbUpdViaString = new DataB();
+ DataB dbUpdViaNode = new DataB();
+
+ assertEquals(1, dbUpdViaString.da.i);
+ assertEquals(3, dbUpdViaString.k);
+ mapper.readerForUpdating(dbUpdViaString).readValue(jsonBString);
+ assertEquals(5, dbUpdViaString.da.i);
+ assertEquals(13, dbUpdViaString.k);
+
+ assertEquals(1, dbUpdViaNode.da.i);
+ assertEquals(3, dbUpdViaNode.k);
+
+ mapper.readerForUpdating(dbUpdViaNode).readValue(jsonBNode);
+ assertEquals(5, dbUpdViaNode.da.i);
+ assertEquals(13, dbUpdViaNode.k);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonSerializer> createContextual(SerializerProvider provider, BeanProperty property)
+ throws JsonMappingException
+ {
+ JsonSerializer> delSer = _delegateSerializer;
+ JavaType delegateType = _delegateType;
+
+ if (delSer == null) {
+ // Otherwise, need to locate serializer to delegate to. For that we need type information...
+ if (delegateType == null) {
+ delegateType = _converter.getOutputType(provider.getTypeFactory());
+ }
+ /* 02-Apr-2015, tatu: For ""dynamic case"", where type is only specified as
+ * java.lang.Object (or missing generic), [databind#731]
+ */
+ delSer = provider.findValueSerializer(delegateType);
+ }
+ if (delSer instanceof ContextualSerializer) {
+ delSer = provider.handleSecondaryContextualization(delSer, property);
+ }
+ return (delSer == _delegateSerializer) ? this
+ : withDelegate(_converter, delegateType, delSer);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ @SuppressWarnings(""unchecked"")
+ public JsonSerializer createSerializer(SerializerProvider prov,
+ JavaType origType)
+ throws JsonMappingException
+ {
+ // Very first thing, let's check if there is explicit serializer annotation:
+ final SerializationConfig config = prov.getConfig();
+ BeanDescription beanDesc = config.introspect(origType);
+ JsonSerializer> ser = findSerializerFromAnnotation(prov, beanDesc.getClassInfo());
+ if (ser != null) {
+ return (JsonSerializer) ser;
+ }
+ boolean staticTyping;
+ // Next: we may have annotations that further define types to use...
+ JavaType type = modifyTypeByAnnotation(config, beanDesc.getClassInfo(), origType);
+ if (type == origType) { // no changes, won't force static typing
+ staticTyping = false;
+ } else { // changes; assume static typing; plus, need to re-introspect if class differs
+ staticTyping = true;
+ if (!type.hasRawClass(origType.getRawClass())) {
+ beanDesc = config.introspect(type);
+ }
+ }
+ // Slight detour: do we have a Converter to consider?
+ Converter conv = beanDesc.findSerializationConverter();
+ if (conv == null) { // no, simple
+ return (JsonSerializer) _createSerializer2(prov, type, beanDesc, staticTyping);
+ }
+ JavaType delegateType = conv.getOutputType(prov.getTypeFactory());
+
+ // One more twist, as per [Issue#288]; probably need to get new BeanDesc
+ if (!delegateType.hasRawClass(type.getRawClass())) {
+ beanDesc = config.introspect(delegateType);
+ // [#359]: explicitly check (again) for @JsonSerializer...
+ ser = findSerializerFromAnnotation(prov, beanDesc.getClassInfo());
+ }
+ // [databind#731]: Should skip if nominally java.lang.Object
+ if (ser == null) {
+ ser = _createSerializer2(prov, delegateType, beanDesc, true);
+ }
+ return new StdDelegatingSerializer(conv, delegateType, ser);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException
+ {
+ Object delegateValue = convertValue(value);
+ // should we accept nulls?
+ if (delegateValue == null) {
+ provider.defaultSerializeNull(gen);
+ return;
+ }
+ // 02-Apr-2015, tatu: As per [databind#731] may need to do dynamic lookup
+ _delegateSerializer.serialize(delegateValue, gen, provider);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider provider,
+ TypeSerializer typeSer) throws IOException
+ {
+ /* 03-Oct-2012, tatu: This is actually unlikely to work ok... but for now,
+ * let's give it a chance?
+ */
+ Object delegateValue = convertValue(value);
+ _delegateSerializer.serializeWithType(delegateValue, gen, provider, typeSer);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ @Deprecated // since 2.5
+ public boolean isEmpty(Object value)
+ {
+ Object delegateValue = convertValue(value);
+ return _delegateSerializer.isEmpty(delegateValue);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public boolean isEmpty(SerializerProvider prov, Object value)
+ {
+ Object delegateValue = convertValue(value);
+ return _delegateSerializer.isEmpty(prov, delegateValue);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
+ throws JsonMappingException
+ {
+ /* 03-Sep-2012, tatu: Not sure if this can be made to really work
+ * properly... but for now, try this:
+ */
+ // 02-Apr-2015, tatu: For dynamic case, very little we can do
+ _delegateSerializer.acceptJsonFormatVisitor(visitor, typeHint);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer> findConvertingContentSerializer(SerializerProvider provider,
+ BeanProperty prop, JsonSerializer> existingSerializer)
+ throws JsonMappingException
+ {
+ /* 19-Oct-2014, tatu: As per [databind#357], need to avoid infinite loop
+ * when applying contextual content converter; this is not ideal way,
+ * but should work for most cases.
+ */
+ final AnnotationIntrospector intr = provider.getAnnotationIntrospector();
+ if (intr != null && prop != null) {
+ AnnotatedMember m = prop.getMember();
+ if (m != null) {
+ Object convDef = intr.findSerializationContentConverter(m);
+ if (convDef != null) {
+ Converter conv = provider.converterInstance(prop.getMember(), convDef);
+ JavaType delegateType = conv.getOutputType(provider.getTypeFactory());
+ // [databind#731]: Should skip if nominally java.lang.Object
+ if (existingSerializer == null) {
+ existingSerializer = provider.findValueSerializer(delegateType);
+ }
+ return new StdDelegatingSerializer(conv, delegateType, existingSerializer);
+ }
+ }
+ }
+ return existingSerializer;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer findConvertingSerializer(SerializerProvider provider,
+ BeanPropertyWriter prop)
+ throws JsonMappingException
+ {
+ final AnnotationIntrospector intr = provider.getAnnotationIntrospector();
+ if (intr != null) {
+ AnnotatedMember m = prop.getMember();
+ if (m != null) {
+ Object convDef = intr.findSerializationConverter(m);
+ if (convDef != null) {
+ Converter conv = provider.converterInstance(prop.getMember(), convDef);
+ JavaType delegateType = conv.getOutputType(provider.getTypeFactory());
+ // [databind#731]: Should skip if nominally java.lang.Object
+ JsonSerializer> ser = provider.findValueSerializer(delegateType, prop);
+ return new StdDelegatingSerializer(conv, delegateType, ser);
+ }
+ }
+ }
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testIssue731() throws Exception
+ {
+ String json = objectWriter().writeValueAsString(new ConvertingBeanWithUntypedConverter(1, 2));
+ // must be {""a"":2,""b"":4}
+ assertEquals(""{\""a\"":2,\""b\"":4}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final boolean _add(Annotation ann) {
+ if (_annotations == null) {
+ _annotations = new HashMap,Annotation>();
+ }
+ Annotation previous = _annotations.put(ann.annotationType(), ann);
+ return (previous != null) && previous.equals(ann);
+ }
+
+// Test Case
+[/INST]
+ public void testMixinWithBundles() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
+ String result = mapper.writeValueAsString(new Foo(""result""));
+ assertEquals(""{\""bar\"":\""result\""}"", result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean useForType(JavaType t)
+ {
+ switch (_appliesFor) {
+ case NON_CONCRETE_AND_ARRAYS:
+ while (t.isArrayType()) {
+ t = t.getContentType();
+ }
+ // fall through
+ case OBJECT_AND_NON_CONCRETE:
+// return t.isJavaLangObject() ||
+ return (t.getRawClass() == Object.class)
+ || (!t.isConcrete()
+ // [databind#88] Should not apply to JSON tree models:
+ || TreeNode.class.isAssignableFrom(t.getRawClass()));
+
+ case NON_FINAL:
+ while (t.isArrayType()) {
+ t = t.getContentType();
+ }
+ // [Issue#88] Should not apply to JSON tree models:
+ return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
+ default:
+ //case JAVA_LANG_OBJECT:
+// return t.isJavaLangObject();
+ return (t.getRawClass() == Object.class);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testArrayWithDefaultTyping() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper()
+ .enableDefaultTyping();
+
+ JsonNode array = mapper.readTree(""[ 1, 2 ]"");
+ assertTrue(array.isArray());
+ assertEquals(2, array.size());
+
+ JsonNode obj = mapper.readTree(""{ \""a\"" : 2 }"");
+ assertTrue(obj.isObject());
+ assertEquals(1, obj.size());
+ assertEquals(2, obj.path(""a"").asInt());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ protected MappingIterator(JavaType type, JsonParser p, DeserializationContext ctxt,
+ JsonDeserializer> deser,
+ boolean managedParser, Object valueToUpdate)
+ {
+ _type = type;
+ _parser = p;
+ _context = ctxt;
+ _deserializer = (JsonDeserializer) deser;
+ _closeParser = managedParser;
+ if (valueToUpdate == null) {
+ _updatedValue = null;
+ } else {
+ _updatedValue = (T) valueToUpdate;
+ }
+
+ /* Ok: one more thing; we may have to skip START_ARRAY, assuming
+ * ""wrapped"" sequence; but this is ONLY done for 'managed' parsers
+ * and never if JsonParser was directly passed by caller (if it
+ * was, caller must have either positioned it over first token of
+ * the first element, or cleared the START_ARRAY token explicitly).
+ * Note, however, that we do not try to guess whether this could be
+ * an unwrapped sequence of arrays/Lists: we just assume it is wrapped;
+ * and if not, caller needs to hand us JsonParser instead, pointing to
+ * the first token of the first element.
+ */
+ if (managedParser && (p != null) && p.isExpectedStartArrayToken()) {
+ // If pointing to START_ARRAY, context should be that ARRAY
+ p.clearCurrentToken();
+ // regardless, recovery context should be whatever context we have now,
+ // with sole exception of pointing to a start marker, in which case it's
+ // the parent
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleRootRecovery() throws Exception
+ {
+ final String JSON = aposToQuotes(""{'a':3}{'a':27,'foo':[1,2],'b':{'x':3}} {'a':1,'b':2} "");
+
+ MappingIterator it = MAPPER.readerFor(Bean.class).readValues(JSON);
+ Bean bean = it.nextValue();
+
+ assertNotNull(bean);
+ assertEquals(3, bean.a);
+
+ // second one problematic
+ try {
+ it.nextValue();
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Unrecognized field \""foo\"""");
+ }
+
+ // but should recover nicely
+ bean = it.nextValue();
+ assertNotNull(bean);
+ assertEquals(1, bean.a);
+ assertEquals(2, bean.b);
+
+ assertFalse(it.hasNextValue());
+
+ it.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void close() throws IOException {
+ if (_parser != null) {
+ _parser.close();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleRootRecovery() throws Exception
+ {
+ final String JSON = aposToQuotes(""{'a':3}{'a':27,'foo':[1,2],'b':{'x':3}} {'a':1,'b':2} "");
+
+ MappingIterator it = MAPPER.readerFor(Bean.class).readValues(JSON);
+ Bean bean = it.nextValue();
+
+ assertNotNull(bean);
+ assertEquals(3, bean.a);
+
+ // second one problematic
+ try {
+ it.nextValue();
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Unrecognized field \""foo\"""");
+ }
+
+ // but should recover nicely
+ bean = it.nextValue();
+ assertNotNull(bean);
+ assertEquals(1, bean.a);
+ assertEquals(2, bean.b);
+
+ assertFalse(it.hasNextValue());
+
+ it.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean hasNextValue() throws IOException
+ {
+ if (_parser == null) {
+ return false;
+ // fall-through
+ }
+ if (!_hasNextChecked) {
+ JsonToken t = _parser.getCurrentToken();
+ _hasNextChecked = true;
+ if (t == null) { // un-initialized or cleared; find next
+ t = _parser.nextToken();
+ // If EOF, no more, or if we hit END_ARRAY (although we don't clear the token).
+ if (t == null || t == JsonToken.END_ARRAY) {
+ JsonParser jp = _parser;
+ _parser = null;
+ if (_closeParser) {
+ jp.close();
+ }
+ return false;
+ }
+ }
+ // fall through
+ }
+ return true;
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleRootRecovery() throws Exception
+ {
+ final String JSON = aposToQuotes(""{'a':3}{'a':27,'foo':[1,2],'b':{'x':3}} {'a':1,'b':2} "");
+
+ MappingIterator it = MAPPER.readerFor(Bean.class).readValues(JSON);
+ Bean bean = it.nextValue();
+
+ assertNotNull(bean);
+ assertEquals(3, bean.a);
+
+ // second one problematic
+ try {
+ it.nextValue();
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Unrecognized field \""foo\"""");
+ }
+
+ // but should recover nicely
+ bean = it.nextValue();
+ assertNotNull(bean);
+ assertEquals(1, bean.a);
+ assertEquals(2, bean.b);
+
+ assertFalse(it.hasNextValue());
+
+ it.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public T nextValue() throws IOException
+ {
+ if (!_hasNextChecked) {
+ if (!hasNextValue()) {
+ return _throwNoSuchElement();
+ }
+ }
+ if (_parser == null) {
+ return _throwNoSuchElement();
+ }
+ _hasNextChecked = false;
+
+ try {
+ T value;
+ if (_updatedValue == null) {
+ value = _deserializer.deserialize(_parser, _context);
+ } else{
+ _deserializer.deserialize(_parser, _context, _updatedValue);
+ value = _updatedValue;
+ }
+ return value;
+ } finally {
+ /* 24-Mar-2015, tatu: As per [#733], need to mark token consumed no
+ * matter what, to avoid infinite loop for certain failure cases.
+ * For 2.6 need to improve further.
+ */
+ _parser.clearCurrentToken();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleRootRecovery() throws Exception
+ {
+ final String JSON = aposToQuotes(""{'a':3}{'a':27,'foo':[1,2],'b':{'x':3}} {'a':1,'b':2} "");
+
+ MappingIterator it = MAPPER.readerFor(Bean.class).readValues(JSON);
+ Bean bean = it.nextValue();
+
+ assertNotNull(bean);
+ assertEquals(3, bean.a);
+
+ // second one problematic
+ try {
+ it.nextValue();
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Unrecognized field \""foo\"""");
+ }
+
+ // but should recover nicely
+ bean = it.nextValue();
+ assertNotNull(bean);
+ assertEquals(1, bean.a);
+ assertEquals(2, bean.b);
+
+ assertFalse(it.hasNextValue());
+
+ it.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JavaType _mapType(Class> rawClass)
+ {
+ // 28-May-2015, tatu: Properties are special, as per [databind#810]
+ JavaType[] typeParams = findTypeParameters(rawClass, Map.class);
+ // ok to have no types (""raw"")
+ if (typeParams == null) {
+ return MapType.construct(rawClass, _unknownType(), _unknownType());
+ }
+ // but exactly 2 types if any found
+ if (typeParams.length != 2) {
+ throw new IllegalArgumentException(""Strange Map type ""+rawClass.getName()+"": can not determine type parameters"");
+ }
+ return MapType.construct(rawClass, typeParams[0], typeParams[1]);
+ }
+
+// Test Case
+[/INST]
+ public void testMapToProperties() throws Exception
+ {
+ Bean bean = new Bean();
+ bean.A = 129;
+ bean.B = ""13"";
+ Properties props = MAPPER.convertValue(bean, Properties.class);
+
+ assertEquals(2, props.size());
+
+ assertEquals(""13"", props.getProperty(""B""));
+ // should coercce non-Strings to Strings
+ assertEquals(""129"", props.getProperty(""A""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeObject(Object value) throws IOException
+ {
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, value);
+ /* 28-May-2014, tatu: Tricky choice here; if no codec, should we
+ * err out, or just embed? For now, do latter.
+ */
+// throw new JsonMappingException(""No ObjectCodec configured for TokenBuffer, writeObject() called"");
+ }
+
+// Test Case
+[/INST]
+ public void testConversionOfPojos() throws Exception
+ {
+ final Issue467Bean input = new Issue467Bean(13);
+ final String EXP = ""{\""x\"":13}"";
+
+ // first, sanity check
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(EXP, json);
+
+ // then via conversions: should become JSON Object
+ JsonNode tree = MAPPER.valueToTree(input);
+ assertTrue(""Expected Object, got ""+tree.getNodeType(), tree.isObject());
+ assertEquals(EXP, MAPPER.writeValueAsString(tree));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeTree(TreeNode node) throws IOException
+ {
+
+ // as with 'writeObject()', is codec optional?
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, node);
+ }
+
+
+// Test Case
+[/INST]
+ public void testConversionOfPojos() throws Exception
+ {
+ final Issue467Bean input = new Issue467Bean(13);
+ final String EXP = ""{\""x\"":13}"";
+
+ // first, sanity check
+ String json = MAPPER.writeValueAsString(input);
+ assertEquals(EXP, json);
+
+ // then via conversions: should become JSON Object
+ JsonNode tree = MAPPER.valueToTree(input);
+ assertTrue(""Expected Object, got ""+tree.getNodeType(), tree.isObject());
+ assertEquals(EXP, MAPPER.writeValueAsString(tree));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonNode setAll(Map properties)
+ {
+ for (Map.Entry en : properties.entrySet()) {
+ JsonNode n = en.getValue();
+ if (n == null) {
+ n = nullNode();
+ }
+ _children.put(en.getKey(), n);
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testNamingWithObjectNode() throws Exception
+ {
+ ObjectMapper m = new ObjectMapper();
+ m.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
+ ClassWithObjectNodeField result =
+ m.readValue(
+ ""{ \""id\"": \""1\"", \""json\"": { \""foo\"": \""bar\"", \""baz\"": \""bing\"" } }"",
+ ClassWithObjectNodeField.class);
+ assertNotNull(result);
+ assertEquals(""1"", result.id);
+ assertNotNull(result.json);
+ assertEquals(2, result.json.size());
+ assertEquals(""bing"", result.json.path(""baz"").asText());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testEnumWithJsonPropertyRename() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new EnumWithPropertyAnno[] {
+ EnumWithPropertyAnno.B, EnumWithPropertyAnno.A
+ });
+ assertEquals(""[\""b\"",\""a\""]"", json);
+
+ // and while not really proper place, let's also verify deser while we're at it
+ EnumWithPropertyAnno[] result = MAPPER.readValue(json, EnumWithPropertyAnno[].class);
+ assertNotNull(result);
+ assertEquals(2, result.length);
+ assertSame(EnumWithPropertyAnno.B, result[0]);
+ assertSame(EnumWithPropertyAnno.A, result[1]);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer> _createSerializer2(SerializerProvider prov,
+ JavaType type, BeanDescription beanDesc, boolean staticTyping)
+ throws JsonMappingException
+ {
+ JsonSerializer> ser = findSerializerByAnnotations(prov, type, beanDesc);
+ if (ser != null) {
+ return ser;
+ }
+ final SerializationConfig config = prov.getConfig();
+
+ // Container types differ from non-container types
+ // (note: called method checks for module-provided serializers)
+ if (type.isContainerType()) {
+ if (!staticTyping) {
+ staticTyping = usesStaticTyping(config, beanDesc, null);
+ // [Issue#23]: Need to figure out how to force passed parameterization
+ // to stick...
+ /*
+ if (property == null) {
+ JavaType t = origType.getContentType();
+ if (t != null && !t.hasRawClass(Object.class)) {
+ staticTyping = true;
+ }
+ }
+ */
+ }
+ // 03-Aug-2012, tatu: As per [Issue#40], may require POJO serializer...
+ ser = buildContainerSerializer(prov, type, beanDesc, staticTyping);
+ // Will return right away, since called method does post-processing:
+ if (ser != null) {
+ return ser;
+ }
+ } else {
+ // Modules may provide serializers of POJO types:
+ for (Serializers serializers : customSerializers()) {
+ ser = serializers.findSerializer(config, type, beanDesc);
+ if (ser != null) {
+ break;
+ }
+ }
+ // 25-Jun-2015, tatu: Then JsonSerializable, @JsonValue etc. NOTE! Prior to 2.6,
+ // this call was BEFORE custom serializer lookup, which was wrong.
+ }
+
+ if (ser == null) {
+ // Otherwise, we will check ""primary types""; both marker types that
+ // indicate specific handling (JsonSerializable), or main types that have
+ // precedence over container types
+ ser = findSerializerByLookup(type, config, beanDesc, staticTyping);
+ if (ser == null) {
+ ser = findSerializerByPrimaryType(prov, type, beanDesc, staticTyping);
+ if (ser == null) {
+ // And this is where this class comes in: if type is not a
+ // known ""primary JDK type"", perhaps it's a bean? We can still
+ // get a null, if we can't find a single suitable bean property.
+ ser = findBeanSerializer(prov, type, beanDesc);
+ // Finally: maybe we can still deal with it as an implementation of some basic JDK interface?
+ if (ser == null) {
+ ser = findSerializerByAddonType(config, type, beanDesc, staticTyping);
+ // 18-Sep-2014, tatu: Actually, as per [jackson-databind#539], need to get
+ // 'unknown' serializer assigned earlier, here, so that it gets properly
+ // post-processed
+ if (ser == null) {
+ ser = prov.getUnknownTypeSerializer(beanDesc.getBeanClass());
+ }
+ }
+ }
+ }
+ }
+ if (ser != null) {
+ // [databind#120]: Allow post-processing
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ ser = mod.modifySerializer(config, beanDesc, ser);
+ }
+ }
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testJsonValueWithCustomOverride() throws Exception
+ {
+ final Bean838 INPUT = new Bean838();
+
+ // by default, @JsonValue should be used
+ assertEquals(quote(""value""), MAPPER.writeValueAsString(INPUT));
+
+ // but custom serializer should override it
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(new SimpleModule()
+ .addSerializer(Bean838.class, new Bean838Serializer())
+ );
+ assertEquals(""42"", mapper.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer> buildContainerSerializer(SerializerProvider prov,
+ JavaType type, BeanDescription beanDesc, boolean staticTyping)
+ throws JsonMappingException
+ {
+ final SerializationConfig config = prov.getConfig();
+
+ /* [databind#23], 15-Mar-2013, tatu: must force static handling of root value type,
+ * with just one important exception: if value type is ""untyped"", let's
+ * leave it as is; no clean way to make it work.
+ */
+ if (!staticTyping && type.useStaticType()) {
+ if (!type.isContainerType() || type.getContentType().getRawClass() != Object.class) {
+ staticTyping = true;
+ }
+ }
+
+ // Let's see what we can learn about element/content/value type, type serializer for it:
+ JavaType elementType = type.getContentType();
+ TypeSerializer elementTypeSerializer = createTypeSerializer(config,
+ elementType);
+
+ // if elements have type serializer, can not force static typing:
+ if (elementTypeSerializer != null) {
+ staticTyping = false;
+ }
+ JsonSerializer elementValueSerializer = _findContentSerializer(prov,
+ beanDesc.getClassInfo());
+ if (type.isMapLikeType()) { // implements java.util.Map
+ MapLikeType mlt = (MapLikeType) type;
+ /* 29-Sep-2012, tatu: This is actually too early to (try to) find
+ * key serializer from property annotations, and can lead to caching
+ * issues (see [databind#75]). Instead, must be done from 'createContextual()' call.
+ * But we do need to check class annotations.
+ */
+ JsonSerializer keySerializer = _findKeySerializer(prov, beanDesc.getClassInfo());
+ if (mlt.isTrueMapType()) {
+ return buildMapSerializer(config, (MapType) mlt, beanDesc, staticTyping,
+ keySerializer, elementTypeSerializer, elementValueSerializer);
+ }
+ // With Map-like, just 2 options: (1) Custom, (2) Annotations
+ JsonSerializer> ser = null;
+ for (Serializers serializers : customSerializers()) { // (1) Custom
+ MapLikeType mlType = (MapLikeType) type;
+ ser = serializers.findMapLikeSerializer(config,
+ mlType, beanDesc, keySerializer, elementTypeSerializer, elementValueSerializer);
+ if (ser != null) {
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ ser = mod.modifyMapLikeSerializer(config, mlType, beanDesc, ser);
+ }
+ }
+ return ser;
+ }
+ }
+ return null;
+ }
+ if (type.isCollectionLikeType()) {
+ CollectionLikeType clt = (CollectionLikeType) type;
+ if (clt.isTrueCollectionType()) {
+ return buildCollectionSerializer(config, (CollectionType) clt, beanDesc, staticTyping,
+ elementTypeSerializer, elementValueSerializer);
+ }
+ // With Map-like, just 2 options: (1) Custom, (2) Annotations
+ JsonSerializer> ser = null;
+ CollectionLikeType clType = (CollectionLikeType) type;
+ for (Serializers serializers : customSerializers()) { // (1) Custom
+ ser = serializers.findCollectionLikeSerializer(config,
+ clType, beanDesc, elementTypeSerializer, elementValueSerializer);
+ if (ser != null) {
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ ser = mod.modifyCollectionLikeSerializer(config, clType, beanDesc, ser);
+ }
+ }
+ return ser;
+ }
+ }
+ return null;
+ }
+ if (type.isArrayType()) {
+ return buildArraySerializer(config, (ArrayType) type, beanDesc, staticTyping,
+ elementTypeSerializer, elementValueSerializer);
+ }
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testJsonValueWithCustomOverride() throws Exception
+ {
+ final Bean838 INPUT = new Bean838();
+
+ // by default, @JsonValue should be used
+ assertEquals(quote(""value""), MAPPER.writeValueAsString(INPUT));
+
+ // but custom serializer should override it
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(new SimpleModule()
+ .addSerializer(Bean838.class, new Bean838Serializer())
+ );
+ assertEquals(""42"", mapper.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer> buildCollectionSerializer(SerializationConfig config,
+ CollectionType type, BeanDescription beanDesc, boolean staticTyping,
+ TypeSerializer elementTypeSerializer, JsonSerializer elementValueSerializer)
+ throws JsonMappingException
+ {
+ JsonSerializer> ser = null;
+ // Order of lookups:
+ // 1. Custom serializers
+ // 2. Annotations (@JsonValue, @JsonDeserialize)
+ // 3. Defaults
+ for (Serializers serializers : customSerializers()) { // (1) Custom
+ ser = serializers.findCollectionSerializer(config,
+ type, beanDesc, elementTypeSerializer, elementValueSerializer);
+ if (ser != null) {
+ break;
+ }
+ }
+
+ if (ser == null) {
+ // We may also want to use serialize Collections ""as beans"", if (and only if)
+ // this is specified with `@JsonFormat(shape=Object)`
+ JsonFormat.Value format = beanDesc.findExpectedFormat(null);
+ if (format != null && format.getShape() == JsonFormat.Shape.OBJECT) {
+ return null;
+ }
+ Class> raw = type.getRawClass();
+ if (EnumSet.class.isAssignableFrom(raw)) {
+ // this may or may not be available (Class doesn't; type of field/method does)
+ JavaType enumType = type.getContentType();
+ // and even if nominally there is something, only use if it really is enum
+ if (!enumType.isEnumType()) {
+ enumType = null;
+ }
+ ser = buildEnumSetSerializer(enumType);
+ } else {
+ Class> elementRaw = type.getContentType().getRawClass();
+ if (isIndexedList(raw)) {
+ if (elementRaw == String.class) {
+ // [JACKSON-829] Must NOT use if we have custom serializer
+ if (elementValueSerializer == null || ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
+ ser = IndexedStringListSerializer.instance;
+ }
+ } else {
+ ser = buildIndexedListSerializer(type.getContentType(), staticTyping,
+ elementTypeSerializer, elementValueSerializer);
+ }
+ } else if (elementRaw == String.class) {
+ // [JACKSON-829] Must NOT use if we have custom serializer
+ if (elementValueSerializer == null || ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
+ ser = StringCollectionSerializer.instance;
+ }
+ }
+ if (ser == null) {
+ ser = buildCollectionSerializer(type.getContentType(), staticTyping,
+ elementTypeSerializer, elementValueSerializer);
+ }
+ }
+ }
+ // [databind#120]: Allow post-processing
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ ser = mod.modifyCollectionSerializer(config, type, beanDesc, ser);
+ }
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testJsonValueWithCustomOverride() throws Exception
+ {
+ final Bean838 INPUT = new Bean838();
+
+ // by default, @JsonValue should be used
+ assertEquals(quote(""value""), MAPPER.writeValueAsString(INPUT));
+
+ // but custom serializer should override it
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(new SimpleModule()
+ .addSerializer(Bean838.class, new Bean838Serializer())
+ );
+ assertEquals(""42"", mapper.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer> buildMapSerializer(SerializationConfig config,
+ MapType type, BeanDescription beanDesc,
+ boolean staticTyping, JsonSerializer keySerializer,
+ TypeSerializer elementTypeSerializer, JsonSerializer elementValueSerializer)
+ throws JsonMappingException
+ {
+ JsonSerializer> ser = null;
+
+ // Order of lookups:
+ // 1. Custom serializers
+ // 2. Annotations (@JsonValue, @JsonDeserialize)
+ // 3. Defaults
+
+ for (Serializers serializers : customSerializers()) { // (1) Custom
+ ser = serializers.findMapSerializer(config, type, beanDesc,
+ keySerializer, elementTypeSerializer, elementValueSerializer);
+ if (ser != null) { break; }
+ }
+ if (ser == null) {
+ // 08-Nov-2014, tatu: As per [databind#601], better just use default Map serializer
+ /*
+ if (EnumMap.class.isAssignableFrom(type.getRawClass())
+ && ((keySerializer == null) || ClassUtil.isJacksonStdImpl(keySerializer))) {
+ JavaType keyType = type.getKeyType();
+ // Need to find key enum values...
+ EnumValues enums = null;
+ if (keyType.isEnumType()) { // non-enum if we got it as type erased class (from instance)
+ @SuppressWarnings(""unchecked"")
+ Class> enumClass = (Class>) keyType.getRawClass();
+ enums = EnumValues.construct(config, enumClass);
+ }
+ ser = new EnumMapSerializer(type.getContentType(), staticTyping, enums,
+ elementTypeSerializer, elementValueSerializer);
+ } else {
+ */
+ Object filterId = findFilterId(config, beanDesc);
+ AnnotationIntrospector ai = config.getAnnotationIntrospector();
+ MapSerializer mapSer = MapSerializer.construct(ai.findPropertiesToIgnore(beanDesc.getClassInfo(), true),
+ type, staticTyping, elementTypeSerializer,
+ keySerializer, elementValueSerializer, filterId);
+ Object suppressableValue = findSuppressableContentValue(config,
+ type.getContentType(), beanDesc);
+ if (suppressableValue != null) {
+ mapSer = mapSer.withContentInclusion(suppressableValue);
+ }
+ ser = mapSer;
+ }
+ // [databind#120]: Allow post-processing
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ ser = mod.modifyMapSerializer(config, type, beanDesc, ser);
+ }
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testJsonValueWithCustomOverride() throws Exception
+ {
+ final Bean838 INPUT = new Bean838();
+
+ // by default, @JsonValue should be used
+ assertEquals(quote(""value""), MAPPER.writeValueAsString(INPUT));
+
+ // but custom serializer should override it
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(new SimpleModule()
+ .addSerializer(Bean838.class, new Bean838Serializer())
+ );
+ assertEquals(""42"", mapper.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JsonSerializer> buildArraySerializer(SerializationConfig config,
+ ArrayType type, BeanDescription beanDesc,
+ boolean staticTyping,
+ TypeSerializer elementTypeSerializer, JsonSerializer elementValueSerializer)
+ throws JsonMappingException
+ {
+ // 25-Jun-2015, tatu: Note that unlike with Collection(Like) and Map(Like) types, array
+ // types can not be annotated (in theory I guess we could have mix-ins but... ?)
+ // so we need not do primary annotation lookup here.
+ // So all we need is (1) Custom, (2) Default array serializers
+ JsonSerializer> ser = null;
+
+ for (Serializers serializers : customSerializers()) { // (1) Custom
+ ser = serializers.findArraySerializer(config,
+ type, beanDesc, elementTypeSerializer, elementValueSerializer);
+ if (ser != null) {
+ break;
+ }
+ }
+
+ if (ser == null) {
+ Class> raw = type.getRawClass();
+ // Important: do NOT use standard serializers if non-standard element value serializer specified
+ if (elementValueSerializer == null || ClassUtil.isJacksonStdImpl(elementValueSerializer)) {
+ if (String[].class == raw) {
+ ser = StringArraySerializer.instance;
+ } else {
+ // other standard types?
+ ser = StdArraySerializers.findStandardImpl(raw);
+ }
+ }
+ if (ser == null) {
+ ser = new ObjectArraySerializer(type.getContentType(), staticTyping, elementTypeSerializer,
+ elementValueSerializer);
+ }
+ }
+ // [databind#120]: Allow post-processing
+ if (_factoryConfig.hasSerializerModifiers()) {
+ for (BeanSerializerModifier mod : _factoryConfig.serializerModifiers()) {
+ ser = mod.modifyArraySerializer(config, type, beanDesc, ser);
+ }
+ }
+ return ser;
+ }
+
+// Test Case
+[/INST]
+ public void testJsonValueWithCustomOverride() throws Exception
+ {
+ final Bean838 INPUT = new Bean838();
+
+ // by default, @JsonValue should be used
+ assertEquals(quote(""value""), MAPPER.writeValueAsString(INPUT));
+
+ // but custom serializer should override it
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(new SimpleModule()
+ .addSerializer(Bean838.class, new Bean838Serializer())
+ );
+ assertEquals(""42"", mapper.writeValueAsString(INPUT));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected abstract static class Base extends StdScalarSerializer
+ implements ContextualSerializer
+ {
+
+ protected final JsonParser.NumberType _numberType;
+ protected final String _schemaType;
+ protected final boolean _isInt;
+
+ protected Base(Class> cls, JsonParser.NumberType numberType, String schemaType) {
+ super(cls, false);
+ _numberType = numberType;
+ _schemaType = schemaType;
+ _isInt = (numberType == JsonParser.NumberType.INT)
+ || (numberType == JsonParser.NumberType.LONG)
+ || (numberType == JsonParser.NumberType.BIG_INTEGER)
+ ;
+ }
+
+ @Override
+ public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
+ return createSchemaNode(_schemaType, true);
+ }
+
+ @Override
+ public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
+ {
+ if (_isInt) {
+ JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);
+ if (v2 != null) {
+ v2.numberType(_numberType);
+ }
+ } else {
+ JsonNumberFormatVisitor v2 = visitor.expectNumberFormat(typeHint);
+ if (v2 != null) {
+ v2.numberType(_numberType);
+ }
+ }
+ }
+
+ @Override
+ public JsonSerializer> createContextual(SerializerProvider prov,
+ BeanProperty property) throws JsonMappingException
+ {
+ if (property != null) {
+ AnnotatedMember m = property.getMember();
+ if (m != null) {
+ JsonFormat.Value format = prov.getAnnotationIntrospector().findFormat(m);
+ if (format != null) {
+ switch (format.getShape()) {
+ case STRING:
+ return ToStringSerializer.instance;
+ default:
+ }
+ }
+ }
+ }
+ return this;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testEmptyInclusionScalars() throws IOException
+ {
+ ObjectMapper defMapper = MAPPER;
+ ObjectMapper inclMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
+
+ // First, Strings
+ StringWrapper str = new StringWrapper("""");
+ assertEquals(""{\""str\"":\""\""}"", defMapper.writeValueAsString(str));
+ assertEquals(""{}"", inclMapper.writeValueAsString(str));
+ assertEquals(""{}"", inclMapper.writeValueAsString(new StringWrapper()));
+
+ assertEquals(""{\""value\"":\""x\""}"", defMapper.writeValueAsString(new NonEmptyString(""x"")));
+ assertEquals(""{}"", defMapper.writeValueAsString(new NonEmptyString("""")));
+
+ // Then numbers
+ assertEquals(""{\""value\"":12}"", defMapper.writeValueAsString(new NonEmptyInt(12)));
+ assertEquals(""{}"", defMapper.writeValueAsString(new NonEmptyInt(0)));
+
+ assertEquals(""{\""value\"":1.25}"", defMapper.writeValueAsString(new NonEmptyDouble(1.25)));
+ assertEquals(""{}"", defMapper.writeValueAsString(new NonEmptyDouble(0.0)));
+
+ IntWrapper zero = new IntWrapper(0);
+ assertEquals(""{\""i\"":0}"", defMapper.writeValueAsString(zero));
+ assertEquals(""{}"", inclMapper.writeValueAsString(zero));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public BaseSettings withDateFormat(DateFormat df) {
+ if (_dateFormat == df) {
+ return this;
+ }
+ TimeZone tz = (df == null) ? _timeZone : df.getTimeZone();
+ return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory,
+ _typeResolverBuilder, df, _handlerInstantiator, _locale,
+ tz, _defaultBase64);
+ }
+
+// Test Case
+[/INST]
+ public void testDateFormatConfig() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ TimeZone tz1 = TimeZone.getTimeZone(""America/Los_Angeles"");
+ TimeZone tz2 = TimeZone.getTimeZone(""Central Standard Time"");
+
+ // sanity checks
+ assertEquals(tz1, tz1);
+ assertEquals(tz2, tz2);
+ if (tz1.equals(tz2)) {
+ fail();
+ }
+
+ mapper.setTimeZone(tz1);
+ assertEquals(tz1, mapper.getSerializationConfig().getTimeZone());
+ assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone());
+
+ // also better stick via reader/writer as well
+ assertEquals(tz1, mapper.writer().getConfig().getTimeZone());
+ assertEquals(tz1, mapper.reader().getConfig().getTimeZone());
+
+ SimpleDateFormat f = new SimpleDateFormat(""yyyy-MM-dd HH:mm:ss"");
+ f.setTimeZone(tz2);
+ mapper.setDateFormat(f);
+
+ // should not change the timezone tho
+ assertEquals(tz1, mapper.getSerializationConfig().getTimeZone());
+ assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone());
+ assertEquals(tz1, mapper.writer().getConfig().getTimeZone());
+ assertEquals(tz1, mapper.reader().getConfig().getTimeZone());
+ }`
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JavaType findTypeMapping(DeserializationConfig config, JavaType type)
+ {
+ // this is the main mapping base, so let's
+ Class> src = type.getRawClass();
+ Class> dst = _mappings.get(new ClassKey(src));
+ if (dst == null) {
+ return null;
+ }
+ // 09-Aug-2015, tatu: Instead of direct call via JavaType, better use TypeFactory
+ return type.narrowBy(dst);
+ }
+
+// Test Case
+[/INST]
+ public void testByteArrayTypeOverride890() throws Exception
+ {
+ HiddenBinaryBean890 result = MAPPER.readValue(
+ aposToQuotes(""{'someBytes':'AQIDBA=='}""), HiddenBinaryBean890.class);
+ assertNotNull(result);
+ assertNotNull(result.someBytes);
+ assertEquals(byte[].class, result.someBytes.getClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,
+ String typeId) throws IOException
+ {
+ JsonDeserializer deser = _deserializers.get(typeId);
+ if (deser == null) {
+ /* As per [Databind#305], need to provide contextual info. But for
+ * backwards compatibility, let's start by only supporting this
+ * for base class, not via interface. Later on we can add this
+ * to the interface, assuming deprecation at base class helps.
+ */
+ JavaType type = _idResolver.typeFromId(ctxt, typeId);
+ if (type == null) {
+ // As per [JACKSON-614], use the default impl if no type id available:
+ deser = _findDefaultImplDeserializer(ctxt);
+ if (deser == null) {
+ deser = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);
+ }
+ } else {
+ /* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
+ * we actually now need to explicitly narrow from base type (which may have parameterization)
+ * using raw type.
+ *
+ * One complication, though; can not change 'type class' (simple type to container); otherwise
+ * we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
+ * type in process (getting SimpleType of Map.class which will not work as expected)
+ */
+ if ((_baseType != null)
+ && _baseType.getClass() == type.getClass()) {
+ /* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
+ * but it appears to check that JavaType impl class is the same which is
+ * important for some reason?
+ * Disabling the check will break 2 Enum-related tests.
+ */
+ type = _baseType.narrowBy(type.getRawClass());
+ }
+ deser = ctxt.findContextualValueDeserializer(type, _property);
+ }
+ _deserializers.put(typeId, deser);
+ }
+ return deser;
+ }
+
+// Test Case
+[/INST]
+ public void testByteArrayTypeOverride890() throws Exception
+ {
+ HiddenBinaryBean890 result = MAPPER.readValue(
+ aposToQuotes(""{'someBytes':'AQIDBA=='}""), HiddenBinaryBean890.class);
+ assertNotNull(result);
+ assertNotNull(result.someBytes);
+ assertEquals(byte[].class, result.someBytes.getClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private JavaType modifyTypeByAnnotation(DeserializationContext ctxt,
+ Annotated a, JavaType type)
+ throws JsonMappingException
+ {
+ // first: let's check class for the instance itself:
+ AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
+ Class> subclass = intr.findDeserializationType(a, type);
+ if (subclass != null) {
+ try {
+ type = type.narrowBy(subclass);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(""Failed to narrow type ""+type+"" with concrete-type annotation (value ""+subclass.getName()+""), method '""+a.getName()+""': ""+iae.getMessage(), null, iae);
+ }
+ }
+
+ // then key class
+ if (type.isContainerType()) {
+ Class> keyClass = intr.findDeserializationKeyType(a, type.getKeyType());
+ if (keyClass != null) {
+ // illegal to use on non-Maps
+ if (!(type instanceof MapLikeType)) {
+ throw new JsonMappingException(""Illegal key-type annotation: type ""+type+"" is not a Map(-like) type"");
+ }
+ try {
+ type = ((MapLikeType) type).narrowKey(keyClass);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(""Failed to narrow key type ""+type+"" with key-type annotation (""+keyClass.getName()+""): ""+iae.getMessage(), null, iae);
+ }
+ }
+ JavaType keyType = type.getKeyType();
+ /* 21-Mar-2011, tatu: ... and associated deserializer too (unless already assigned)
+ * (not 100% why or how, but this does seem to get called more than once, which
+ * is not good: for now, let's just avoid errors)
+ */
+ if (keyType != null && keyType.getValueHandler() == null) {
+ Object kdDef = intr.findKeyDeserializer(a);
+ if (kdDef != null) {
+ KeyDeserializer kd = ctxt.keyDeserializerInstance(a, kdDef);
+ if (kd != null) {
+ type = ((MapLikeType) type).withKeyValueHandler(kd);
+ keyType = type.getKeyType(); // just in case it's used below
+ }
+ }
+ }
+
+ // and finally content class; only applicable to structured types
+ Class> cc = intr.findDeserializationContentType(a, type.getContentType());
+ if (cc != null) {
+ try {
+ type = type.narrowContentsBy(cc);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(""Failed to narrow content type ""+type+"" with content-type annotation (""+cc.getName()+""): ""+iae.getMessage(), null, iae);
+ }
+ }
+ // ... as well as deserializer for contents:
+ JavaType contentType = type.getContentType();
+ if (contentType.getValueHandler() == null) { // as with above, avoid resetting (which would trigger exception)
+ Object cdDef = intr.findContentDeserializer(a);
+ if (cdDef != null) {
+ JsonDeserializer> cd = null;
+ if (cdDef instanceof JsonDeserializer>) {
+ cdDef = (JsonDeserializer>) cdDef;
+ } else {
+ Class> cdClass = _verifyAsClass(cdDef, ""findContentDeserializer"", JsonDeserializer.None.class);
+ if (cdClass != null) {
+ cd = ctxt.deserializerInstance(a, cdClass);
+ }
+ }
+ if (cd != null) {
+ type = type.withContentValueHandler(cd);
+ }
+ }
+ }
+ }
+ return type;
+ }
+
+// Test Case
+[/INST]
+ public void testByteArrayTypeOverride890() throws Exception
+ {
+ HiddenBinaryBean890 result = MAPPER.readValue(
+ aposToQuotes(""{'someBytes':'AQIDBA=='}""), HiddenBinaryBean890.class);
+ assertNotNull(result);
+ assertNotNull(result.someBytes);
+ assertEquals(byte[].class, result.someBytes.getClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings({ ""unchecked"" })
+ protected T modifyTypeByAnnotation(DeserializationContext ctxt,
+ Annotated a, T type)
+ throws JsonMappingException
+ {
+ // first: let's check class for the instance itself:
+ AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
+ Class> subclass = intr.findDeserializationType(a, type);
+ if (subclass != null) {
+ try {
+ type = (T) type.narrowBy(subclass);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(""Failed to narrow type ""+type+"" with concrete-type annotation (value ""+subclass.getName()+""), method '""+a.getName()+""': ""+iae.getMessage(), null, iae);
+ }
+ }
+
+ // then key class
+ if (type.isContainerType()) {
+ Class> keyClass = intr.findDeserializationKeyType(a, type.getKeyType());
+ if (keyClass != null) {
+ // illegal to use on non-Maps
+ if (!(type instanceof MapLikeType)) {
+ throw new JsonMappingException(""Illegal key-type annotation: type ""+type+"" is not a Map(-like) type"");
+ }
+ try {
+ type = (T) ((MapLikeType) type).narrowKey(keyClass);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(""Failed to narrow key type ""+type+"" with key-type annotation (""+keyClass.getName()+""): ""+iae.getMessage(), null, iae);
+ }
+ }
+ JavaType keyType = type.getKeyType();
+ /* 21-Mar-2011, tatu: ... and associated deserializer too (unless already assigned)
+ * (not 100% why or how, but this does seem to get called more than once, which
+ * is not good: for now, let's just avoid errors)
+ */
+ if (keyType != null && keyType.getValueHandler() == null) {
+ Object kdDef = intr.findKeyDeserializer(a);
+ KeyDeserializer kd = ctxt.keyDeserializerInstance(a, kdDef);
+ if (kd != null) {
+ type = (T) ((MapLikeType) type).withKeyValueHandler(kd);
+ keyType = type.getKeyType(); // just in case it's used below
+ }
+ }
+
+ // and finally content class; only applicable to structured types
+ Class> cc = intr.findDeserializationContentType(a, type.getContentType());
+ if (cc != null) {
+ try {
+ type = (T) type.narrowContentsBy(cc);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(""Failed to narrow content type ""+type+"" with content-type annotation (""+cc.getName()+""): ""+iae.getMessage(), null, iae);
+ }
+ }
+ // ... as well as deserializer for contents:
+ JavaType contentType = type.getContentType();
+ if (contentType.getValueHandler() == null) { // as with above, avoid resetting (which would trigger exception)
+ Object cdDef = intr.findContentDeserializer(a);
+ JsonDeserializer> cd = ctxt.deserializerInstance(a, cdDef);
+ if (cd != null) {
+ type = (T) type.withContentValueHandler(cd);
+ }
+ }
+ }
+ return type;
+ }
+
+// Test Case
+[/INST]
+ public void testByteArrayTypeOverride890() throws Exception
+ {
+ HiddenBinaryBean890 result = MAPPER.readValue(
+ aposToQuotes(""{'someBytes':'AQIDBA=='}""), HiddenBinaryBean890.class);
+ assertNotNull(result);
+ assertNotNull(result.someBytes);
+ assertEquals(byte[].class, result.someBytes.getClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testEnumHandlers() throws IOException
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ // ensure we have serializers and/or deserializers, first
+ String json = mapper.writerFor(EnumPOJO.class)
+ .writeValueAsString(new EnumPOJO());
+ EnumPOJO result = mapper.readerFor(EnumPOJO.class)
+ .readValue(json);
+ assertNotNull(result);
+
+ // and then use JDK serialization to freeze/thaw objects
+ byte[] bytes = jdkSerialize(mapper);
+ ObjectMapper mapper2 = jdkDeserialize(bytes);
+ assertNotNull(mapper2);
+
+ bytes = jdkSerialize(mapper.readerFor(EnumPOJO.class));
+ ObjectReader r = jdkDeserialize(bytes);
+ assertNotNull(r);
+
+ /* 14-Aug-2015, tatu: Looks like pre-loading JsonSerializer is problematic
+ * at this point; comment out for now. Try to fix later on.
+ */
+ bytes = jdkSerialize(mapper.writerFor(EnumPOJO.class));
+ ObjectWriter w = jdkDeserialize(bytes);
+ assertNotNull(w);
+
+ // plus, ensure objects are usable:
+ String json2 = w.writeValueAsString(new EnumPOJO());
+ assertEquals(json, json2);
+ EnumPOJO result2 = r.readValue(json2);
+ assertNotNull(result2);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)
+ throws IOException
+ {
+ final ExternalTypeHandler ext = _externalTypeIdHandler.start();
+ final PropertyBasedCreator creator = _propertyBasedCreator;
+ PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
+
+ TokenBuffer tokens = new TokenBuffer(p);
+ tokens.writeStartObject();
+
+ JsonToken t = p.getCurrentToken();
+ for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
+ String propName = p.getCurrentName();
+ p.nextToken(); // to point to value
+ // creator property?
+ SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
+ if (creatorProp != null) {
+ // first: let's check to see if this might be part of value with external type id:
+ // 11-Sep-2015, tatu: Important; do NOT pass buffer as last arg, but null,
+ // since it is not the bean
+ if (ext.handlePropertyValue(p, ctxt, propName, buffer)) {
+ ;
+ } else {
+ // Last creator property to set?
+ if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
+ t = p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
+ Object bean;
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
+ continue; // never gets here
+ }
+ // if so, need to copy all remaining tokens into buffer
+ while (t == JsonToken.FIELD_NAME) {
+ p.nextToken(); // to skip name
+ tokens.copyCurrentStructure(p);
+ t = p.nextToken();
+ }
+ if (bean.getClass() != _beanType.getRawClass()) {
+ // !!! 08-Jul-2011, tatu: Could theoretically support; but for now
+ // it's too complicated, so bail out
+ throw ctxt.mappingException(""Can not create polymorphic instances with unwrapped values"");
+ }
+ return ext.complete(p, ctxt, bean);
+ }
+ }
+ continue;
+ }
+ // Object Id property?
+ if (buffer.readIdProperty(propName)) {
+ continue;
+ }
+ // regular property? needs buffering
+ SettableBeanProperty prop = _beanProperties.find(propName);
+ if (prop != null) {
+ buffer.bufferProperty(prop, prop.deserialize(p, ctxt));
+ continue;
+ }
+ // external type id (or property that depends on it)?
+ if (ext.handlePropertyValue(p, ctxt, propName, null)) {
+ continue;
+ }
+ /* As per [JACKSON-313], things marked as ignorable should not be
+ * passed to any setter
+ */
+ if (_ignorableProps != null && _ignorableProps.contains(propName)) {
+ handleIgnoredProperty(p, ctxt, handledType(), propName);
+ continue;
+ }
+ // ""any property""?
+ if (_anySetter != null) {
+ buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
+ }
+ }
+
+ // We hit END_OBJECT; resolve the pieces:
+ try {
+ return ext.complete(p, ctxt, buffer, creator);
+ } catch (Exception e) {
+ wrapInstantiationProblem(e, ctxt);
+ return null; // never gets here
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testInverseExternalId928() throws Exception
+ {
+ final String CLASS = Payload928.class.getName();
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ final String successCase = ""{\""payload\"":{\""something\"":\""test\""},\""class\"":\""""+CLASS+""\""}"";
+ Envelope928 envelope1 = mapper.readValue(successCase, Envelope928.class);
+ assertNotNull(envelope1);
+ assertEquals(Payload928.class, envelope1._payload.getClass());
+
+ // and then re-ordered case that was problematic
+ final String failCase = ""{\""class\"":\""""+CLASS+""\"",\""payload\"":{\""something\"":\""test\""}}"";
+ Envelope928 envelope2 = mapper.readValue(failCase, Envelope928.class);
+ assertNotNull(envelope2);
+ assertEquals(Payload928.class, envelope2._payload.getClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ if (p.getCurrentToken() == JsonToken.START_OBJECT) {
+ p.nextToken();
+ return deserializeObject(p, ctxt, ctxt.getNodeFactory());
+ }
+ // 23-Sep-2015, tatu: Ugh. We may also be given END_OBJECT (similar to FIELD_NAME),
+ // if caller has advanced to the first token of Object, but for empty Object
+ if (p.getCurrentToken() == JsonToken.FIELD_NAME) {
+ return deserializeObject(p, ctxt, ctxt.getNodeFactory());
+ }
+ throw ctxt.mappingException(ObjectNode.class);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue941() throws Exception
+ {
+ ObjectNode object = MAPPER.createObjectNode();
+
+ String json = MAPPER.writeValueAsString(object);
+ System.out.println(""json: ""+json);
+
+ ObjectNode de1 = MAPPER.readValue(json, ObjectNode.class); // this works
+ System.out.println(""Deserialized to ObjectNode: ""+de1);
+
+ MyValue de2 = MAPPER.readValue(json, MyValue.class); // but this throws exception
+ System.out.println(""Deserialized to MyValue: ""+de2);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""resource"")
+ protected final Object _deserialize(JsonParser p, DeserializationContext ctxt,
+ int index, String typeId) throws IOException
+ {
+ JsonParser p2 = _tokens[index].asParser(p);
+ JsonToken t = p2.nextToken();
+ // 29-Sep-2015, tatu: As per [databind#942], nulls need special support
+
+ TokenBuffer merged = new TokenBuffer(p);
+ merged.writeStartArray();
+ merged.writeString(typeId);
+ merged.copyCurrentStructure(p2);
+ merged.writeEndArray();
+
+ // needs to point to START_OBJECT (or whatever first token is)
+ JsonParser mp = merged.asParser(p);
+ mp.nextToken();
+ return _properties[index].getProperty().deserialize(mp, ctxt);
+ }
+
+
+// Test Case
+[/INST]
+ public void testExternalTypeIdWithNull() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerSubtypes(ValueBean.class);
+ ExternalBean b;
+ b = mapper.readValue(aposToQuotes(""{'bean':null,'extType':'vbean'}""),
+ ExternalBean.class);
+ assertNotNull(b);
+ b = mapper.readValue(aposToQuotes(""{'extType':'vbean','bean':null}""),
+ ExternalBean.class);
+ assertNotNull(b);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""resource"")
+ protected final void _deserializeAndSet(JsonParser p, DeserializationContext ctxt,
+ Object bean, int index, String typeId) throws IOException
+ {
+ /* Ok: time to mix type id, value; and we will actually use ""wrapper-array""
+ * style to ensure we can handle all kinds of JSON constructs.
+ */
+ JsonParser p2 = _tokens[index].asParser(p);
+ JsonToken t = p2.nextToken();
+ // 29-Sep-2015, tatu: As per [databind#942], nulls need special support
+ TokenBuffer merged = new TokenBuffer(p);
+ merged.writeStartArray();
+ merged.writeString(typeId);
+
+ merged.copyCurrentStructure(p2);
+ merged.writeEndArray();
+ // needs to point to START_OBJECT (or whatever first token is)
+ JsonParser mp = merged.asParser(p);
+ mp.nextToken();
+ _properties[index].getProperty().deserializeAndSet(mp, ctxt, bean);
+ }
+
+// Test Case
+[/INST]
+ public void testExternalTypeIdWithNull() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerSubtypes(ValueBean.class);
+ ExternalBean b;
+ b = mapper.readValue(aposToQuotes(""{'bean':null,'extType':'vbean'}""),
+ ExternalBean.class);
+ assertNotNull(b);
+ b = mapper.readValue(aposToQuotes(""{'extType':'vbean','bean':null}""),
+ ExternalBean.class);
+ assertNotNull(b);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String[] deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
+ {
+ // Ok: must point to START_ARRAY (or equivalent)
+ if (!jp.isExpectedStartArrayToken()) {
+ return handleNonArray(jp, ctxt);
+ }
+ if (_elementDeserializer != null) {
+ return _deserializeCustom(jp, ctxt);
+ }
+
+ final ObjectBuffer buffer = ctxt.leaseObjectBuffer();
+ Object[] chunk = buffer.resetAndStart();
+
+ int ix = 0;
+ JsonToken t;
+
+ while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
+ // Ok: no need to convert Strings, but must recognize nulls
+ String value;
+ if (t == JsonToken.VALUE_STRING) {
+ value = jp.getText();
+ } else if (t == JsonToken.VALUE_NULL) {
+ value = _elementDeserializer.getNullValue();
+ } else {
+ value = _parseString(jp, ctxt);
+ }
+ if (ix >= chunk.length) {
+ chunk = buffer.appendCompletedChunk(chunk);
+ ix = 0;
+ }
+ chunk[ix++] = value;
+ }
+ String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class);
+ ctxt.returnObjectBuffer(buffer);
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testStringArray() throws Exception
+ {
+ final String[] STRS = new String[] {
+ ""a"", ""b"", ""abcd"", """", ""???"", ""\""quoted\"""", ""lf: \n"",
+ };
+ StringWriter sw = new StringWriter();
+ JsonGenerator jg = MAPPER.getFactory().createGenerator(sw);
+ jg.writeStartArray();
+ for (String str : STRS) {
+ jg.writeString(str);
+ }
+ jg.writeEndArray();
+ jg.close();
+
+ String[] result = MAPPER.readValue(sw.toString(), String[].class);
+ assertNotNull(result);
+
+ assertEquals(STRS.length, result.length);
+ for (int i = 0; i < STRS.length; ++i) {
+ assertEquals(STRS[i], result[i]);
+ }
+
+ // [#479]: null handling was busted in 2.4.0
+ result = MAPPER.readValue("" [ null ]"", String[].class);
+ assertNotNull(result);
+ assertEquals(1, result.length);
+ assertNull(result[0]);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final String[] _deserializeCustom(JsonParser jp, DeserializationContext ctxt) throws IOException
+ {
+ final ObjectBuffer buffer = ctxt.leaseObjectBuffer();
+ Object[] chunk = buffer.resetAndStart();
+ final JsonDeserializer deser = _elementDeserializer;
+
+ int ix = 0;
+ JsonToken t;
+
+ while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
+ // Ok: no need to convert Strings, but must recognize nulls
+ String value = (t == JsonToken.VALUE_NULL) ? null : deser.deserialize(jp, ctxt);
+ if (ix >= chunk.length) {
+ chunk = buffer.appendCompletedChunk(chunk);
+ ix = 0;
+ }
+ chunk[ix++] = value;
+ }
+ String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class);
+ ctxt.returnObjectBuffer(buffer);
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testStringArray() throws Exception
+ {
+ final String[] STRS = new String[] {
+ ""a"", ""b"", ""abcd"", """", ""???"", ""\""quoted\"""", ""lf: \n"",
+ };
+ StringWriter sw = new StringWriter();
+ JsonGenerator jg = MAPPER.getFactory().createGenerator(sw);
+ jg.writeStartArray();
+ for (String str : STRS) {
+ jg.writeString(str);
+ }
+ jg.writeEndArray();
+ jg.close();
+
+ String[] result = MAPPER.readValue(sw.toString(), String[].class);
+ assertNotNull(result);
+
+ assertEquals(STRS.length, result.length);
+ for (int i = 0; i < STRS.length; ++i) {
+ assertEquals(STRS[i], result[i]);
+ }
+
+ // [#479]: null handling was busted in 2.4.0
+ result = MAPPER.readValue("" [ null ]"", String[].class);
+ assertNotNull(result);
+ assertEquals(1, result.length);
+ assertNull(result[0]);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public TokenBuffer(JsonParser p, DeserializationContext ctxt)
+ {
+ _objectCodec = p.getCodec();
+ _generatorFeatures = DEFAULT_GENERATOR_FEATURES;
+ _writeContext = JsonWriteContext.createRootContext(null);
+ // at first we have just one segment
+ _first = _last = new Segment();
+ _appendAt = 0;
+ _hasNativeTypeIds = p.canReadTypeId();
+ _hasNativeObjectIds = p.canReadObjectId();
+ _mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
+ }
+
+// Test Case
+[/INST]
+ public void testBigDecimal965() throws Exception
+ {
+
+ Wrapper965 w = new Wrapper965();
+ w.typeEnum = Type965.BIG_DECIMAL;
+ final String NUM_STR = ""-10000000000.0000000001"";
+ w.value = new BigDecimal(NUM_STR);
+
+ String json = MAPPER.writeValueAsString(w);
+
+ // simple sanity check so serialization is faithful
+ if (!json.contains(NUM_STR)) {
+ fail(""JSON content should contain value '""+NUM_STR+""', does not appear to: ""+json);
+ }
+
+ Wrapper965 w2 = MAPPER.readerFor(Wrapper965.class)
+ .with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .readValue(json);
+
+ assertEquals(w.typeEnum, w2.typeEnum);
+ assertTrue(String.format(""Expected %s = %s; got back %s = %s"",
+ w.value.getClass().getSimpleName(), w.value.toString(), w2.value.getClass().getSimpleName(), w2.value.toString()),
+ w.value.equals(w2.value));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void copyCurrentEvent(JsonParser p) throws IOException
+ {
+ if (_mayHaveNativeIds) {
+ _checkNativeIds(p);
+ }
+ switch (p.getCurrentToken()) {
+ case START_OBJECT:
+ writeStartObject();
+ break;
+ case END_OBJECT:
+ writeEndObject();
+ break;
+ case START_ARRAY:
+ writeStartArray();
+ break;
+ case END_ARRAY:
+ writeEndArray();
+ break;
+ case FIELD_NAME:
+ writeFieldName(p.getCurrentName());
+ break;
+ case VALUE_STRING:
+ if (p.hasTextCharacters()) {
+ writeString(p.getTextCharacters(), p.getTextOffset(), p.getTextLength());
+ } else {
+ writeString(p.getText());
+ }
+ break;
+ case VALUE_NUMBER_INT:
+ switch (p.getNumberType()) {
+ case INT:
+ writeNumber(p.getIntValue());
+ break;
+ case BIG_INTEGER:
+ writeNumber(p.getBigIntegerValue());
+ break;
+ default:
+ writeNumber(p.getLongValue());
+ }
+ break;
+ case VALUE_NUMBER_FLOAT:
+ /* 10-Oct-2015, tatu: Ideally we would first determine whether underlying
+ * number is already decoded into a number (in which case might as well
+ * access as number); or is still retained as text (in which case we
+ * should further defer decoding that may not need BigDecimal):
+ */
+ switch (p.getNumberType()) {
+ case BIG_DECIMAL:
+ writeNumber(p.getDecimalValue());
+ break;
+ case FLOAT:
+ writeNumber(p.getFloatValue());
+ break;
+ default:
+ writeNumber(p.getDoubleValue());
+ }
+ break;
+ case VALUE_TRUE:
+ writeBoolean(true);
+ break;
+ case VALUE_FALSE:
+ writeBoolean(false);
+ break;
+ case VALUE_NULL:
+ writeNull();
+ break;
+ case VALUE_EMBEDDED_OBJECT:
+ writeObject(p.getEmbeddedObject());
+ break;
+ default:
+ throw new RuntimeException(""Internal error: should never end up through this code path"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBigDecimal965() throws Exception
+ {
+
+ Wrapper965 w = new Wrapper965();
+ w.typeEnum = Type965.BIG_DECIMAL;
+ final String NUM_STR = ""-10000000000.0000000001"";
+ w.value = new BigDecimal(NUM_STR);
+
+ String json = MAPPER.writeValueAsString(w);
+
+ // simple sanity check so serialization is faithful
+ if (!json.contains(NUM_STR)) {
+ fail(""JSON content should contain value '""+NUM_STR+""', does not appear to: ""+json);
+ }
+
+ Wrapper965 w2 = MAPPER.readerFor(Wrapper965.class)
+ .with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .readValue(json);
+
+ assertEquals(w.typeEnum, w2.typeEnum);
+ assertTrue(String.format(""Expected %s = %s; got back %s = %s"",
+ w.value.getClass().getSimpleName(), w.value.toString(), w2.value.getClass().getSimpleName(), w2.value.toString()),
+ w.value.equals(w2.value));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings({ ""unchecked"", ""resource"" })
+ public T valueToTree(Object fromValue)
+ throws IllegalArgumentException
+ {
+ if (fromValue == null) return null;
+ TokenBuffer buf = new TokenBuffer(this, false);
+ JsonNode result;
+ try {
+ writeValue(buf, fromValue);
+ JsonParser jp = buf.asParser();
+ result = readTree(jp);
+ jp.close();
+ } catch (IOException e) { // should not occur, no real i/o...
+ throw new IllegalArgumentException(e.getMessage(), e);
+ }
+ return (T) result;
+ }
+
+// Test Case
+[/INST]
+ public void testBigDecimal965() throws Exception
+ {
+
+ Wrapper965 w = new Wrapper965();
+ w.typeEnum = Type965.BIG_DECIMAL;
+ final String NUM_STR = ""-10000000000.0000000001"";
+ w.value = new BigDecimal(NUM_STR);
+
+ String json = MAPPER.writeValueAsString(w);
+
+ // simple sanity check so serialization is faithful
+ if (!json.contains(NUM_STR)) {
+ fail(""JSON content should contain value '""+NUM_STR+""', does not appear to: ""+json);
+ }
+
+ Wrapper965 w2 = MAPPER.readerFor(Wrapper965.class)
+ .with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .readValue(json);
+
+ assertEquals(w.typeEnum, w2.typeEnum);
+ assertTrue(String.format(""Expected %s = %s; got back %s = %s"",
+ w.value.getClass().getSimpleName(), w.value.toString(), w2.value.getClass().getSimpleName(), w2.value.toString()),
+ w.value.equals(w2.value));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""resource"")
+ protected Object _convert(Object fromValue, JavaType toValueType)
+ throws IllegalArgumentException
+ {
+ // also, as per [Issue-11], consider case for simple cast
+ /* But with caveats: one is that while everything is Object.class, we don't
+ * want to ""optimize"" that out; and the other is that we also do not want
+ * to lose conversions of generic types.
+ */
+ Class> targetType = toValueType.getRawClass();
+ if (targetType != Object.class
+ && !toValueType.hasGenericTypes()
+ && targetType.isAssignableFrom(fromValue.getClass())) {
+ return fromValue;
+ }
+
+ // Then use TokenBuffer, which is a JsonGenerator:
+ TokenBuffer buf = new TokenBuffer(this, false);
+ try {
+ // inlined 'writeValue' with minor changes:
+ // first: disable wrapping when writing
+ SerializationConfig config = getSerializationConfig().without(SerializationFeature.WRAP_ROOT_VALUE);
+ // no need to check for closing of TokenBuffer
+ _serializerProvider(config).serializeValue(buf, fromValue);
+
+ // then matching read, inlined 'readValue' with minor mods:
+ final JsonParser jp = buf.asParser();
+ Object result;
+ // ok to pass in existing feature flags; unwrapping handled by mapper
+ final DeserializationConfig deserConfig = getDeserializationConfig();
+ JsonToken t = _initForReading(jp);
+ if (t == JsonToken.VALUE_NULL) {
+ DeserializationContext ctxt = createDeserializationContext(jp, deserConfig);
+ result = _findRootDeserializer(ctxt, toValueType).getNullValue(ctxt);
+ } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
+ result = null;
+ } else { // pointing to event other than null
+ DeserializationContext ctxt = createDeserializationContext(jp, deserConfig);
+ JsonDeserializer deser = _findRootDeserializer(ctxt, toValueType);
+ // note: no handling of unwarpping
+ result = deser.deserialize(jp, ctxt);
+ }
+ jp.close();
+ return result;
+ } catch (IOException e) { // should not occur, no real i/o...
+ throw new IllegalArgumentException(e.getMessage(), e);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testBigDecimal965() throws Exception
+ {
+
+ Wrapper965 w = new Wrapper965();
+ w.typeEnum = Type965.BIG_DECIMAL;
+ final String NUM_STR = ""-10000000000.0000000001"";
+ w.value = new BigDecimal(NUM_STR);
+
+ String json = MAPPER.writeValueAsString(w);
+
+ // simple sanity check so serialization is faithful
+ if (!json.contains(NUM_STR)) {
+ fail(""JSON content should contain value '""+NUM_STR+""', does not appear to: ""+json);
+ }
+
+ Wrapper965 w2 = MAPPER.readerFor(Wrapper965.class)
+ .with(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+ .readValue(json);
+
+ assertEquals(w.typeEnum, w2.typeEnum);
+ assertTrue(String.format(""Expected %s = %s; got back %s = %s"",
+ w.value.getClass().getSimpleName(), w.value.toString(), w2.value.getClass().getSimpleName(), w2.value.toString()),
+ w.value.equals(w2.value));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeString(String text) throws IOException {
+ if (text == null) {
+ writeNull();
+ } else {
+ _append(JsonToken.VALUE_STRING, text);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeString(SerializableString text) throws IOException {
+ if (text == null) {
+ writeNull();
+ } else {
+ _append(JsonToken.VALUE_STRING, text);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeRawValue(String text) throws IOException {
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, new RawValue(text));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeRawValue(String text, int offset, int len) throws IOException {
+ if (offset > 0 || len != text.length()) {
+ text = text.substring(offset, offset+len);
+ }
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, new RawValue(text));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeRawValue(char[] text, int offset, int len) throws IOException {
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, new String(text, offset, len));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(short i) throws IOException {
+ _append(JsonToken.VALUE_NUMBER_INT, Short.valueOf(i));
+ }
+
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(int i) throws IOException {
+ _append(JsonToken.VALUE_NUMBER_INT, Integer.valueOf(i));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(long l) throws IOException {
+ _append(JsonToken.VALUE_NUMBER_INT, Long.valueOf(l));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(double d) throws IOException {
+ _append(JsonToken.VALUE_NUMBER_FLOAT, Double.valueOf(d));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(float f) throws IOException {
+ _append(JsonToken.VALUE_NUMBER_FLOAT, Float.valueOf(f));
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(BigDecimal dec) throws IOException {
+ if (dec == null) {
+ writeNull();
+ } else {
+ _append(JsonToken.VALUE_NUMBER_FLOAT, dec);
+ }
+ }
+
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(BigInteger v) throws IOException {
+ if (v == null) {
+ writeNull();
+ } else {
+ _append(JsonToken.VALUE_NUMBER_INT, v);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNumber(String encodedValue) throws IOException {
+ /* 03-Dec-2010, tatu: related to [JACKSON-423], should try to keep as numeric
+ * identity as long as possible
+ */
+ _append(JsonToken.VALUE_NUMBER_FLOAT, encodedValue);
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeBoolean(boolean state) throws IOException {
+ _append(state ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE);
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeNull() throws IOException {
+ _append(JsonToken.VALUE_NULL);
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeObject(Object value) throws IOException
+ {
+ if (value == null) {
+ writeNull();
+ return;
+ }
+ Class> raw = value.getClass();
+ if (raw == byte[].class || (value instanceof RawValue)) {
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, value);
+ return;
+ }
+ if (_objectCodec == null) {
+ /* 28-May-2014, tatu: Tricky choice here; if no codec, should we
+ * err out, or just embed? For now, do latter.
+ */
+// throw new JsonMappingException(""No ObjectCodec configured for TokenBuffer, writeObject() called"");
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, value);
+ } else {
+ _objectCodec.writeValue(this, value);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void writeTree(TreeNode node) throws IOException
+ {
+ if (node == null) {
+ writeNull();
+ return;
+ }
+
+ if (_objectCodec == null) {
+ // as with 'writeObject()', is codec optional?
+ _append(JsonToken.VALUE_EMBEDDED_OBJECT, node);
+ } else {
+ _objectCodec.writeTree(this, node);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testOutputContext() throws IOException
+ {
+ TokenBuffer buf = new TokenBuffer(null, false); // no ObjectCodec
+ StringWriter w = new StringWriter();
+ JsonGenerator gen = MAPPER.getFactory().createGenerator(w);
+
+ // test content: [{""a"":1,""b"":{""c"":2}},{""a"":2,""b"":{""c"":3}}]
+
+ buf.writeStartArray();
+ gen.writeStartArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""a"");
+ gen.writeFieldName(""a"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(1);
+ gen.writeNumber(1);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""b"");
+ gen.writeFieldName(""b"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeStartObject();
+ gen.writeStartObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeFieldName(""c"");
+ gen.writeFieldName(""c"");
+ _verifyOutputContext(buf, gen);
+
+ buf.writeNumber(2);
+ gen.writeNumber(2);
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndObject();
+ gen.writeEndObject();
+ _verifyOutputContext(buf, gen);
+
+ buf.writeEndArray();
+ gen.writeEndArray();
+ _verifyOutputContext(buf, gen);
+
+ buf.close();
+ gen.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ switch (p.getCurrentTokenId()) {
+ case JsonTokenId.ID_START_OBJECT:
+ case JsonTokenId.ID_FIELD_NAME:
+ // 28-Oct-2015, tatu: [databind#989] We may also be given END_OBJECT (similar to FIELD_NAME),
+ // if caller has advanced to the first token of Object, but for empty Object
+ if (_mapDeserializer != null) {
+ return _mapDeserializer.deserialize(p, ctxt);
+ }
+ return mapObject(p, ctxt);
+ case JsonTokenId.ID_START_ARRAY:
+ if (ctxt.isEnabled(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY)) {
+ return mapArrayToArray(p, ctxt);
+ }
+ if (_listDeserializer != null) {
+ return _listDeserializer.deserialize(p, ctxt);
+ }
+ return mapArray(p, ctxt);
+ case JsonTokenId.ID_EMBEDDED_OBJECT:
+ return p.getEmbeddedObject();
+ case JsonTokenId.ID_STRING:
+ if (_stringDeserializer != null) {
+ return _stringDeserializer.deserialize(p, ctxt);
+ }
+ return p.getText();
+
+ case JsonTokenId.ID_NUMBER_INT:
+ if (_numberDeserializer != null) {
+ return _numberDeserializer.deserialize(p, ctxt);
+ }
+ /* Caller may want to get all integral values returned as {@link java.math.BigInteger},
+ * or {@link java.lang.Long} for consistency
+ */
+ if (ctxt.hasSomeOfFeatures(F_MASK_INT_COERCIONS)) {
+ return _coerceIntegral(p, ctxt);
+ }
+ return p.getNumberValue(); // should be optimal, whatever it is
+
+ case JsonTokenId.ID_NUMBER_FLOAT:
+ if (_numberDeserializer != null) {
+ return _numberDeserializer.deserialize(p, ctxt);
+ }
+ /* [JACKSON-72]: need to allow overriding the behavior regarding
+ * which type to use
+ */
+ if (ctxt.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
+ return p.getDecimalValue();
+ }
+ return p.getDoubleValue();
+
+ case JsonTokenId.ID_TRUE:
+ return Boolean.TRUE;
+ case JsonTokenId.ID_FALSE:
+ return Boolean.FALSE;
+
+ case JsonTokenId.ID_NULL: // should not get this but...
+ return null;
+
+// case JsonTokenId.ID_END_ARRAY: // invalid
+ default:
+ }
+ throw ctxt.mappingException(Object.class);
+ }
+
+// Test Case
+[/INST]
+ public void testNestedUntyped989() throws IOException
+ {
+ Untyped989 pojo;
+ ObjectReader r = MAPPER.readerFor(Untyped989.class);
+
+ pojo = r.readValue(""[]"");
+ assertTrue(pojo.value instanceof List);
+ pojo = r.readValue(""[{}]"");
+ assertTrue(pojo.value instanceof List);
+
+ pojo = r.readValue(""{}"");
+ assertTrue(pojo.value instanceof Map);
+ pojo = r.readValue(""{\""a\"":[]}"");
+ assertTrue(pojo.value instanceof Map);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ switch (p.getCurrentTokenId()) {
+ case JsonTokenId.ID_START_OBJECT:
+ {
+ JsonToken t = p.nextToken();
+ if (t == JsonToken.END_OBJECT) {
+ return new LinkedHashMap(2);
+ }
+ }
+ case JsonTokenId.ID_FIELD_NAME:
+ return mapObject(p, ctxt);
+ case JsonTokenId.ID_START_ARRAY:
+ {
+ JsonToken t = p.nextToken();
+ if (t == JsonToken.END_ARRAY) { // and empty one too
+ if (ctxt.isEnabled(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY)) {
+ return NO_OBJECTS;
+ }
+ return new ArrayList(2);
+ }
+ }
+ if (ctxt.isEnabled(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY)) {
+ return mapArrayToArray(p, ctxt);
+ }
+ return mapArray(p, ctxt);
+ case JsonTokenId.ID_EMBEDDED_OBJECT:
+ return p.getEmbeddedObject();
+ case JsonTokenId.ID_STRING:
+ return p.getText();
+
+ case JsonTokenId.ID_NUMBER_INT:
+ if (ctxt.hasSomeOfFeatures(F_MASK_INT_COERCIONS)) {
+ return _coerceIntegral(p, ctxt);
+ }
+ return p.getNumberValue(); // should be optimal, whatever it is
+
+ case JsonTokenId.ID_NUMBER_FLOAT:
+ if (ctxt.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
+ return p.getDecimalValue();
+ }
+ return Double.valueOf(p.getDoubleValue());
+
+ case JsonTokenId.ID_TRUE:
+ return Boolean.TRUE;
+ case JsonTokenId.ID_FALSE:
+ return Boolean.FALSE;
+
+ case JsonTokenId.ID_NULL: // should not get this but...
+ return null;
+
+ // 28-Oct-2015, tatu: [databind#989] We may also be given END_OBJECT (similar to FIELD_NAME),
+ // if caller has advanced to the first token of Object, but for empty Object
+
+ //case JsonTokenId.ID_END_ARRAY: // invalid
+ default:
+ throw ctxt.mappingException(Object.class);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testNestedUntyped989() throws IOException
+ {
+ Untyped989 pojo;
+ ObjectReader r = MAPPER.readerFor(Untyped989.class);
+
+ pojo = r.readValue(""[]"");
+ assertTrue(pojo.value instanceof List);
+ pojo = r.readValue(""[{}]"");
+ assertTrue(pojo.value instanceof List);
+
+ pojo = r.readValue(""{}"");
+ assertTrue(pojo.value instanceof Map);
+ pojo = r.readValue(""{\""a\"":[]}"");
+ assertTrue(pojo.value instanceof Map);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public PropertyName findNameForSerialization(Annotated a)
+ {
+ String name = null;
+
+ JsonGetter jg = _findAnnotation(a, JsonGetter.class);
+ if (jg != null) {
+ name = jg.value();
+ } else {
+ JsonProperty pann = _findAnnotation(a, JsonProperty.class);
+ if (pann != null) {
+ name = pann.value();
+ /* 22-Apr-2014, tatu: Should figure out a better way to do this, but
+ * it's actually bit tricky to do it more efficiently (meta-annotations
+ * add more lookups; AnnotationMap costs etc)
+ */
+ } else if (_hasAnnotation(a, JsonSerialize.class)
+ || _hasAnnotation(a, JsonView.class)
+ || _hasAnnotation(a, JsonRawValue.class)) {
+ name = """";
+ } else {
+ return null;
+ }
+ }
+ return PropertyName.construct(name);
+ }
+
+// Test Case
+[/INST]
+ public void testUnwrappedAsPropertyIndicator() throws Exception
+ {
+ Inner inner = new Inner();
+ inner.animal = ""Zebra"";
+
+ Outer outer = new Outer();
+ outer.inner = inner;
+
+ String actual = MAPPER.writeValueAsString(outer);
+
+ assertTrue(actual.contains(""animal""));
+ assertTrue(actual.contains(""Zebra""));
+ assertFalse(actual.contains(""inner""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
+ {
+ if (_isInt) {
+ visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);
+ } else {
+ Class> h = handledType();
+ if (h == BigDecimal.class) {
+ visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);
+ } else {
+ // otherwise bit unclear what to call... but let's try:
+ /*JsonNumberFormatVisitor v2 =*/ visitor.expectNumberFormat(typeHint);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSimpleNumbers() throws Exception
+ {
+ final StringBuilder sb = new StringBuilder();
+
+ MAPPER.acceptJsonFormatVisitor(Numbers.class,
+ new JsonFormatVisitorWrapper.Base() {
+ @Override
+ public JsonObjectFormatVisitor expectObjectFormat(final JavaType type) {
+ return new JsonObjectFormatVisitor.Base(getProvider()) {
+ @Override
+ public void optionalProperty(BeanProperty prop) throws JsonMappingException {
+ sb.append(""[optProp "").append(prop.getName()).append(""("");
+ JsonSerializer ser = null;
+ if (prop instanceof BeanPropertyWriter) {
+ BeanPropertyWriter bpw = (BeanPropertyWriter) prop;
+ ser = bpw.getSerializer();
+ }
+ final SerializerProvider prov = getProvider();
+ if (ser == null) {
+ ser = prov.findValueSerializer(prop.getType(), prop);
+ }
+ ser.acceptJsonFormatVisitor(new JsonFormatVisitorWrapper.Base() {
+ @Override
+ public JsonNumberFormatVisitor expectNumberFormat(
+ JavaType type) throws JsonMappingException {
+ return new JsonNumberFormatVisitor() {
+ @Override
+ public void format(JsonValueFormat format) {
+ sb.append(""[numberFormat="").append(format).append(""]"");
+ }
+
+ @Override
+ public void enumTypes(Set enums) { }
+
+ @Override
+ public void numberType(NumberType numberType) {
+ sb.append(""[numberType="").append(numberType).append(""]"");
+ }
+ };
+ }
+
+ @Override
+ public JsonIntegerFormatVisitor expectIntegerFormat(JavaType type) throws JsonMappingException {
+ return new JsonIntegerFormatVisitor() {
+ @Override
+ public void format(JsonValueFormat format) {
+ sb.append(""[integerFormat="").append(format).append(""]"");
+ }
+
+ @Override
+ public void enumTypes(Set enums) { }
+
+ @Override
+ public void numberType(NumberType numberType) {
+ sb.append(""[numberType="").append(numberType).append(""]"");
+ }
+ };
+ }
+ }, prop.getType());
+
+ sb.append("")]"");
+ }
+ };
+ }
+ });
+ assertEquals(""[optProp dec([numberType=BIG_DECIMAL])][optProp bigInt([numberType=BIG_INTEGER])]"",
+ sb.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ // 02-Aug-2013, tatu: May need to use native type ids
+ if (p.canReadTypeId()) {
+ Object typeId = p.getTypeId();
+ if (typeId != null) {
+ return _deserializeWithNativeTypeId(p, ctxt, typeId);
+ }
+ }
+ // first, sanity checks
+ if (p.getCurrentToken() != JsonToken.START_OBJECT) {
+ throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT,
+ ""need JSON Object to contain As.WRAPPER_OBJECT type information for class ""+baseTypeName());
+ }
+ // should always get field name, but just in case...
+ if (p.nextToken() != JsonToken.FIELD_NAME) {
+ throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,
+ ""need JSON String that contains type id (for subtype of ""+baseTypeName()+"")"");
+ }
+ final String typeId = p.getText();
+ JsonDeserializer deser = _findDeserializer(ctxt, typeId);
+ p.nextToken();
+
+ // Minor complication: we may need to merge type id in?
+ if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) {
+ // but what if there's nowhere to add it in? Error? Or skip? For now, skip.
+ TokenBuffer tb = new TokenBuffer(null, false);
+ tb.writeStartObject(); // recreate START_OBJECT
+ tb.writeFieldName(_typePropertyName);
+ tb.writeString(typeId);
+ p = JsonParserSequence.createFlattened(tb.asParser(p), p);
+ p.nextToken();
+ }
+
+ Object value = deser.deserialize(p, ctxt);
+ // And then need the closing END_OBJECT
+ if (p.nextToken() != JsonToken.END_OBJECT) {
+ throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT,
+ ""expected closing END_OBJECT after type information and deserialized value"");
+ }
+ return value;
+ }
+
+// Test Case
+[/INST]
+ public void testSimple() throws Exception
+ {
+ Company comp = new Company();
+ comp.addComputer(new DesktopComputer(""computer-1"", ""Bangkok""));
+ comp.addComputer(new DesktopComputer(""computer-2"", ""Pattaya""));
+ comp.addComputer(new LaptopComputer(""computer-3"", ""Apple""));
+
+ final ObjectMapper mapper = new ObjectMapper();
+
+ String json = mapper.writerWithDefaultPrettyPrinter()
+ .writeValueAsString(comp);
+
+ System.out.println(""JSON: ""+json);
+
+ Company result = mapper.readValue(json, Company.class);
+ assertNotNull(result);
+ assertNotNull(result.computers);
+ assertEquals(3, result.computers.size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final static DateFormat _cloneFormat(DateFormat df, String format,
+ TimeZone tz, Locale loc, Boolean lenient)
+ {
+ if (!loc.equals(DEFAULT_LOCALE)) {
+ df = new SimpleDateFormat(format, loc);
+ df.setTimeZone((tz == null) ? DEFAULT_TIMEZONE : tz);
+ } else {
+ df = (DateFormat) df.clone();
+ if (tz != null) {
+ df.setTimeZone(tz);
+ }
+ }
+ return df;
+ }
+
+// Test Case
+[/INST]
+ public void testLenient() throws Exception
+ {
+ StdDateFormat f = StdDateFormat.instance;
+
+ // default should be lenient
+ assertTrue(f.isLenient());
+
+ StdDateFormat f2 = f.clone();
+ assertTrue(f2.isLenient());
+
+ f2.setLenient(false);
+ assertFalse(f2.isLenient());
+
+ f2.setLenient(true);
+ assertTrue(f2.isLenient());
+
+ // and for testing, finally, leave as non-lenient
+ f2.setLenient(false);
+ assertFalse(f2.isLenient());
+ StdDateFormat f3 = f2.clone();
+ assertFalse(f3.isLenient());
+
+ // first, legal dates are... legal
+ Date dt = f3.parse(""2015-11-30"");
+ assertNotNull(dt);
+
+ // but as importantly, when not lenient, do not allow
+ try {
+ f3.parse(""2015-11-32"");
+ fail(""Should not pass"");
+ } catch (ParseException e) {
+ verifyException(e, ""can not parse date"");
+ }
+
+ // ... yet, with lenient, do allow
+ f3.setLenient(true);
+ dt = f3.parse(""2015-11-32"");
+ assertNotNull(dt);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType _narrow(Class> subclass)
+ {
+ if (_class == subclass) {
+ return this;
+ }
+ // Should we check that there is a sub-class relationship?
+ // 15-Jan-2016, tatu: Almost yes, but there are some complications with
+ // placeholder values, so no.
+ /*
+ if (!_class.isAssignableFrom(subclass)) {
+ throw new IllegalArgumentException(""Class ""+subclass.getName()+"" not sub-type of ""
+ +_class.getName());
+ }
+ */
+ // 15-Jan-2015, tatu: Not correct; should really re-resolve...
+ return new SimpleType(subclass, _bindings, _superClass, _superInterfaces,
+ _valueHandler, _typeHandler, _asStatic);
+ }
+
+// Test Case
+[/INST]
+ public void testSimple() throws Exception {
+ final ObjectMapper mapper = new ObjectMapper();
+ final String json = aposToQuotes(""{'schemas': [{\n""
+ + "" 'name': 'FoodMart'\n""
+ + ""}]}\n"");
+ mapper.readValue(json, JsonRoot.class);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Deprecated // since 2.7
+ public static MapType construct(Class> rawType, JavaType keyT, JavaType valueT)
+ {
+ // First: may need to fabricate TypeBindings (needed for refining into
+ // concrete collection types, as per [databind#1102])
+ // !!! TODO: Wrong, does have supertypes
+ return new MapType(rawType, null, _bogusSuperClass(rawType), null,
+ keyT, valueT, null, null, false);
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""deprecation"")
+ public void testExplicitMapType() throws Exception
+ {
+ JavaType key = SimpleType.construct(String.class);
+ JavaType elem = SimpleType.construct(Point.class);
+ JavaType t = MapType.construct(Map.class, key, elem);
+
+ final String json = aposToQuotes(""{'x':{'x':3,'y':5}}"");
+
+ Map m = MAPPER.readValue(json, t);
+ assertNotNull(m);
+ assertEquals(1, m.size());
+ Object ob = m.values().iterator().next();
+ assertEquals(Point.class, ob.getClass());
+ Point p = (Point) ob;
+ assertEquals(3, p.x);
+ assertEquals(5, p.getY());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Deprecated // since 2.7
+ public static CollectionType construct(Class> rawType, JavaType elemT) {
+ // First: may need to fabricate TypeBindings (needed for refining into
+ // concrete collection types, as per [databind#1102])
+ return new CollectionType(rawType, null,
+ // !!! TODO: Wrong, does have supertypes, but:
+ _bogusSuperClass(rawType), null, elemT,
+ null, null, false);
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""deprecation"")
+ public void testExplicitMapType() throws Exception
+ {
+ JavaType key = SimpleType.construct(String.class);
+ JavaType elem = SimpleType.construct(Point.class);
+ JavaType t = MapType.construct(Map.class, key, elem);
+
+ final String json = aposToQuotes(""{'x':{'x':3,'y':5}}"");
+
+ Map m = MAPPER.readValue(json, t);
+ assertNotNull(m);
+ assertEquals(1, m.size());
+ Object ob = m.values().iterator().next();
+ assertEquals(Point.class, ob.getClass());
+ Point p = (Point) ob;
+ assertEquals(3, p.x);
+ assertEquals(5, p.getY());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Deprecated
+ public static SimpleType construct(Class> cls)
+ {
+ /* Let's add sanity checks, just to ensure no
+ * Map/Collection entries are constructed
+ */
+ if (Map.class.isAssignableFrom(cls)) {
+ throw new IllegalArgumentException(""Can not construct SimpleType for a Map (class: ""+cls.getName()+"")"");
+ }
+ if (Collection.class.isAssignableFrom(cls)) {
+ throw new IllegalArgumentException(""Can not construct SimpleType for a Collection (class: ""+cls.getName()+"")"");
+ }
+ // ... and while we are at it, not array types either
+ if (cls.isArray()) {
+ throw new IllegalArgumentException(""Can not construct SimpleType for an array (class: ""+cls.getName()+"")"");
+ }
+ return new SimpleType(cls, TypeBindings.emptyBindings(),
+ _bogusSuperClass(cls), null, null, null, false);
+ }
+
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""deprecation"")
+ public void testExplicitMapType() throws Exception
+ {
+ JavaType key = SimpleType.construct(String.class);
+ JavaType elem = SimpleType.construct(Point.class);
+ JavaType t = MapType.construct(Map.class, key, elem);
+
+ final String json = aposToQuotes(""{'x':{'x':3,'y':5}}"");
+
+ Map m = MAPPER.readValue(json, t);
+ assertNotNull(m);
+ assertEquals(1, m.size());
+ Object ob = m.values().iterator().next();
+ assertEquals(Point.class, ob.getClass());
+ Point p = (Point) ob;
+ assertEquals(3, p.x);
+ assertEquals(5, p.getY());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ // 29-Jan-2016, tatu: Simple skipping for all other tokens, but FIELD_NAME bit
+ // special unfortunately
+ p.skipChildren();
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testUnknownTypeIDRecovery() throws Exception
+ {
+ ObjectReader reader = MAPPER.readerFor(CallRecord.class).without(
+ DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
+ String json = aposToQuotes(""{'version':0.0,'application':'123',""
+ +""'item':{'type':'xevent','location':'location1'},""
+ +""'item2':{'type':'event','location':'location1'}}"");
+ // can't read item2 - which is valid
+ CallRecord r = reader.readValue(json);
+ assertNull(r.item);
+ assertNotNull(r.item2);
+
+ json = aposToQuotes(""{'item':{'type':'xevent','location':'location1'}, 'version':0.0,'application':'123'}"");
+ CallRecord r3 = reader.readValue(json);
+ assertNull(r3.item);
+ assertEquals(""123"", r3.application);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public String[] deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
+ {
+ // Ok: must point to START_ARRAY (or equivalent)
+ if (!jp.isExpectedStartArrayToken()) {
+ return handleNonArray(jp, ctxt);
+ }
+ if (_elementDeserializer != null) {
+ return _deserializeCustom(jp, ctxt);
+ }
+
+ final ObjectBuffer buffer = ctxt.leaseObjectBuffer();
+ Object[] chunk = buffer.resetAndStart();
+
+ int ix = 0;
+ JsonToken t;
+
+ while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
+ // Ok: no need to convert Strings, but must recognize nulls
+ String value;
+ if (t == JsonToken.VALUE_STRING) {
+ value = jp.getText();
+ } else if (t == JsonToken.VALUE_NULL) {
+ value = null; // since we have established that '_elementDeserializer == null' earlier
+ } else {
+ value = _parseString(jp, ctxt);
+ }
+ if (ix >= chunk.length) {
+ chunk = buffer.appendCompletedChunk(chunk);
+ ix = 0;
+ }
+ chunk[ix++] = value;
+ }
+ // note: pass String.class, not String[].class, as we need element type for error info
+ String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class);
+ ctxt.returnObjectBuffer(buffer);
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testArrayIndexForExceptions() throws Exception
+ {
+ final String OBJECTS_JSON = ""[ \""KEY2\"", false ]"";
+ try {
+ MAPPER.readValue(OBJECTS_JSON, Key[].class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Can not deserialize"");
+ List refs = e.getPath();
+ assertEquals(1, refs.size());
+ assertEquals(1, refs.get(0).getIndex());
+ }
+
+ try {
+ MAPPER.readValue(""[ \""xyz\"", { } ]"", String[].class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Can not deserialize"");
+ List refs = e.getPath();
+ assertEquals(1, refs.size());
+ assertEquals(1, refs.get(0).getIndex());
+ }
+
+ try {
+ MAPPER.readValue(""{\""keys\"":""+OBJECTS_JSON+""}"", KeyListBean.class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Can not deserialize"");
+ List refs = e.getPath();
+ assertEquals(2, refs.size());
+ // Bean has no index, but has name:
+ assertEquals(-1, refs.get(0).getIndex());
+ assertEquals(""keys"", refs.get(0).getFieldName());
+
+ // and for List, reverse:
+ assertEquals(1, refs.get(1).getIndex());
+ assertNull(refs.get(1).getFieldName());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final String[] _deserializeCustom(JsonParser jp, DeserializationContext ctxt) throws IOException
+ {
+ final ObjectBuffer buffer = ctxt.leaseObjectBuffer();
+ Object[] chunk = buffer.resetAndStart();
+ final JsonDeserializer deser = _elementDeserializer;
+
+ int ix = 0;
+ JsonToken t;
+
+ while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
+ // Ok: no need to convert Strings, but must recognize nulls
+ String value = (t == JsonToken.VALUE_NULL) ? deser.getNullValue() : deser.deserialize(jp, ctxt);
+ if (ix >= chunk.length) {
+ chunk = buffer.appendCompletedChunk(chunk);
+ ix = 0;
+ }
+ chunk[ix++] = value;
+ }
+ // note: pass String.class, not String[].class, as we need element type for error info
+ String[] result = buffer.completeAndClearBuffer(chunk, ix, String.class);
+ ctxt.returnObjectBuffer(buffer);
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testArrayIndexForExceptions() throws Exception
+ {
+ final String OBJECTS_JSON = ""[ \""KEY2\"", false ]"";
+ try {
+ MAPPER.readValue(OBJECTS_JSON, Key[].class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Can not deserialize"");
+ List refs = e.getPath();
+ assertEquals(1, refs.size());
+ assertEquals(1, refs.get(0).getIndex());
+ }
+
+ try {
+ MAPPER.readValue(""[ \""xyz\"", { } ]"", String[].class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Can not deserialize"");
+ List refs = e.getPath();
+ assertEquals(1, refs.size());
+ assertEquals(1, refs.get(0).getIndex());
+ }
+
+ try {
+ MAPPER.readValue(""{\""keys\"":""+OBJECTS_JSON+""}"", KeyListBean.class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Can not deserialize"");
+ List refs = e.getPath();
+ assertEquals(2, refs.size());
+ // Bean has no index, but has name:
+ assertEquals(-1, refs.get(0).getIndex());
+ assertEquals(""keys"", refs.get(0).getFieldName());
+
+ // and for List, reverse:
+ assertEquals(1, refs.get(1).getIndex());
+ assertNull(refs.get(1).getFieldName());
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testEmptyToNullCoercionForPrimitives() throws Exception {
+ _testEmptyToNullCoercion(int.class, Integer.valueOf(0));
+ _testEmptyToNullCoercion(long.class, Long.valueOf(0));
+ _testEmptyToNullCoercion(double.class, Double.valueOf(0.0));
+ _testEmptyToNullCoercion(float.class, Float.valueOf(0.0f));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Deprecated
+ public JavaType constructType(Type type, Class> contextClass) {
+ return constructType(type, constructType(contextClass));
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""deprecation"")
+ public void testDeprecatedTypeResolution() throws Exception
+ {
+ TypeFactory tf = MAPPER.getTypeFactory();
+
+ // first, with real (if irrelevant) context
+ JavaType t = tf.constructType(Point.class, getClass());
+ assertEquals(Point.class, t.getRawClass());
+
+ // and then missing context
+ JavaType t2 = tf.constructType(Point.class, (Class>) null);
+ assertEquals(Point.class, t2.getRawClass());
+
+ JavaType ctxt = tf.constructType(getClass());
+ JavaType t3 = tf.constructType(Point.class, ctxt);
+ assertEquals(Point.class, t3.getRawClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Deprecated
+ public JavaType constructType(Type type, JavaType contextType) {
+ return _fromAny(null, type, contextType.getBindings());
+ }
+
+
+// Test Case
+[/INST]
+ @SuppressWarnings(""deprecation"")
+ public void testDeprecatedTypeResolution() throws Exception
+ {
+ TypeFactory tf = MAPPER.getTypeFactory();
+
+ // first, with real (if irrelevant) context
+ JavaType t = tf.constructType(Point.class, getClass());
+ assertEquals(Point.class, t.getRawClass());
+
+ // and then missing context
+ JavaType t2 = tf.constructType(Point.class, (Class>) null);
+ assertEquals(Point.class, t2.getRawClass());
+
+ JavaType ctxt = tf.constructType(getClass());
+ JavaType t3 = tf.constructType(Point.class, ctxt);
+ assertEquals(Point.class, t3.getRawClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object _deserializeFromEmptyString() throws IOException {
+ // As per [databind#398], URI requires special handling
+ if (_kind == STD_URI) {
+ return URI.create("""");
+ }
+ // As per [databind#1123], Locale too
+ return super._deserializeFromEmptyString();
+ }
+
+// Test Case
+[/INST]
+ public void testLocale() throws IOException
+ {
+ assertEquals(new Locale(""en""), MAPPER.readValue(quote(""en""), Locale.class));
+ assertEquals(new Locale(""es"", ""ES""), MAPPER.readValue(quote(""es_ES""), Locale.class));
+ assertEquals(new Locale(""FI"", ""fi"", ""savo""),
+ MAPPER.readValue(quote(""fi_FI_savo""), Locale.class));
+ // [databind#1123]
+ Locale loc = MAPPER.readValue(quote(""""), Locale.class);
+ assertSame(Locale.ROOT, loc);
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object deserializeSetAndReturn(JsonParser p,
+ DeserializationContext ctxt, Object instance) throws IOException
+ {
+ Object id = _valueDeserializer.deserialize(p, ctxt);
+ /* 02-Apr-2015, tatu: Actually, as per [databind#742], let it be;
+ * missing or null id is needed for some cases, such as cases where id
+ * will be generated externally, at a later point, and is not available
+ * quite yet. Typical use case is with DB inserts.
+ */
+ // note: no null checks (unlike usually); deserializer should fail if one found
+ if (id == null) {
+ return null;
+ }
+ ReadableObjectId roid = ctxt.findObjectId(id, _objectIdReader.generator, _objectIdReader.resolver);
+ roid.bindItem(instance);
+ // also: may need to set a property value as well
+ SettableBeanProperty idProp = _objectIdReader.idProperty;
+ if (idProp != null) {
+ return idProp.setAndReturn(instance, id);
+ }
+ return instance;
+ }
+
+// Test Case
+[/INST]
+ public void testNullStringPropertyId() throws Exception
+ {
+ IdentifiableStringId value = MAPPER.readValue
+ (aposToQuotes(""{'value':3, 'next':null, 'id':null}""), IdentifiableStringId.class);
+ assertNotNull(value);
+ assertEquals(3, value.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType _narrow(Class> subclass)
+ {
+ if (_class == subclass) {
+ return this;
+ }
+ // Should we check that there is a sub-class relationship?
+ // 15-Jan-2016, tatu: Almost yes, but there are some complications with
+ // placeholder values (`Void`, `NoClass`), so can not quite do yet.
+ // TODO: fix in 2.8
+ /*
+ throw new IllegalArgumentException(""Class ""+subclass.getName()+"" not sub-type of ""
+ +_class.getName());
+ */
+ return new SimpleType(subclass, _bindings, this, _superInterfaces,
+ _valueHandler, _typeHandler, _asStatic);
+ // Otherwise, stitch together the hierarchy. First, super-class
+ // if not found, try a super-interface
+ // should not get here but...
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1125WithDefault() throws Exception
+ {
+ Issue1125Wrapper result = MAPPER.readValue(aposToQuotes(""{'value':{'a':3,'def':9,'b':5}}""),
+ Issue1125Wrapper.class);
+ assertNotNull(result.value);
+ assertEquals(Default1125.class, result.value.getClass());
+ Default1125 impl = (Default1125) result.value;
+ assertEquals(3, impl.a);
+ assertEquals(5, impl.b);
+ assertEquals(9, impl.def);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonSerializer> createContextual(SerializerProvider serializers,
+ BeanProperty property) throws JsonMappingException
+ {
+ if (property != null) {
+ JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember());
+ if (format != null) {
+
+ // Simple case first: serialize as numeric timestamp?
+ JsonFormat.Shape shape = format.getShape();
+ if (shape.isNumeric()) {
+ return withFormat(Boolean.TRUE, null);
+ }
+
+ if (format.getShape() == JsonFormat.Shape.STRING) {
+ TimeZone tz = format.getTimeZone();
+ final String pattern = format.hasPattern()
+ ? format.getPattern()
+ : StdDateFormat.DATE_FORMAT_STR_ISO8601;
+ final Locale loc = format.hasLocale()
+ ? format.getLocale()
+ : serializers.getLocale();
+ SimpleDateFormat df = new SimpleDateFormat(pattern, loc);
+ if (tz == null) {
+ tz = serializers.getTimeZone();
+ }
+ df.setTimeZone(tz);
+ return withFormat(Boolean.FALSE, df);
+ }
+ }
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testDateDefaultShape() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ // No @JsonFormat => default to user config
+ mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ String json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
+ assertEquals(aposToQuotes(""{'date':0}""), json);
+ mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01T00:00:00.000+0000'}""), json);
+
+ // Empty @JsonFormat => default to user config
+ mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
+ assertEquals(aposToQuotes(""{'date':0}""), json);
+ mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01T00:00:00.000+0000'}""), json);
+
+ // @JsonFormat with Shape.ANY and pattern => STRING shape, regardless of user config
+ mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01'}""), json);
+ mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01'}""), json);
+
+ // @JsonFormat with Shape.ANY and locale => STRING shape, regardless of user config
+ mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01T00:00:00.000+0000'}""), json);
+ mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01T00:00:00.000+0000'}""), json);
+
+ // @JsonFormat with Shape.ANY and timezone => STRING shape, regardless of user config
+ mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01T01:00:00.000+0100'}""), json);
+ mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01T01:00:00.000+0100'}""), json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public StringBuilder getGenericSignature(StringBuilder sb)
+ {
+ _classSignature(_class, sb, false);
+ sb.append('<');
+ sb = _referencedType.getGenericSignature(sb);
+ sb.append(';');
+ return sb;
+ }
+
+// Test Case
+[/INST]
+ public void testGenericSignature1195() throws Exception
+ {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ Method m;
+ JavaType t;
+
+ m = Generic1195.class.getMethod(""getList"");
+ t = tf.constructType(m.getGenericReturnType());
+ assertEquals(""Ljava/util/List;"", t.getGenericSignature());
+
+ m = Generic1195.class.getMethod(""getMap"");
+ t = tf.constructType(m.getGenericReturnType());
+ assertEquals(""Ljava/util/Map;"",
+ t.getGenericSignature());
+
+ m = Generic1195.class.getMethod(""getGeneric"");
+ t = tf.constructType(m.getGenericReturnType());
+ assertEquals(""Ljava/util/concurrent/atomic/AtomicReference;"", t.getGenericSignature());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JavaType refineSerializationType(final MapperConfig> config,
+ final Annotated a, final JavaType baseType) throws JsonMappingException
+ {
+ JavaType type = baseType;
+ final TypeFactory tf = config.getTypeFactory();
+
+ // 10-Oct-2015, tatu: For 2.7, we'll need to delegate back to
+ // now-deprecated secondary methods; this because while
+ // direct sub-class not yet retrofitted may only override
+ // those methods. With 2.8 or later we may consider removal
+ // of these methods
+
+
+ // Ok: start by refining the main type itself; common to all types
+ Class> serClass = findSerializationType(a);
+ if (serClass != null) {
+ if (type.hasRawClass(serClass)) {
+ // 30-Nov-2015, tatu: As per [databind#1023], need to allow forcing of
+ // static typing this way
+ type = type.withStaticTyping();
+ } else {
+ try {
+ // 11-Oct-2015, tatu: For deser, we call `TypeFactory.constructSpecializedType()`,
+ // may be needed here too in future?
+ type = tf.constructGeneralizedType(type, serClass);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to widen type %s with annotation (value %s), from '%s': %s"",
+ type, serClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ }
+ // Then further processing for container types
+
+ // First, key type (for Maps, Map-like types):
+ if (type.isMapLikeType()) {
+ JavaType keyType = type.getKeyType();
+ Class> keyClass = findSerializationKeyType(a, keyType);
+ if (keyClass != null) {
+ if (keyType.hasRawClass(keyClass)) {
+ keyType = keyType.withStaticTyping();
+ } else {
+ Class> currRaw = keyType.getRawClass();
+ try {
+ // 19-May-2016, tatu: As per [databind#1231], [databind#1178] may need to actually
+ // specialize (narrow) type sometimes, even if more commonly opposite
+ // is needed.
+ if (keyClass.isAssignableFrom(currRaw)) { // common case
+ keyType = tf.constructGeneralizedType(keyType, keyClass);
+ } else if (currRaw.isAssignableFrom(keyClass)) { // specialization, ok as well
+ keyType = tf.constructSpecializedType(keyType, keyClass);
+ } else {
+ throw new JsonMappingException(null,
+ String.format(""Can not refine serialization key type %s into %s; types not related"",
+ keyType, keyClass.getName()));
+ }
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s"",
+ type, keyClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ type = ((MapLikeType) type).withKeyType(keyType);
+ }
+ }
+
+ JavaType contentType = type.getContentType();
+ if (contentType != null) { // collection[like], map[like], array, reference
+ // And then value types for all containers:
+ Class> contentClass = findSerializationContentType(a, contentType);
+ if (contentClass != null) {
+ if (contentType.hasRawClass(contentClass)) {
+ contentType = contentType.withStaticTyping();
+ } else {
+ // 03-Apr-2016, tatu: As per [databind#1178], may need to actually
+ // specialize (narrow) type sometimes, even if more commonly opposite
+ // is needed.
+ Class> currRaw = contentType.getRawClass();
+ try {
+ if (contentClass.isAssignableFrom(currRaw)) { // common case
+ contentType = tf.constructGeneralizedType(contentType, contentClass);
+ } else if (currRaw.isAssignableFrom(contentClass)) { // specialization, ok as well
+ contentType = tf.constructSpecializedType(contentType, contentClass);
+ } else {
+ throw new JsonMappingException(null,
+ String.format(""Can not refine serialization content type %s into %s; types not related"",
+ contentType, contentClass.getName()));
+ }
+ } catch (IllegalArgumentException iae) { // shouldn't really happen
+ throw new JsonMappingException(null,
+ String.format(""Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s"",
+ type, contentClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ type = type.withContentType(contentType);
+ }
+ }
+ return type;
+ }
+
+// Test Case
+[/INST]
+ public void testBrokenAnnotation() throws Exception
+ {
+ try {
+ serializeAsString(MAPPER, new BrokenClass());
+ } catch (Exception e) {
+ verifyException(e, ""types not related"");
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public VisibilityChecker> getDefaultVisibilityChecker()
+ {
+ VisibilityChecker> vchecker = super.getDefaultVisibilityChecker();
+ if (!isEnabled(MapperFeature.AUTO_DETECT_SETTERS)) {
+ vchecker = vchecker.withSetterVisibility(Visibility.NONE);
+ }
+ if (!isEnabled(MapperFeature.AUTO_DETECT_CREATORS)) {
+ vchecker = vchecker.withCreatorVisibility(Visibility.NONE);
+ }
+ if (!isEnabled(MapperFeature.AUTO_DETECT_FIELDS)) {
+ vchecker = vchecker.withFieldVisibility(Visibility.NONE);
+ }
+ return vchecker;
+ }
+
+// Test Case
+[/INST]
+ public void testVisibilityFeatures() throws Exception
+ {
+ ObjectMapper om = new ObjectMapper();
+ // Only use explicitly specified values to be serialized/deserialized (i.e., JSONProperty).
+ om.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
+ om.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
+ om.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
+ om.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
+ om.configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);
+ om.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
+ om.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
+ om.configure(MapperFeature.USE_ANNOTATIONS, true);
+
+ JavaType javaType = om.getTypeFactory().constructType(TCls.class);
+ BeanDescription desc = (BeanDescription) om.getSerializationConfig().introspect(javaType);
+ List props = desc.findProperties();
+ if (props.size() != 1) {
+ fail(""Should find 1 property, not ""+props.size()+""; properties = ""+props);
+ }
+ }
+}
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public VisibilityChecker> getDefaultVisibilityChecker()
+ {
+ VisibilityChecker> vchecker = super.getDefaultVisibilityChecker();
+ // then global overrides (disabling)
+ if (!isEnabled(MapperFeature.AUTO_DETECT_GETTERS)) {
+ vchecker = vchecker.withGetterVisibility(Visibility.NONE);
+ }
+ if (!isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)) {
+ vchecker = vchecker.withIsGetterVisibility(Visibility.NONE);
+ }
+ if (!isEnabled(MapperFeature.AUTO_DETECT_FIELDS)) {
+ vchecker = vchecker.withFieldVisibility(Visibility.NONE);
+ }
+ return vchecker;
+ }
+
+// Test Case
+[/INST]
+ public void testVisibilityFeatures() throws Exception
+ {
+ ObjectMapper om = new ObjectMapper();
+ // Only use explicitly specified values to be serialized/deserialized (i.e., JSONProperty).
+ om.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
+ om.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
+ om.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
+ om.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
+ om.configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);
+ om.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
+ om.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
+ om.configure(MapperFeature.USE_ANNOTATIONS, true);
+
+ JavaType javaType = om.getTypeFactory().constructType(TCls.class);
+ BeanDescription desc = (BeanDescription) om.getSerializationConfig().introspect(javaType);
+ List props = desc.findProperties();
+ if (props.size() != 1) {
+ fail(""Should find 1 property, not ""+props.size()+""; properties = ""+props);
+ }
+ }
+}
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object generateId(Object forPojo) {
+ // 04-Jun-2016, tatu: As per [databind#1255], need to consider possibility of
+ // id being generated for ""alwaysAsId"", but not being written as POJO; regardless,
+ // need to use existing id if there is one:
+ id = generator.generateId(forPojo);
+ return id;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1255() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ Foo mo = new Foo();
+ mo.bar1 = new Bar();
+ mo.bar2 = mo.bar1;
+
+ String json = mapper.writeValueAsString(mo);
+
+ Foo result = mapper.readValue(json, Foo.class);
+ assertNotNull(result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _addMethodMixIns(Class> targetClass, AnnotatedMethodMap methods,
+ Class> mixInCls, AnnotatedMethodMap mixIns)
+ {
+ List> parents = new ArrayList>();
+ parents.add(mixInCls);
+ ClassUtil.findSuperTypes(mixInCls, targetClass, parents);
+ for (Class> mixin : parents) {
+ for (Method m : mixin.getDeclaredMethods()) {
+ if (!_isIncludableMemberMethod(m)) {
+ continue;
+ }
+ AnnotatedMethod am = methods.find(m);
+ /* Do we already have a method to augment (from sub-class
+ * that will mask this mixIn)? If so, add if visible
+ * without masking (no such annotation)
+ */
+ if (am != null) {
+ _addMixUnders(m, am);
+ /* Otherwise will have precedence, but must wait
+ * until we find the real method (mixIn methods are
+ * just placeholder, can't be called)
+ */
+ } else {
+ // Well, or, as per [Issue#515], multi-level merge within mixins...
+ mixIns.add(_constructMethod(m));
+ }
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDisappearingMixins515() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS)
+ .disable(MapperFeature.AUTO_DETECT_FIELDS)
+ .disable(MapperFeature.AUTO_DETECT_GETTERS)
+ .disable(MapperFeature.AUTO_DETECT_IS_GETTERS)
+ .disable(MapperFeature.INFER_PROPERTY_MUTATORS);
+ SimpleModule module = new SimpleModule(""Test"");
+ module.setMixInAnnotation(Person.class, PersonMixin.class);
+ mapper.registerModule(module);
+
+ assertEquals(""{\""city\"":\""Seattle\""}"", mapper.writeValueAsString(new PersonImpl()));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ @SuppressWarnings(""resource"")
+ protected Object _deserializeUsingPropertyBased(final JsonParser p, final DeserializationContext ctxt)
+ throws IOException
+ {
+ final PropertyBasedCreator creator = _propertyBasedCreator;
+ PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
+
+ TokenBuffer unknown = null;
+
+ JsonToken t = p.getCurrentToken();
+ for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
+ String propName = p.getCurrentName();
+ p.nextToken(); // to point to value
+ // creator property?
+ SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
+ if (creatorProp != null) {
+ // Last creator property to set?
+ if (buffer.assignParameter(creatorProp,
+ _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
+ p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
+ Object bean;
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ bean = wrapInstantiationProblem(e, ctxt);
+ }
+ if (bean == null) {
+ return ctxt.handleInstantiationProblem(handledType(), null,
+ _creatorReturnedNullException());
+ }
+ // [databind#631]: Assign current value, to be accessible by custom serializers
+ p.setCurrentValue(bean);
+
+ // polymorphic?
+ if (bean.getClass() != _beanType.getRawClass()) {
+ return handlePolymorphic(p, ctxt, bean, unknown);
+ }
+ if (unknown != null) { // nope, just extra unknown stuff...
+ bean = handleUnknownProperties(ctxt, bean, unknown);
+ }
+ // or just clean?
+ return deserialize(p, ctxt, bean);
+ }
+ continue;
+ }
+ // Object Id property?
+ if (buffer.readIdProperty(propName)) {
+ continue;
+ }
+ // regular property? needs buffering
+ SettableBeanProperty prop = _beanProperties.find(propName);
+ if (prop != null) {
+ buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));
+ // 14-Jun-2016, tatu: As per [databind#1261], looks like we need additional
+ // handling of forward references here. Not exactly sure why existing
+ // facilities did not cover, but this does appear to solve the problem
+ continue;
+ }
+ // Things marked as ignorable should not be passed to any setter
+ if (_ignorableProps != null && _ignorableProps.contains(propName)) {
+ handleIgnoredProperty(p, ctxt, handledType(), propName);
+ continue;
+ }
+ // ""any property""?
+ if (_anySetter != null) {
+ try {
+ buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
+ } catch (Exception e) {
+ wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
+ }
+ continue;
+ }
+ // Ok then, let's collect the whole field; name and value
+ if (unknown == null) {
+ unknown = new TokenBuffer(p, ctxt);
+ }
+ unknown.writeFieldName(propName);
+ unknown.copyCurrentStructure(p);
+ }
+
+ // We hit END_OBJECT, so:
+ Object bean;
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ wrapInstantiationProblem(e, ctxt);
+ bean = null; // never gets here
+ }
+ if (unknown != null) {
+ // polymorphic?
+ if (bean.getClass() != _beanType.getRawClass()) {
+ return handlePolymorphic(null, ctxt, bean, unknown);
+ }
+ // no, just some extra unknown properties
+ return handleUnknownProperties(ctxt, bean, unknown);
+ }
+ return bean;
+ }
+
+// Test Case
+[/INST]
+ public void testObjectIds1261() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+ mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
+
+ Answer initialAnswer = createInitialAnswer();
+ String initialAnswerString = mapper.writeValueAsString(initialAnswer);
+// System.out.println(""Initial answer:\n""+initialAnswerString);
+ JsonNode tree = mapper.readTree(initialAnswerString);
+ Answer deserializedAnswer = mapper.readValue(initialAnswerString,
+ Answer.class);
+ String reserializedAnswerString = mapper
+ .writeValueAsString(deserializedAnswer);
+ JsonNode newTree = mapper.readTree(reserializedAnswerString);
+ if (!tree.equals(newTree)) {
+ fail(""Original and recovered Json are different. Recovered = \n""
+ + reserializedAnswerString + ""\n"");
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,
+ String typeId) throws IOException
+ {
+ JsonDeserializer deser = _deserializers.get(typeId);
+ if (deser == null) {
+ /* As per [Databind#305], need to provide contextual info. But for
+ * backwards compatibility, let's start by only supporting this
+ * for base class, not via interface. Later on we can add this
+ * to the interface, assuming deprecation at base class helps.
+ */
+ JavaType type = _idResolver.typeFromId(ctxt, typeId);
+ if (type == null) {
+ // As per [JACKSON-614], use the default impl if no type id available:
+ deser = _findDefaultImplDeserializer(ctxt);
+ if (deser == null) {
+ // 10-May-2016, tatu: We may get some help...
+ JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);
+ if (actual == null) { // what should this be taken to mean?
+ // TODO: try to figure out something better
+ return null;
+ }
+ // ... would this actually work?
+ deser = ctxt.findContextualValueDeserializer(actual, _property);
+ }
+ } else {
+ /* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
+ * we actually now need to explicitly narrow from base type (which may have parameterization)
+ * using raw type.
+ *
+ * One complication, though; can not change 'type class' (simple type to container); otherwise
+ * we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
+ * type in process (getting SimpleType of Map.class which will not work as expected)
+ */
+ if ((_baseType != null)
+ && _baseType.getClass() == type.getClass()) {
+ /* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
+ * but it appears to check that JavaType impl class is the same which is
+ * important for some reason?
+ * Disabling the check will break 2 Enum-related tests.
+ */
+ // 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
+ // generic type with custom type resolvers. If so, should try to retain them.
+ // Whether this is sufficient to avoid problems remains to be seen, but for
+ // now it should improve things.
+ type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());
+ }
+ deser = ctxt.findContextualValueDeserializer(type, _property);
+ }
+ _deserializers.put(typeId, deser);
+ }
+ return deser;
+ }
+
+// Test Case
+[/INST]
+ public void testPolymorphicTypeViaCustom() throws Exception {
+ Base1270 req = new Base1270();
+ Poly1 o = new Poly1();
+ o.val = ""optionValue"";
+ req.options = o;
+ req.val = ""some value"";
+ Top1270 top = new Top1270();
+ top.b = req;
+ String json = MAPPER.writeValueAsString(top);
+ JsonNode tree = MAPPER.readTree(json);
+ assertNotNull(tree.get(""b""));
+ assertNotNull(tree.get(""b"").get(""options""));
+ assertNotNull(tree.get(""b"").get(""options"").get(""val""));
+
+ // Can we reverse the process? I have some doubts
+ Top1270 itemRead = MAPPER.readValue(json, Top1270.class);
+ assertNotNull(itemRead);
+ assertNotNull(itemRead.b);
+ }
+}
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void resolve(DeserializationContext ctxt)
+ throws JsonMappingException
+ {
+ ExternalTypeHandler.Builder extTypes = null;
+ // if ValueInstantiator can use ""creator"" approach, need to resolve it here...
+ SettableBeanProperty[] creatorProps;
+
+ if (_valueInstantiator.canCreateFromObjectWith()) {
+ creatorProps = _valueInstantiator.getFromObjectArguments(ctxt.getConfig());
+
+ // 21-Jun-2015, tatu: This resolution was duplicated later on and seems like
+ // it really should be only done at a later point. So commented out in 2.8.
+ // However, just in case there was a reason for it, leaving commented out
+ // here instead of immediately removing.
+
+ /*
+ // also: need to try to resolve 'external' type ids...
+ for (SettableBeanProperty prop : creatorProps) {
+ if (prop.hasValueTypeDeserializer()) {
+ TypeDeserializer typeDeser = prop.getValueTypeDeserializer();
+ if (typeDeser.getTypeInclusion() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
+ if (extTypes == null) {
+ extTypes = new ExternalTypeHandler.Builder();
+ }
+ extTypes.addExternal(prop, typeDeser);
+ }
+ }
+ }
+ */
+ } else {
+ creatorProps = null;
+ }
+
+ UnwrappedPropertyHandler unwrapped = null;
+
+ for (SettableBeanProperty origProp : _beanProperties) {
+ SettableBeanProperty prop = origProp;
+
+ // May already have deserializer from annotations, if so, skip:
+ if (!prop.hasValueDeserializer()) {
+ // [databind#125]: allow use of converters
+ JsonDeserializer> deser = findConvertingDeserializer(ctxt, prop);
+ if (deser == null) {
+ deser = findDeserializer(ctxt, prop.getType(), prop);
+ }
+ prop = prop.withValueDeserializer(deser);
+ } else { // may need contextual version
+ JsonDeserializer deser = prop.getValueDeserializer();
+ /* Important! This is the only place where actually handle ""primary""
+ * property deserializers -- call is different from other places.
+ */
+ JsonDeserializer> cd = ctxt.handlePrimaryContextualization(deser, prop,
+ prop.getType());
+ if (cd != deser) {
+ prop = prop.withValueDeserializer(cd);
+ }
+ }
+
+ // Need to link managed references with matching back references
+ prop = _resolveManagedReferenceProperty(ctxt, prop);
+
+ // [databind#351[: need to wrap properties that require object id resolution.
+ if (!(prop instanceof ManagedReferenceProperty)) {
+ prop = _resolvedObjectIdProperty(ctxt, prop);
+ }
+ // Support unwrapped values (via @JsonUnwrapped)
+ SettableBeanProperty u = _resolveUnwrappedProperty(ctxt, prop);
+ if (u != null) {
+ prop = u;
+ if (unwrapped == null) {
+ unwrapped = new UnwrappedPropertyHandler();
+ }
+ unwrapped.addProperty(prop);
+ /* 12-Dec-2014, tatu: As per [databind#647], we will have problems if
+ * the original property is left in place. So let's remove it now.
+ */
+ _beanProperties.remove(prop);
+ continue;
+ }
+ // non-static inner classes too:
+ prop = _resolveInnerClassValuedProperty(ctxt, prop);
+ if (prop != origProp) {
+ _beanProperties.replace(prop);
+ // [databind#795]: Make sure PropertyBasedCreator's properties stay in sync
+ if (creatorProps != null) {
+ // 18-May-2015, tatu: _Should_ start with consistent set. But can we really
+ // fully count on this? May need to revisit in future; seems to hold for now.
+ for (int i = 0, len = creatorProps.length; i < len; ++i) {
+ if (creatorProps[i] == origProp) {
+ creatorProps[i] = prop;
+ break;
+ }
+ // ... as per above, it is possible we'd need to add this as fallback
+ // if (but only if) identity check fails?
+ /*
+ if (creatorProps[i].getName().equals(prop.getName())) {
+ creatorProps[i] = prop;
+ break;
+ }
+ */
+ }
+ }
+ }
+ // one more thing: if this property uses ""external property"" type inclusion,
+ // it needs different handling altogether
+ if (prop.hasValueTypeDeserializer()) {
+ TypeDeserializer typeDeser = prop.getValueTypeDeserializer();
+ if (typeDeser.getTypeInclusion() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
+ if (extTypes == null) {
+ extTypes = new ExternalTypeHandler.Builder();
+ }
+ extTypes.addExternal(prop, typeDeser);
+ // In fact, remove from list of known properties to simplify later handling
+ _beanProperties.remove(prop);
+ continue;
+ }
+ }
+ }
+ // ""any setter"" may also need to be resolved now
+ if (_anySetter != null && !_anySetter.hasValueDeserializer()) {
+ _anySetter = _anySetter.withValueDeserializer(findDeserializer(ctxt,
+ _anySetter.getType(), _anySetter.getProperty()));
+ }
+ // as well as delegate-based constructor:
+ if (_valueInstantiator.canCreateUsingDelegate()) {
+ JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
+ if (delegateType == null) {
+ throw new IllegalArgumentException(""Invalid delegate-creator definition for ""+_beanType
+ +"": value instantiator (""+_valueInstantiator.getClass().getName()
+ +"") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'"");
+ }
+ _delegateDeserializer = _findDelegateDeserializer(ctxt, delegateType,
+ _valueInstantiator.getDelegateCreator());
+ }
+
+ // and array-delegate-based constructor:
+ if (_valueInstantiator.canCreateUsingArrayDelegate()) {
+ JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig());
+ if (delegateType == null) {
+ throw new IllegalArgumentException(""Invalid array-delegate-creator definition for ""+_beanType
+ +"": value instantiator (""+_valueInstantiator.getClass().getName()
+ +"") returned true for 'canCreateUsingArrayDelegate()', but null for 'getArrayDelegateType()'"");
+ }
+ _arrayDelegateDeserializer = _findDelegateDeserializer(ctxt, delegateType,
+ _valueInstantiator.getArrayDelegateCreator());
+ }
+
+ // And now that we know CreatorProperty instances are also resolved can finally create the creator:
+ if (creatorProps != null) {
+ _propertyBasedCreator = PropertyBasedCreator.construct(ctxt, _valueInstantiator, creatorProps);
+ }
+
+ if (extTypes != null) {
+ // 21-Jun-2016, tatu: related to [databind#999], may need to link type ids too,
+ // so need to pass collected properties
+ _externalTypeIdHandler = extTypes.build();
+ // we consider this non-standard, to offline handling
+ _nonStandardCreation = true;
+ }
+
+ _unwrappedPropertyHandler = unwrapped;
+ if (unwrapped != null) { // we consider this non-standard, to offline handling
+ _nonStandardCreation = true;
+ }
+
+ // may need to disable vanilla processing, if unwrapped handling was enabled...
+ _vanillaProcessing = _vanillaProcessing && !_nonStandardCreation;
+ }
+
+// Test Case
+[/INST]
+ public void testExternalTypeId() throws Exception
+ {
+ TypeReference> type = new TypeReference>() { };
+
+ Message> msg = MAPPER.readValue(aposToQuotes(""{ 'type':'foo', 'payload': {} }""), type);
+ assertNotNull(msg);
+ assertNotNull(msg.payload);
+ assertEquals(""foo"", msg.type);
+
+ // and then with different order
+ msg = MAPPER.readValue(aposToQuotes(""{'payload': {}, 'type':'foo' }""), type);
+ assertNotNull(msg);
+ assertNotNull(msg.payload);
+ assertEquals(""foo"", msg.type);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testExternalTypeId() throws Exception
+ {
+ TypeReference> type = new TypeReference>() { };
+
+ Message> msg = MAPPER.readValue(aposToQuotes(""{ 'type':'foo', 'payload': {} }""), type);
+ assertNotNull(msg);
+ assertNotNull(msg.payload);
+ assertEquals(""foo"", msg.type);
+
+ // and then with different order
+ msg = MAPPER.readValue(aposToQuotes(""{'payload': {}, 'type':'foo' }""), type);
+ assertNotNull(msg);
+ assertNotNull(msg.payload);
+ assertEquals(""foo"", msg.type);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JavaType constructSpecializedType(JavaType baseType, Class> subclass)
+ {
+ // simple optimization to avoid costly introspection if type-erased type does NOT differ
+ final Class> rawBase = baseType.getRawClass();
+ if (rawBase == subclass) {
+ return baseType;
+ }
+
+ JavaType newType;
+
+ // also: if we start from untyped, not much to save
+ do { // bogus loop to be able to break
+ if (rawBase == Object.class) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ if (!rawBase.isAssignableFrom(subclass)) {
+ throw new IllegalArgumentException(String.format(
+ ""Class %s not subtype of %s"", subclass.getName(), baseType));
+ }
+ // A few special cases where we can simplify handling:
+
+ // (1) Original target type has no generics -- just resolve subtype
+ if (baseType.getBindings().isEmpty()) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ // (2) A small set of ""well-known"" List/Map subtypes where can take a short-cut
+ if (baseType.isContainerType()) {
+ if (baseType.isMapLikeType()) {
+ if ((subclass == HashMap.class)
+ || (subclass == LinkedHashMap.class)
+ || (subclass == EnumMap.class)
+ || (subclass == TreeMap.class)) {
+ newType = _fromClass(null, subclass,
+ TypeBindings.create(subclass, baseType.getKeyType(), baseType.getContentType()));
+ break;
+ }
+ } else if (baseType.isCollectionLikeType()) {
+ if ((subclass == ArrayList.class)
+ || (subclass == LinkedList.class)
+ || (subclass == HashSet.class)
+ || (subclass == TreeSet.class)) {
+ newType = _fromClass(null, subclass,
+ TypeBindings.create(subclass, baseType.getContentType()));
+ break;
+ }
+ // 29-Oct-2015, tatu: One further shortcut: there are variants of `EnumSet`,
+ // but they are impl details and we basically do not care...
+ if (rawBase == EnumSet.class) {
+ return baseType;
+ }
+ }
+ }
+ // (3) Sub-class does not take type parameters -- just resolve subtype
+ int typeParamCount = subclass.getTypeParameters().length;
+ if (typeParamCount == 0) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+
+ // If not, we'll need to do more thorough forward+backwards resolution. Sigh.
+ // !!! TODO (as of 28-Jan-2016, at least)
+
+ // 20-Oct-2015, tatu: Container, Map-types somewhat special. There is
+ // a way to fully resolve and merge hierarchies; but that gets expensive
+ // so let's, for now, try to create close-enough approximation that
+ // is not 100% same, structurally, but has equivalent information for
+ // our specific neeeds.
+ // 29-Mar-2016, tatu: See [databind#1173] (and test `TypeResolverTest`)
+ // for a case where this code does get invoked: not ideal
+ // 29-Jun-2016, tatu: As to bindings, this works for [databind#1215], but
+ // not certain it would reliably work... but let's hope for best for now
+ if (baseType.isInterface()) {
+ newType = baseType.refine(subclass, TypeBindings.emptyBindings(), null, new JavaType[] { baseType });
+ } else {
+ newType = baseType.refine(subclass, TypeBindings.emptyBindings(), baseType, NO_TYPES);
+ }
+ // Only SimpleType returns null, but if so just resolve regularly
+ if (newType == null) {
+ TypeBindings tb = null;
+ if (baseType.containedTypeCount() == typeParamCount) {
+ if (typeParamCount == 1) {
+ tb = TypeBindings.create(subclass, baseType.containedType(0));
+ } else if (typeParamCount == 2) {
+ tb = TypeBindings.create(subclass, baseType.containedType(0),
+ baseType.containedType(1));
+ }
+ }
+ newType = _fromClass(null, subclass,
+ (tb == null) ? TypeBindings.emptyBindings() : tb);
+ }
+ } while (false);
+
+ // except possibly handlers
+// newType = newType.withHandlersFrom(baseType);
+ return newType;
+
+ // 20-Oct-2015, tatu: Old simplistic approach
+
+ /*
+ // Currently mostly SimpleType instances can become something else
+ if (baseType instanceof SimpleType) {
+ // and only if subclass is an array, Collection or Map
+ if (subclass.isArray()
+ || Map.class.isAssignableFrom(subclass)
+ || Collection.class.isAssignableFrom(subclass)) {
+ // need to assert type compatibility...
+ if (!baseType.getRawClass().isAssignableFrom(subclass)) {
+ throw new IllegalArgumentException(""Class ""+subclass.getClass().getName()+"" not subtype of ""+baseType);
+ }
+ // this _should_ work, right?
+ JavaType subtype = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ // one more thing: handlers to copy?
+ Object h = baseType.getValueHandler();
+ if (h != null) {
+ subtype = subtype.withValueHandler(h);
+ }
+ h = baseType.getTypeHandler();
+ if (h != null) {
+ subtype = subtype.withTypeHandler(h);
+ }
+ return subtype;
+ }
+ }
+ // But there is the need for special case for arrays too, it seems
+ if (baseType instanceof ArrayType) {
+ if (subclass.isArray()) {
+ // actually see if it might be a no-op first:
+ ArrayType at = (ArrayType) baseType;
+ Class> rawComp = subclass.getComponentType();
+ if (at.getContentType().getRawClass() == rawComp) {
+ return baseType;
+ }
+ JavaType componentType = _fromAny(null, rawComp, null);
+ return ((ArrayType) baseType).withComponentType(componentType);
+ }
+ }
+
+ // otherwise regular narrowing should work just fine
+ return baseType.narrowBy(subclass);
+ */
+ }
+
+// Test Case
+[/INST]
+ public void testMapRefinement() throws Exception
+ {
+ String ID1 = ""3a6383d4-8123-4c43-8b8d-7cedf3e59404"";
+ String ID2 = ""81c3d978-90c4-4b00-8da1-1c39ffcab02c"";
+ String json = aposToQuotes(
+""{'id':'""+ID1+""','items':[{'id':'""+ID2+""','property':'value'}]}"");
+
+ ObjectMapper m = new ObjectMapper();
+ Data data = m.readValue(json, Data.class);
+
+ assertEquals(ID1, data.id);
+ assertNotNull(data.items);
+ assertEquals(1, data.items.size());
+ Item value = data.items.get(ID2);
+ assertNotNull(value);
+ assertEquals(""value"", value.property);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType _fromClass(ClassStack context, Class> rawType, TypeBindings bindings)
+ {
+ // Very first thing: small set of core types we know well:
+ JavaType result = _findWellKnownSimple(rawType);
+ if (result != null) {
+ return result;
+ }
+ // Barring that, we may have recently constructed an instance
+ boolean cachable = (bindings == null) || bindings.isEmpty();
+ if (cachable) {
+ result = _typeCache.get(rawType);
+ if (result != null) {
+ return result;
+ }
+ }
+
+ // 15-Oct-2015, tatu: recursive reference?
+ if (context == null) {
+ context = new ClassStack(rawType);
+ } else {
+ ClassStack prev = context.find(rawType);
+ if (prev != null) {
+ // Self-reference: needs special handling, then...
+ ResolvedRecursiveType selfRef = new ResolvedRecursiveType(rawType, EMPTY_BINDINGS);
+ prev.addSelfReference(selfRef);
+ return selfRef;
+ }
+ // no, but need to update context to allow for proper cycle resolution
+ context = context.child(rawType);
+ }
+
+ // First: do we have an array type?
+ if (rawType.isArray()) {
+ result = ArrayType.construct(_fromAny(context, rawType.getComponentType(), bindings),
+ bindings);
+ } else {
+ // If not, need to proceed by first resolving parent type hierarchy
+
+ JavaType superClass;
+ JavaType[] superInterfaces;
+
+ if (rawType.isInterface()) {
+ superClass = null;
+ superInterfaces = _resolveSuperInterfaces(context, rawType, bindings);
+ } else {
+ // Note: even Enums can implement interfaces, so can not drop those
+ superClass = _resolveSuperClass(context, rawType, bindings);
+ superInterfaces = _resolveSuperInterfaces(context, rawType, bindings);
+ }
+
+ // 19-Oct-2015, tatu: Bit messy, but we need to 'fix' java.util.Properties here...
+ if (rawType == Properties.class) {
+ result = MapType.construct(rawType, bindings, superClass, superInterfaces,
+ CORE_TYPE_STRING, CORE_TYPE_STRING);
+ }
+ // And then check what flavor of type we got. Start by asking resolved
+ // super-type if refinement is all that is needed?
+ else if (superClass != null) {
+ result = superClass.refine(rawType, bindings, superClass, superInterfaces);
+ }
+ // if not, perhaps we are now resolving a well-known class or interface?
+ if (result == null) {
+ result = _fromWellKnownClass(context, rawType, bindings, superClass, superInterfaces);
+ if (result == null) {
+ result = _fromWellKnownInterface(context, rawType, bindings, superClass, superInterfaces);
+ if (result == null) {
+ // but if nothing else, ""simple"" class for now:
+ result = _newSimpleType(rawType, bindings, superClass, superInterfaces);
+ }
+ }
+ }
+ }
+ context.resolveSelfReferences(result);
+ if (cachable) {
+ _typeCache.putIfAbsent(rawType, result);
+ }
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testMapRefinement() throws Exception
+ {
+ String ID1 = ""3a6383d4-8123-4c43-8b8d-7cedf3e59404"";
+ String ID2 = ""81c3d978-90c4-4b00-8da1-1c39ffcab02c"";
+ String json = aposToQuotes(
+""{'id':'""+ID1+""','items':[{'id':'""+ID2+""','property':'value'}]}"");
+
+ ObjectMapper m = new ObjectMapper();
+ Data data = m.readValue(json, Data.class);
+
+ assertEquals(ID1, data.id);
+ assertNotNull(data.items);
+ assertEquals(1, data.items.size());
+ Item value = data.items.get(ID2);
+ assertNotNull(value);
+ assertEquals(""value"", value.property);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType _fromClass(ClassStack context, Class> rawType, TypeBindings bindings)
+ {
+ // Very first thing: small set of core types we know well:
+ JavaType result = _findWellKnownSimple(rawType);
+ if (result != null) {
+ return result;
+ }
+ // Barring that, we may have recently constructed an instance
+ boolean cachable = (bindings == null) || bindings.isEmpty();
+ if (cachable) {
+ result = _typeCache.get(rawType);
+ if (result != null) {
+ return result;
+ }
+ }
+
+ // 15-Oct-2015, tatu: recursive reference?
+ if (context == null) {
+ context = new ClassStack(rawType);
+ } else {
+ ClassStack prev = context.find(rawType);
+ if (prev != null) {
+ // Self-reference: needs special handling, then...
+ ResolvedRecursiveType selfRef = new ResolvedRecursiveType(rawType, EMPTY_BINDINGS);
+ prev.addSelfReference(selfRef);
+ return selfRef;
+ }
+ // no, but need to update context to allow for proper cycle resolution
+ context = context.child(rawType);
+ }
+
+ // First: do we have an array type?
+ if (rawType.isArray()) {
+ result = ArrayType.construct(_fromAny(context, rawType.getComponentType(), bindings),
+ bindings);
+ } else {
+ // If not, need to proceed by first resolving parent type hierarchy
+
+ JavaType superClass;
+ JavaType[] superInterfaces;
+
+ if (rawType.isInterface()) {
+ superClass = null;
+ superInterfaces = _resolveSuperInterfaces(context, rawType, bindings);
+ } else {
+ // Note: even Enums can implement interfaces, so can not drop those
+ superClass = _resolveSuperClass(context, rawType, bindings);
+ superInterfaces = _resolveSuperInterfaces(context, rawType, bindings);
+ }
+
+ // 19-Oct-2015, tatu: Bit messy, but we need to 'fix' java.util.Properties here...
+ if (rawType == Properties.class) {
+ result = MapType.construct(rawType, bindings, superClass, superInterfaces,
+ CORE_TYPE_STRING, CORE_TYPE_STRING);
+ }
+ // And then check what flavor of type we got. Start by asking resolved
+ // super-type if refinement is all that is needed?
+ else if (superClass != null) {
+ result = superClass.refine(rawType, bindings, superClass, superInterfaces);
+ }
+ // if not, perhaps we are now resolving a well-known class or interface?
+ if (result == null) {
+ result = _fromWellKnownClass(context, rawType, bindings, superClass, superInterfaces);
+ if (result == null) {
+ result = _fromWellKnownInterface(context, rawType, bindings, superClass, superInterfaces);
+ if (result == null) {
+ // but if nothing else, ""simple"" class for now:
+ result = _newSimpleType(rawType, bindings, superClass, superInterfaces);
+ }
+ }
+ }
+ }
+ context.resolveSelfReferences(result);
+ if (cachable) {
+ _typeCache.putIfAbsent(rawType, result);
+ }
+ return result;
+ }
+
+// Test Case
+[/INST]
+ public void testMapRefinement() throws Exception
+ {
+ String ID1 = ""3a6383d4-8123-4c43-8b8d-7cedf3e59404"";
+ String ID2 = ""81c3d978-90c4-4b00-8da1-1c39ffcab02c"";
+ String json = aposToQuotes(
+""{'id':'""+ID1+""','items':[{'id':'""+ID2+""','property':'value'}]}"");
+
+ ObjectMapper m = new ObjectMapper();
+ Data data = m.readValue(json, Data.class);
+
+ assertEquals(ID1, data.id);
+ assertNotNull(data.items);
+ assertEquals(1, data.items.size());
+ Item value = data.items.get(ID2);
+ assertNotNull(value);
+ assertEquals(""value"", value.property);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMapRefinement() throws Exception
+ {
+ String ID1 = ""3a6383d4-8123-4c43-8b8d-7cedf3e59404"";
+ String ID2 = ""81c3d978-90c4-4b00-8da1-1c39ffcab02c"";
+ String json = aposToQuotes(
+""{'id':'""+ID1+""','items':[{'id':'""+ID2+""','property':'value'}]}"");
+
+ ObjectMapper m = new ObjectMapper();
+ Data data = m.readValue(json, Data.class);
+
+ assertEquals(ID1, data.id);
+ assertNotNull(data.items);
+ assertEquals(1, data.items.size());
+ Item value = data.items.get(ID2);
+ assertNotNull(value);
+ assertEquals(""value"", value.property);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected BeanPropertyWriter buildWriter(SerializerProvider prov,
+ BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer> ser,
+ TypeSerializer typeSer, TypeSerializer contentTypeSer,
+ AnnotatedMember am, boolean defaultUseStaticTyping)
+ throws JsonMappingException
+ {
+ // do we have annotation that forces type to use (to declared type or its super type)?
+ JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
+
+ // Container types can have separate type serializers for content (value / element) type
+ if (contentTypeSer != null) {
+ /* 04-Feb-2010, tatu: Let's force static typing for collection, if there is
+ * type information for contents. Should work well (for JAXB case); can be
+ * revisited if this causes problems.
+ */
+ if (serializationType == null) {
+// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
+ serializationType = declaredType;
+ }
+ JavaType ct = serializationType.getContentType();
+ // Not exactly sure why, but this used to occur; better check explicitly:
+ if (ct == null) {
+ throw new IllegalStateException(""Problem trying to create BeanPropertyWriter for property '""
+ +propDef.getName()+""' (of type ""+_beanDesc.getType()+""); serialization type ""+serializationType+"" has no content"");
+ }
+ serializationType = serializationType.withContentTypeHandler(contentTypeSer);
+ ct = serializationType.getContentType();
+ }
+
+ Object valueToSuppress = null;
+ boolean suppressNulls = false;
+
+ JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion());
+ JsonInclude.Include inclusion = inclV.getValueInclusion();
+ if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
+ inclusion = JsonInclude.Include.ALWAYS;
+ }
+
+ // 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
+ JavaType actualType = (serializationType == null) ? declaredType : serializationType;
+
+ switch (inclusion) {
+ case NON_DEFAULT:
+ // 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
+ // so that if enclosing class has this, we may need to values of property,
+ // whereas for global defaults OR per-property overrides, we have more
+ // static definition. Sigh.
+ // First: case of class specifying it; try to find POJO property defaults
+ if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) {
+ valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);
+ } else {
+ valueToSuppress = getDefaultValue(actualType);
+ }
+ if (valueToSuppress == null) {
+ suppressNulls = true;
+ } else {
+ if (valueToSuppress.getClass().isArray()) {
+ valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
+ }
+ }
+
+ break;
+ case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
+ // always suppress nulls
+ suppressNulls = true;
+ // and for referential types, also ""empty"", which in their case means ""absent""
+ if (declaredType.isReferenceType()) {
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ }
+ break;
+ case NON_EMPTY:
+ // always suppress nulls
+ suppressNulls = true;
+ // but possibly also 'empty' values:
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ break;
+ case NON_NULL:
+ suppressNulls = true;
+ // fall through
+ case ALWAYS: // default
+ default:
+ // we may still want to suppress empty collections, as per [JACKSON-254]:
+ if (declaredType.isContainerType()
+ && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ }
+ break;
+ }
+ BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
+ am, _beanDesc.getClassAnnotations(), declaredType,
+ ser, typeSer, serializationType, suppressNulls, valueToSuppress);
+
+ // How about custom null serializer?
+ Object serDef = _annotationIntrospector.findNullSerializer(am);
+ if (serDef != null) {
+ bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
+ }
+ // And then, handling of unwrapping
+ NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
+ if (unwrapper != null) {
+ bpw = bpw.unwrappingWriter(unwrapper);
+ }
+ return bpw;
+ }
+
+// Test Case
+[/INST]
+ public void testEmpty1256() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
+
+ String json = mapper.writeValueAsString(new Issue1256Bean());
+ assertEquals(""{}"", json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ public static JsonSerializer getFallbackKeySerializer(SerializationConfig config,
+ Class> rawKeyType)
+ {
+ if (rawKeyType != null) {
+ // 29-Sep-2015, tatu: Odd case here, of `Enum`, which we may get for `EnumMap`; not sure
+ // if that is a bug or feature. Regardless, it seems to require dynamic handling
+ // (compared to getting actual fully typed Enum).
+ // Note that this might even work from the earlier point, but let's play it safe for now
+ // 11-Aug-2016, tatu: Turns out we get this if `EnumMap` is the root value because
+ // then there is no static type
+ if (rawKeyType == Enum.class) {
+ return new Dynamic();
+ }
+ if (rawKeyType.isEnum()) {
+ return new Default(Default.TYPE_ENUM, rawKeyType);
+ }
+ }
+ return DEFAULT_KEY_SERIALIZER;
+ }
+
+// Test Case
+[/INST]
+ public void testEnumsWithJsonPropertyAsKey() throws Exception
+ {
+ EnumMap input = new EnumMap(EnumWithJsonProperty.class);
+ input.put(EnumWithJsonProperty.A, ""b"");
+ assertEquals(""{\""aleph\"":\""b\""}"", MAPPER.writeValueAsString(input));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ protected Object _deserialize(String value, DeserializationContext ctxt) throws IOException
+ {
+ switch (_kind) {
+ case STD_FILE:
+ return new File(value);
+ case STD_URL:
+ return new URL(value);
+ case STD_URI:
+ return URI.create(value);
+ case STD_CLASS:
+ try {
+ return ctxt.findClass(value);
+ } catch (Exception e) {
+ throw ctxt.instantiationException(_valueClass, ClassUtil.getRootCause(e));
+ }
+ case STD_JAVA_TYPE:
+ return ctxt.getTypeFactory().constructFromCanonical(value);
+ case STD_CURRENCY:
+ // will throw IAE if unknown:
+ return Currency.getInstance(value);
+ case STD_PATTERN:
+ // will throw IAE (or its subclass) if malformed
+ return Pattern.compile(value);
+ case STD_LOCALE:
+ {
+ int ix = value.indexOf('_');
+ if (ix < 0) { // single argument
+ return new Locale(value);
+ }
+ String first = value.substring(0, ix);
+ value = value.substring(ix+1);
+ ix = value.indexOf('_');
+ if (ix < 0) { // two pieces
+ return new Locale(first, value);
+ }
+ String second = value.substring(0, ix);
+ return new Locale(first, second, value.substring(ix+1));
+ }
+ case STD_CHARSET:
+ return Charset.forName(value);
+ case STD_TIME_ZONE:
+ return TimeZone.getTimeZone(value);
+ case STD_INET_ADDRESS:
+ return InetAddress.getByName(value);
+ case STD_INET_SOCKET_ADDRESS:
+ if (value.startsWith(""["")) {
+ // bracketed IPv6 (with port number)
+
+ int i = value.lastIndexOf(']');
+ if (i == -1) {
+ throw new InvalidFormatException(ctxt.getParser(),
+ ""Bracketed IPv6 address must contain closing bracket"",
+ value, InetSocketAddress.class);
+ }
+
+ int j = value.indexOf(':', i);
+ int port = j > -1 ? Integer.parseInt(value.substring(j + 1)) : 0;
+ return new InetSocketAddress(value.substring(0, i + 1), port);
+ } else {
+ int ix = value.indexOf(':');
+ if (ix >= 0 && value.indexOf(':', ix + 1) < 0) {
+ // host:port
+ int port = Integer.parseInt(value.substring(ix+1));
+ return new InetSocketAddress(value.substring(0, ix), port);
+ }
+ // host or unbracketed IPv6, without port number
+ return new InetSocketAddress(value, 0);
+ }
+ }
+ throw new IllegalArgumentException();
+ }
+
+// Test Case
+[/INST]
+ public void testLocale() throws IOException
+ {
+ assertEquals(new Locale(""en""), MAPPER.readValue(quote(""en""), Locale.class));
+ assertEquals(new Locale(""es"", ""ES""), MAPPER.readValue(quote(""es_ES""), Locale.class));
+ assertEquals(new Locale(""FI"", ""fi"", ""savo""),
+ MAPPER.readValue(quote(""fi_FI_savo""), Locale.class));
+ assertEquals(new Locale(""en"", ""US""),
+ MAPPER.readValue(quote(""en-US""), Locale.class));
+
+ // [databind#1123]
+ Locale loc = MAPPER.readValue(quote(""""), Locale.class);
+ assertSame(Locale.ROOT, loc);
+ }
+
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public MappingIterator readValues(byte[] src, int offset, int length)
+ throws IOException, JsonProcessingException
+ {
+ if (_dataFormatReaders != null) {
+ return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false);
+ }
+ return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src),
+ true));
+ }
+
+// Test Case
+[/INST]
+ public void testRootBeans() throws Exception
+ {
+ for (Source src : Source.values()) {
+ _testRootBeans(src);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,
+ BeanDescription beanDesc, BeanPropertyDefinition propDef,
+ JavaType propType0)
+ throws JsonMappingException
+ {
+ // need to ensure method is callable (for non-public)
+ AnnotatedMember mutator = propDef.getNonConstructorMutator();
+
+ if (ctxt.canOverrideAccessModifiers()) {
+ // [databind#877]: explicitly prevent forced access to `cause` of `Throwable`;
+ // never needed and attempts may cause problems on some platforms.
+ // !!! NOTE: should be handled better for 2.8 and later
+ mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
+ }
+ // note: this works since we know there's exactly one argument for methods
+ BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),
+ propType0, propDef.getWrapperName(),
+ beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());
+ JavaType type = resolveType(ctxt, beanDesc, propType0, mutator);
+ // did type change?
+ if (type != propType0) {
+ property = property.withType(type);
+ }
+
+ // First: does the Method specify the deserializer to use? If so, let's use it.
+ JsonDeserializer propDeser = findDeserializerFromAnnotation(ctxt, mutator);
+ type = modifyTypeByAnnotation(ctxt, mutator, type);
+ TypeDeserializer typeDeser = type.getTypeHandler();
+ SettableBeanProperty prop;
+ if (mutator instanceof AnnotatedMethod) {
+ prop = new MethodProperty(propDef, type, typeDeser,
+ beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);
+ } else {
+ prop = new FieldProperty(propDef, type, typeDeser,
+ beanDesc.getClassAnnotations(), (AnnotatedField) mutator);
+ }
+ if (propDeser != null) {
+ prop = prop.withValueDeserializer(propDeser);
+ }
+ // need to retain name of managed forward references:
+ AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();
+ if (ref != null && ref.isManagedReference()) {
+ prop.setManagedReferenceName(ref.getName());
+ }
+ ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();
+ if(objectIdInfo != null){
+ prop.setObjectIdInfo(objectIdInfo);
+ }
+ return prop;
+ }
+
+// Test Case
+[/INST]
+ public void testCauseOfThrowableIgnoral() throws Exception
+ {
+ final SecurityManager origSecMan = System.getSecurityManager();
+ try {
+ System.setSecurityManager(new CauseBlockingSecurityManager());
+ _testCauseOfThrowableIgnoral();
+ } finally {
+ System.setSecurityManager(origSecMan);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JavaType constructSpecializedType(JavaType baseType, Class> subclass)
+ {
+ // simple optimization to avoid costly introspection if type-erased type does NOT differ
+ final Class> rawBase = baseType.getRawClass();
+ if (rawBase == subclass) {
+ return baseType;
+ }
+
+ JavaType newType;
+
+ // also: if we start from untyped, not much to save
+ do { // bogus loop to be able to break
+ if (rawBase == Object.class) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ if (!rawBase.isAssignableFrom(subclass)) {
+ throw new IllegalArgumentException(String.format(
+ ""Class %s not subtype of %s"", subclass.getName(), baseType));
+ }
+ // A few special cases where we can simplify handling:
+
+ // (1) Original target type has no generics -- just resolve subtype
+ if (baseType.getBindings().isEmpty()) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ // (2) A small set of ""well-known"" List/Map subtypes where can take a short-cut
+ if (baseType.isContainerType()) {
+ if (baseType.isMapLikeType()) {
+ if ((subclass == HashMap.class)
+ || (subclass == LinkedHashMap.class)
+ || (subclass == EnumMap.class)
+ || (subclass == TreeMap.class)) {
+ newType = _fromClass(null, subclass,
+ TypeBindings.create(subclass, baseType.getKeyType(), baseType.getContentType()));
+ break;
+ }
+ } else if (baseType.isCollectionLikeType()) {
+ if ((subclass == ArrayList.class)
+ || (subclass == LinkedList.class)
+ || (subclass == HashSet.class)
+ || (subclass == TreeSet.class)) {
+ newType = _fromClass(null, subclass,
+ TypeBindings.create(subclass, baseType.getContentType()));
+ break;
+ }
+ // 29-Oct-2015, tatu: One further shortcut: there are variants of `EnumSet`,
+ // but they are impl details and we basically do not care...
+ if (rawBase == EnumSet.class) {
+ return baseType;
+ }
+ }
+ }
+ // (3) Sub-class does not take type parameters -- just resolve subtype
+ int typeParamCount = subclass.getTypeParameters().length;
+ if (typeParamCount == 0) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+
+ // If not, we'll need to do more thorough forward+backwards resolution. Sigh.
+
+ // 20-Oct-2015, tatu: Container, Map-types somewhat special. There is
+ // a way to fully resolve and merge hierarchies; but that gets expensive
+ // so let's, for now, try to create close-enough approximation that
+ // is not 100% same, structurally, but has equivalent information for
+ // our specific neeeds.
+ // 29-Mar-2016, tatu: See [databind#1173] (and test `TypeResolverTest`)
+ // for a case where this code does get invoked: not ideal
+ // 29-Jun-2016, tatu: As to bindings, this works for [databind#1215], but
+ // not certain it would reliably work... but let's hope for best for now
+ TypeBindings tb = _bindingsForSubtype(baseType, typeParamCount, subclass);
+ if (baseType.isInterface()) {
+ newType = baseType.refine(subclass, tb, null, new JavaType[] { baseType });
+ } else {
+ newType = baseType.refine(subclass, tb, baseType, NO_TYPES);
+ }
+ // Only SimpleType returns null, but if so just resolve regularly
+ if (newType == null) {
+ newType = _fromClass(null, subclass, tb);
+ }
+ } while (false);
+
+ // 25-Sep-2016, tatu: As per [databind#1384] also need to ensure handlers get
+ // copied as well
+ return newType;
+
+ // 20-Oct-2015, tatu: Old simplistic approach
+
+ /*
+ // Currently mostly SimpleType instances can become something else
+ if (baseType instanceof SimpleType) {
+ // and only if subclass is an array, Collection or Map
+ if (subclass.isArray()
+ || Map.class.isAssignableFrom(subclass)
+ || Collection.class.isAssignableFrom(subclass)) {
+ // need to assert type compatibility...
+ if (!baseType.getRawClass().isAssignableFrom(subclass)) {
+ throw new IllegalArgumentException(""Class ""+subclass.getClass().getName()+"" not subtype of ""+baseType);
+ }
+ // this _should_ work, right?
+ JavaType subtype = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ // one more thing: handlers to copy?
+ Object h = baseType.getValueHandler();
+ if (h != null) {
+ subtype = subtype.withValueHandler(h);
+ }
+ h = baseType.getTypeHandler();
+ if (h != null) {
+ subtype = subtype.withTypeHandler(h);
+ }
+ return subtype;
+ }
+ }
+ // But there is the need for special case for arrays too, it seems
+ if (baseType instanceof ArrayType) {
+ if (subclass.isArray()) {
+ // actually see if it might be a no-op first:
+ ArrayType at = (ArrayType) baseType;
+ Class> rawComp = subclass.getComponentType();
+ if (at.getContentType().getRawClass() == rawComp) {
+ return baseType;
+ }
+ JavaType componentType = _fromAny(null, rawComp, null);
+ return ((ArrayType) baseType).withComponentType(componentType);
+ }
+ }
+
+ // otherwise regular narrowing should work just fine
+ return baseType.narrowBy(subclass);
+ */
+ }
+
+// Test Case
+[/INST]
+ public void testMapKeyRefinement1384() throws Exception
+ {
+ final String TEST_INSTANCE_SERIALIZED =
+ ""{\""mapProperty\"":[\""java.util.HashMap\"",{\""Compound|Key\"":\""Value\""}]}"";
+ ObjectMapper mapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+
+ TestClass testInstance = mapper.readValue(TEST_INSTANCE_SERIALIZED, TestClass.class);
+ assertEquals(1, testInstance.mapProperty.size());
+ Object key = testInstance.mapProperty.keySet().iterator().next();
+ assertEquals(CompoundKey.class, key.getClass());
+ String testInstanceSerialized = mapper.writeValueAsString(testInstance);
+ assertEquals(TEST_INSTANCE_SERIALIZED, testInstanceSerialized);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMapKeyRefinement1384() throws Exception
+ {
+ final String TEST_INSTANCE_SERIALIZED =
+ ""{\""mapProperty\"":[\""java.util.HashMap\"",{\""Compound|Key\"":\""Value\""}]}"";
+ ObjectMapper mapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+
+ TestClass testInstance = mapper.readValue(TEST_INSTANCE_SERIALIZED, TestClass.class);
+ assertEquals(1, testInstance.mapProperty.size());
+ Object key = testInstance.mapProperty.keySet().iterator().next();
+ assertEquals(CompoundKey.class, key.getClass());
+ String testInstanceSerialized = mapper.writeValueAsString(testInstance);
+ assertEquals(TEST_INSTANCE_SERIALIZED, testInstanceSerialized);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMapKeyRefinement1384() throws Exception
+ {
+ final String TEST_INSTANCE_SERIALIZED =
+ ""{\""mapProperty\"":[\""java.util.HashMap\"",{\""Compound|Key\"":\""Value\""}]}"";
+ ObjectMapper mapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+
+ TestClass testInstance = mapper.readValue(TEST_INSTANCE_SERIALIZED, TestClass.class);
+ assertEquals(1, testInstance.mapProperty.size());
+ Object key = testInstance.mapProperty.keySet().iterator().next();
+ assertEquals(CompoundKey.class, key.getClass());
+ String testInstanceSerialized = mapper.writeValueAsString(testInstance);
+ assertEquals(TEST_INSTANCE_SERIALIZED, testInstanceSerialized);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testMapKeyRefinement1384() throws Exception
+ {
+ final String TEST_INSTANCE_SERIALIZED =
+ ""{\""mapProperty\"":[\""java.util.HashMap\"",{\""Compound|Key\"":\""Value\""}]}"";
+ ObjectMapper mapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+
+ TestClass testInstance = mapper.readValue(TEST_INSTANCE_SERIALIZED, TestClass.class);
+ assertEquals(1, testInstance.mapProperty.size());
+ Object key = testInstance.mapProperty.keySet().iterator().next();
+ assertEquals(CompoundKey.class, key.getClass());
+ String testInstanceSerialized = mapper.writeValueAsString(testInstance);
+ assertEquals(TEST_INSTANCE_SERIALIZED, testInstanceSerialized);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Date parseAsISO8601(String dateStr, ParsePosition pos)
+ {
+ /* 21-May-2009, tatu: DateFormat has very strict handling of
+ * timezone modifiers for ISO-8601. So we need to do some scrubbing.
+ */
+
+ /* First: do we have ""zulu"" format ('Z' == ""GMT"")? If yes, that's
+ * quite simple because we already set date format timezone to be
+ * GMT, and hence can just strip out 'Z' altogether
+ */
+ int len = dateStr.length();
+ char c = dateStr.charAt(len-1);
+ DateFormat df;
+
+ // [JACKSON-200]: need to support ""plain"" date...
+ if (len <= 10 && Character.isDigit(c)) {
+ df = _formatPlain;
+ if (df == null) {
+ df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale);
+ }
+ } else if (c == 'Z') {
+ df = _formatISO8601_z;
+ if (df == null) {
+ df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale);
+ }
+ // [JACKSON-334]: may be missing milliseconds... if so, add
+ if (dateStr.charAt(len-4) == ':') {
+ StringBuilder sb = new StringBuilder(dateStr);
+ sb.insert(len-1, "".000"");
+ dateStr = sb.toString();
+ }
+ } else {
+ // Let's see if we have timezone indicator or not...
+ if (hasTimeZone(dateStr)) {
+ c = dateStr.charAt(len-3);
+ if (c == ':') { // remove optional colon
+ // remove colon
+ StringBuilder sb = new StringBuilder(dateStr);
+ sb.delete(len-3, len-2);
+ dateStr = sb.toString();
+ } else if (c == '+' || c == '-') { // missing minutes
+ // let's just append '00'
+ dateStr += ""00"";
+ }
+ // Milliseconds partial or missing; and even seconds are optional
+ len = dateStr.length();
+ // remove 'T', '+'/'-' and 4-digit timezone-offset
+ c = dateStr.charAt(len-9);
+ if (Character.isDigit(c)) {
+ StringBuilder sb = new StringBuilder(dateStr);
+ sb.insert(len-5, "".000"");
+ dateStr = sb.toString();
+ }
+ df = _formatISO8601;
+ if (_formatISO8601 == null) {
+ df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale);
+ }
+ } else {
+ // If not, plain date. Easiest to just patch 'Z' in the end?
+ StringBuilder sb = new StringBuilder(dateStr);
+ // And possible also millisecond part if missing
+ int timeLen = len - dateStr.lastIndexOf('T') - 1;
+ if (timeLen <= 8) {
+ sb.append("".000"");
+ }
+ sb.append('Z');
+ dateStr = sb.toString();
+ df = _formatISO8601_z;
+ if (df == null) {
+ df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z,
+ _timezone, _locale);
+ }
+ }
+ }
+ return df.parse(dateStr, pos);
+ }
+
+// Test Case
+[/INST]
+ public void testISO8601MissingSeconds() throws Exception
+ {
+ String inputStr;
+ Date inputDate;
+ Calendar c = Calendar.getInstance(TimeZone.getTimeZone(""GMT""));
+
+ inputStr = ""1997-07-16T19:20+01:00"";
+ inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
+ c.setTime(inputDate);
+ assertEquals(1997, c.get(Calendar.YEAR));
+ assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
+ assertEquals(16, c.get(Calendar.DAY_OF_MONTH));
+ assertEquals(19 - 1, c.get(Calendar.HOUR_OF_DAY));
+ assertEquals(0, c.get(Calendar.SECOND));
+ assertEquals(0, c.get(Calendar.MILLISECOND));
+}
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public void serializeWithType(Object bean, JsonGenerator gen, SerializerProvider provider,
+ TypeSerializer typeSer0) throws IOException
+ {
+ // Regardless of other parts, first need to find value to serialize:
+ Object value = null;
+ try {
+ value = _accessorMethod.getValue(bean);
+ // and if we got null, can also just write it directly
+ if (value == null) {
+ provider.defaultSerializeNull(gen);
+ return;
+ }
+ JsonSerializer ser = _valueSerializer;
+ if (ser == null) { // no serializer yet? Need to fetch
+// ser = provider.findTypedValueSerializer(value.getClass(), true, _property);
+ ser = provider.findValueSerializer(value.getClass(), _property);
+ } else {
+ /* 09-Dec-2010, tatu: To work around natural type's refusal to add type info, we do
+ * this (note: type is for the wrapper type, not enclosed value!)
+ */
+ if (_forceTypeInformation) {
+ typeSer0.writeTypePrefixForScalar(bean, gen);
+ ser.serialize(value, gen, provider);
+ typeSer0.writeTypeSuffixForScalar(bean, gen);
+ return;
+ }
+ }
+ // 28-Sep-2016, tatu: As per [databind#1385], we do need to do some juggling
+ // to use different Object for type id (logical type) and actual serialization
+ // (delegat type).
+ ser.serializeWithType(value, gen, provider, typeSer0);
+ } catch (IOException ioe) {
+ throw ioe;
+ } catch (Exception e) {
+ Throwable t = e;
+ // Need to unwrap this specific type, to see infinite recursion...
+ while (t instanceof InvocationTargetException && t.getCause() != null) {
+ t = t.getCause();
+ }
+ // Errors shouldn't be wrapped (and often can't, as well)
+ if (t instanceof Error) {
+ throw (Error) t;
+ }
+ // let's try to indicate the path best we can...
+ throw JsonMappingException.wrapWithPath(t, bean, _accessorMethod.getName() + ""()"");
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testWithCreatorAndJsonValue() throws Exception
+ {
+ final byte[] BYTES = new byte[] { 1, 2, 3, 4, 5 };
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enableDefaultTyping();
+ String json = mapper.writeValueAsString(new Bean1385Wrapper(
+ new Bean1385(BYTES)
+ ));
+ Bean1385Wrapper result = mapper.readValue(json, Bean1385Wrapper.class);
+ assertNotNull(result);
+ assertNotNull(result.value);
+ assertEquals(Bean1385.class, result.value.getClass());
+ Bean1385 b = (Bean1385) result.value;
+ Assert.assertArrayEquals(BYTES, b.raw);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public TypeSerializer buildTypeSerializer(SerializationConfig config,
+ JavaType baseType, Collection subtypes)
+ {
+ if (_idType == JsonTypeInfo.Id.NONE) { return null; }
+ // 03-Oct-2016, tatu: As per [databind#1395] better prevent use for primitives,
+ // regardless of setting
+ TypeIdResolver idRes = idResolver(config, baseType, subtypes, true, false);
+ switch (_includeAs) {
+ case WRAPPER_ARRAY:
+ return new AsArrayTypeSerializer(idRes, null);
+ case PROPERTY:
+ return new AsPropertyTypeSerializer(idRes, null, _typeProperty);
+ case WRAPPER_OBJECT:
+ return new AsWrapperTypeSerializer(idRes, null);
+ case EXTERNAL_PROPERTY:
+ return new AsExternalTypeSerializer(idRes, null, _typeProperty);
+ case EXISTING_PROPERTY:
+ // as per [#528]
+ return new AsExistingPropertyTypeSerializer(idRes, null, _typeProperty);
+ }
+ throw new IllegalStateException(""Do not know how to construct standard type serializer for inclusion type: ""+_includeAs);
+ }
+
+// Test Case
+[/INST]
+ public void testDefaultTypingWithLong() throws Exception
+ {
+ Data data = new Data();
+ data.key = 1L;
+ Map mapData = new HashMap();
+ mapData.put(""longInMap"", 2L);
+ mapData.put(""longAsField"", data);
+
+ // Configure Jackson to preserve types
+ ObjectMapper mapper = new ObjectMapper();
+ StdTypeResolverBuilder resolver = new StdTypeResolverBuilder();
+ resolver.init(JsonTypeInfo.Id.CLASS, null);
+ resolver.inclusion(JsonTypeInfo.As.PROPERTY);
+ resolver.typeProperty(""__t"");
+ mapper.setDefaultTyping(resolver);
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+
+ // Serialize
+ String json = mapper.writeValueAsString(mapData);
+
+ // Deserialize
+ Map,?> result = mapper.readValue(json, Map.class);
+ assertNotNull(result);
+ assertEquals(2, result.size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public TypeDeserializer buildTypeDeserializer(DeserializationConfig config,
+ JavaType baseType, Collection subtypes)
+ {
+ if (_idType == JsonTypeInfo.Id.NONE) { return null; }
+ // 03-Oct-2016, tatu: As per [databind#1395] better prevent use for primitives,
+ // regardless of setting
+
+ TypeIdResolver idRes = idResolver(config, baseType, subtypes, false, true);
+
+ JavaType defaultImpl;
+
+ if (_defaultImpl == null) {
+ defaultImpl = null;
+ } else {
+ // 20-Mar-2016, tatu: It is important to do specialization go through
+ // TypeFactory to ensure proper resolution; with 2.7 and before, direct
+ // call to JavaType was used, but that can not work reliably with 2.7
+ // 20-Mar-2016, tatu: Can finally add a check for type compatibility BUT
+ // if so, need to add explicit checks for marker types. Not ideal, but
+ // seems like a reasonable compromise.
+ if ((_defaultImpl == Void.class)
+ || (_defaultImpl == NoClass.class)) {
+ defaultImpl = config.getTypeFactory().constructType(_defaultImpl);
+ } else {
+ defaultImpl = config.getTypeFactory()
+ .constructSpecializedType(baseType, _defaultImpl);
+ }
+ }
+
+ // First, method for converting type info to type id:
+ switch (_includeAs) {
+ case WRAPPER_ARRAY:
+ return new AsArrayTypeDeserializer(baseType, idRes,
+ _typeProperty, _typeIdVisible, defaultImpl);
+ case PROPERTY:
+ case EXISTING_PROPERTY: // as per [#528] same class as PROPERTY
+ return new AsPropertyTypeDeserializer(baseType, idRes,
+ _typeProperty, _typeIdVisible, defaultImpl, _includeAs);
+ case WRAPPER_OBJECT:
+ return new AsWrapperTypeDeserializer(baseType, idRes,
+ _typeProperty, _typeIdVisible, defaultImpl);
+ case EXTERNAL_PROPERTY:
+ return new AsExternalTypeDeserializer(baseType, idRes,
+ _typeProperty, _typeIdVisible, defaultImpl);
+ }
+ throw new IllegalStateException(""Do not know how to construct standard type serializer for inclusion type: ""+_includeAs);
+ }
+
+// Test Case
+[/INST]
+ public void testDefaultTypingWithLong() throws Exception
+ {
+ Data data = new Data();
+ data.key = 1L;
+ Map mapData = new HashMap();
+ mapData.put(""longInMap"", 2L);
+ mapData.put(""longAsField"", data);
+
+ // Configure Jackson to preserve types
+ ObjectMapper mapper = new ObjectMapper();
+ StdTypeResolverBuilder resolver = new StdTypeResolverBuilder();
+ resolver.init(JsonTypeInfo.Id.CLASS, null);
+ resolver.inclusion(JsonTypeInfo.As.PROPERTY);
+ resolver.typeProperty(""__t"");
+ mapper.setDefaultTyping(resolver);
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+
+ // Serialize
+ String json = mapper.writeValueAsString(mapData);
+
+ // Deserialize
+ Map,?> result = mapper.readValue(json, Map.class);
+ assertNotNull(result);
+ assertEquals(2, result.size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean useForType(JavaType t)
+ {
+ // 03-Oct-2016, tatu: As per [databind#1395], need to skip
+ // primitive types too, regardless
+
+ switch (_appliesFor) {
+ case NON_CONCRETE_AND_ARRAYS:
+ while (t.isArrayType()) {
+ t = t.getContentType();
+ }
+ // fall through
+ case OBJECT_AND_NON_CONCRETE:
+ // 19-Apr-2016, tatu: ReferenceType like Optional also requires similar handling:
+ while (t.isReferenceType()) {
+ t = t.getReferencedType();
+ }
+ return t.isJavaLangObject()
+ || (!t.isConcrete()
+ // [databind#88] Should not apply to JSON tree models:
+ && !TreeNode.class.isAssignableFrom(t.getRawClass()));
+
+ case NON_FINAL:
+ while (t.isArrayType()) {
+ t = t.getContentType();
+ }
+ // 19-Apr-2016, tatu: ReferenceType like Optional also requires similar handling:
+ while (t.isReferenceType()) {
+ t = t.getReferencedType();
+ }
+ // [databind#88] Should not apply to JSON tree models:
+ return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
+ default:
+ //case JAVA_LANG_OBJECT:
+ return t.isJavaLangObject();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testDefaultTypingWithLong() throws Exception
+ {
+ Data data = new Data();
+ data.key = 1L;
+ Map mapData = new HashMap();
+ mapData.put(""longInMap"", 2L);
+ mapData.put(""longAsField"", data);
+
+ // Configure Jackson to preserve types
+ ObjectMapper mapper = new ObjectMapper();
+ StdTypeResolverBuilder resolver = new StdTypeResolverBuilder();
+ resolver.init(JsonTypeInfo.Id.CLASS, null);
+ resolver.inclusion(JsonTypeInfo.As.PROPERTY);
+ resolver.typeProperty(""__t"");
+ mapper.setDefaultTyping(resolver);
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+
+ // Serialize
+ String json = mapper.writeValueAsString(mapData);
+
+ // Deserialize
+ Map,?> result = mapper.readValue(json, Map.class);
+ assertNotNull(result);
+ assertEquals(2, result.size());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public CollectionDeserializer createContextual(DeserializationContext ctxt,
+ BeanProperty property) throws JsonMappingException
+ {
+ // May need to resolve types for delegate-based creators:
+ JsonDeserializer delegateDeser = null;
+ if (_valueInstantiator != null) {
+ if (_valueInstantiator.canCreateUsingDelegate()) {
+ JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
+ if (delegateType == null) {
+ throw new IllegalArgumentException(""Invalid delegate-creator definition for ""+_collectionType
+ +"": value instantiator (""+_valueInstantiator.getClass().getName()
+ +"") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'"");
+ }
+ delegateDeser = findDeserializer(ctxt, delegateType, property);
+ }
+ }
+ // [databind#1043]: allow per-property allow-wrapping of single overrides:
+ // 11-Dec-2015, tatu: Should we pass basic `Collection.class`, or more refined? Mostly
+ // comes down to ""List vs Collection"" I suppose... for now, pass Collection
+ Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,
+ JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ // also, often value deserializer is resolved here:
+ JsonDeserializer> valueDeser = _valueDeserializer;
+
+ // May have a content converter
+ valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);
+ final JavaType vt = _collectionType.getContentType();
+ if (valueDeser == null) {
+ valueDeser = ctxt.findContextualValueDeserializer(vt, property);
+ } else { // if directly assigned, probably not yet contextual, so:
+ valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, vt);
+ }
+ // and finally, type deserializer needs context as well
+ TypeDeserializer valueTypeDeser = _valueTypeDeserializer;
+ if (valueTypeDeser != null) {
+ valueTypeDeser = valueTypeDeser.forProperty(property);
+ }
+ return withResolved(delegateDeser, valueDeser, valueTypeDeser, unwrapSingle);
+ }
+
+// Test Case
+[/INST]
+ public void testUnmodifiable() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ Class> unmodSetType = Collections.unmodifiableSet(Collections.emptySet()).getClass();
+ mapper.addMixIn(unmodSetType, UnmodifiableSetMixin.class);
+ mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
+
+ final String EXPECTED_JSON = ""[\""""+unmodSetType.getName()+""\"",[]]"";
+
+ Set> foo = mapper.readValue(EXPECTED_JSON, Set.class);
+ assertTrue(foo.isEmpty());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static class Reference implements Serializable
+ {
+ private static final long serialVersionUID = 2L; // changes between 2.7 and 2.8
+
+ // transient since 2.8
+ protected transient Object _from;
+
+ /**
+ * Name of field (for beans) or key (for Maps) that is part
+ * of the reference. May be null for Collection types (which
+ * generally have {@link #_index} defined), or when resolving
+ * Map classes without (yet) having an instance to operate on.
+ */
+ protected String _fieldName;
+
+ /**
+ * Index within a {@link Collection} instance that contained
+ * the reference; used if index is relevant and available.
+ * If either not applicable, or not available, -1 is used to
+ * denote ""not known"" (or not relevant).
+ */
+ protected int _index = -1;
+
+ /**
+ * Lazily-constructed description of this instance; needed mostly to
+ * allow JDK serialization to work in case where {@link #_from} is
+ * non-serializable (and has to be dropped) but we still want to pass
+ * actual description along.
+ *
+ * @since 2.8
+ */
+ protected String _desc;
+
+ /**
+ * Default constructor for deserialization/sub-classing purposes
+ */
+ protected Reference() { }
+
+ public Reference(Object from) { _from = from; }
+
+ public Reference(Object from, String fieldName) {
+ _from = from;
+ if (fieldName == null) {
+ throw new NullPointerException(""Can not pass null fieldName"");
+ }
+ _fieldName = fieldName;
+ }
+
+ public Reference(Object from, int index) {
+ _from = from;
+ _index = index;
+ }
+
+ // Setters to let Jackson deserialize instances, but not to be called from outside
+ void setFieldName(String n) { _fieldName = n; }
+ void setIndex(int ix) { _index = ix; }
+ void setDescription(String d) { _desc = d; }
+
+ /**
+ * Object through which reference was resolved. Can be either
+ * actual instance (usually the case for serialization), or
+ * Class (usually the case for deserialization).
+ *
+ * Note that this value must be `transient` to allow serializability (as
+ * often such Object is NOT serializable; or, in case of `Class`, may
+ * not available at the point of deserialization). As such will return
+ * `null` if instance has been passed using JDK serialization.
+ */
+ @JsonIgnore
+ public Object getFrom() { return _from; }
+
+ public String getFieldName() { return _fieldName; }
+ public int getIndex() { return _index; }
+ public String getDescription() {
+ if (_desc == null) {
+ StringBuilder sb = new StringBuilder();
+
+ if (_from == null) { // can this ever occur?
+ sb.append(""UNKNOWN"");
+ } else {
+ Class> cls = (_from instanceof Class>) ? (Class>)_from : _from.getClass();
+ // Hmmh. Although Class.getName() is mostly ok, it does look
+ // butt-ugly for arrays.
+ // 06-Oct-2016, tatu: as per [databind#1403], `getSimpleName()` not so good
+ // as it drops enclosing class. So let's try bit different approach
+ String pkgName = ClassUtil.getPackageName(cls);
+ if (pkgName != null) {
+ sb.append(pkgName);
+ sb.append('.');
+ }
+ sb.append(cls.getSimpleName());
+ }
+ sb.append('[');
+ if (_fieldName != null) {
+ sb.append('""');
+ sb.append(_fieldName);
+ sb.append('""');
+ } else if (_index >= 0) {
+ sb.append(_index);
+ } else {
+ sb.append('?');
+ }
+ sb.append(']');
+ _desc = sb.toString();
+ }
+ return _desc;
+ }
+
+ @Override
+ public String toString() {
+ return getDescription();
+ }
+
+ /**
+ * May need some cleaning here, given that `from` may or may not be serializable.
+ *
+ * since 2.8
+ */
+ Object writeReplace() {
+ // as per [databind#1195], need to ensure description is not null, since
+ // `_from` is transient
+ getDescription();
+ return this;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testReferenceChainForInnerClass() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new Outer());
+ try {
+ MAPPER.readValue(json, Outer.class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ JsonMappingException.Reference reference = e.getPath().get(0);
+ assertEquals(getClass().getName()+""$Outer[\""inner\""]"",
+ reference.toString());
+ }
+ }
+
+ public static void main(String[] args)
+ {
+ System.err.println(""Int, full: ""+Integer.TYPE.getName());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected BeanPropertyWriter buildWriter(SerializerProvider prov,
+ BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer> ser,
+ TypeSerializer typeSer, TypeSerializer contentTypeSer,
+ AnnotatedMember am, boolean defaultUseStaticTyping)
+ throws JsonMappingException
+ {
+ // do we have annotation that forces type to use (to declared type or its super type)?
+ JavaType serializationType;
+ try {
+ serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
+ } catch (JsonMappingException e) {
+ return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());
+ }
+
+ // Container types can have separate type serializers for content (value / element) type
+ if (contentTypeSer != null) {
+ /* 04-Feb-2010, tatu: Let's force static typing for collection, if there is
+ * type information for contents. Should work well (for JAXB case); can be
+ * revisited if this causes problems.
+ */
+ if (serializationType == null) {
+// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
+ serializationType = declaredType;
+ }
+ JavaType ct = serializationType.getContentType();
+ // Not exactly sure why, but this used to occur; better check explicitly:
+ if (ct == null) {
+ prov.reportBadPropertyDefinition(_beanDesc, propDef,
+ ""serialization type ""+serializationType+"" has no content"");
+ }
+ serializationType = serializationType.withContentTypeHandler(contentTypeSer);
+ ct = serializationType.getContentType();
+ }
+
+ Object valueToSuppress = null;
+ boolean suppressNulls = false;
+
+ // 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
+ JavaType actualType = (serializationType == null) ? declaredType : serializationType;
+
+ // 17-Aug-2016, tatu: Default inclusion covers global default (for all types), as well
+ // as type-default for enclosing POJO. What we need, then, is per-type default (if any)
+ // for declared property type... and finally property annotation overrides
+ JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(),
+ _defaultInclusion);
+
+ // property annotation override
+
+ inclV = inclV.withOverrides(propDef.findInclusion());
+ JsonInclude.Include inclusion = inclV.getValueInclusion();
+
+ if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
+ inclusion = JsonInclude.Include.ALWAYS;
+ }
+
+ switch (inclusion) {
+ case NON_DEFAULT:
+ // 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
+ // so that if enclosing class has this, we may need to access values of property,
+ // whereas for global defaults OR per-property overrides, we have more
+ // static definition. Sigh.
+ // First: case of class/type specifying it; try to find POJO property defaults
+
+ // 16-Oct-2016, tatu: Note: if we can not for some reason create ""default instance"",
+ // revert logic to the case of general/per-property handling, so both
+ // type-default AND null are to be excluded.
+ // (as per [databind#1417]
+ if (_useRealPropertyDefaults) {
+ // 07-Sep-2016, tatu: may also need to front-load access forcing now
+ if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {
+ am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
+ }
+ valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);
+ } else {
+ valueToSuppress = getDefaultValue(actualType);
+ suppressNulls = true;
+ }
+ if (valueToSuppress == null) {
+ suppressNulls = true;
+ } else {
+ if (valueToSuppress.getClass().isArray()) {
+ valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
+ }
+ }
+ break;
+ case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
+ // always suppress nulls
+ suppressNulls = true;
+ // and for referential types, also ""empty"", which in their case means ""absent""
+ if (actualType.isReferenceType()) {
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ }
+ break;
+ case NON_EMPTY:
+ // always suppress nulls
+ suppressNulls = true;
+ // but possibly also 'empty' values:
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ break;
+ case NON_NULL:
+ suppressNulls = true;
+ // fall through
+ case ALWAYS: // default
+ default:
+ // we may still want to suppress empty collections, as per [JACKSON-254]:
+ if (actualType.isContainerType()
+ && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
+ valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
+ }
+ break;
+ }
+ BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
+ am, _beanDesc.getClassAnnotations(), declaredType,
+ ser, typeSer, serializationType, suppressNulls, valueToSuppress);
+
+ // How about custom null serializer?
+ Object serDef = _annotationIntrospector.findNullSerializer(am);
+ if (serDef != null) {
+ bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
+ }
+ // And then, handling of unwrapping
+ NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
+ if (unwrapper != null) {
+ bpw = bpw.unwrappingWriter(unwrapper);
+ }
+ return bpw;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1351() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
+ assertEquals(aposToQuotes(""{}""),
+ mapper.writeValueAsString(new Issue1351Bean(null, (double) 0)));
+ // [databind#1417]
+ assertEquals(aposToQuotes(""{}""),
+ mapper.writeValueAsString(new Issue1351NonBean(0)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Object deserializeKey(String key, DeserializationContext ctxt)
+ throws IOException
+ {
+ if (key == null) { // is this even legal call?
+ return null;
+ }
+ try {
+ Object result = _parse(key, ctxt);
+ if (result != null) {
+ return result;
+ }
+ } catch (Exception re) {
+ return ctxt.handleWeirdKey(_keyClass, key, ""not a valid representation, problem: %s"", re.getMessage());
+ }
+ if (_keyClass.isEnum() && ctxt.getConfig().isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
+ return null;
+ }
+ return ctxt.handleWeirdKey(_keyClass, key, ""not a valid representation"");
+ }
+
+
+// Test Case
+[/INST]
+ public void testDeserializeKeyViaFactory() throws Exception
+ {
+ Map map =
+ new ObjectMapper().readValue(""{\""first.last\"": 42}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Method findFactoryMethod(Class>... expArgTypes)
+ {
+ // So, of all single-arg static methods:
+ for (AnnotatedMethod am : _classInfo.getStaticMethods()) {
+ // 24-Oct-2016, tatu: Better ensure it only takes 1 arg, no matter what
+ if (isFactoryMethod(am)) {
+ // And must take one of expected arg types (or supertype)
+ Class> actualArgType = am.getRawParameterType(0);
+ for (Class> expArgType : expArgTypes) {
+ // And one that matches what we would pass in
+ if (actualArgType.isAssignableFrom(expArgType)) {
+ return am.getAnnotated();
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testDeserializeKeyViaFactory() throws Exception
+ {
+ Map map =
+ new ObjectMapper().readValue(""{\""first.last\"": 42}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected boolean isFactoryMethod(AnnotatedMethod am)
+ {
+ /* First: return type must be compatible with the introspected class
+ * (i.e. allowed to be sub-class, although usually is the same class)
+ */
+ Class> rt = am.getRawReturnType();
+ if (!getBeanClass().isAssignableFrom(rt)) {
+ return false;
+ }
+ /* Also: must be a recognized factory method, meaning:
+ * (a) marked with @JsonCreator annotation, or
+ * (b) ""valueOf"" (at this point, need not be public)
+ */
+ if (_annotationIntrospector.hasCreatorAnnotation(am)) {
+ return true;
+ }
+ final String name = am.getName();
+ // 24-Oct-2016, tatu: As per [databind#1429] must ensure takes exactly one arg
+ if (""valueOf"".equals(name)) {
+ return true;
+ }
+ // [databind#208] Also accept ""fromString()"", if takes String or CharSequence
+ if (""fromString"".equals(name)) {
+ if (am.getParameterCount() == 1) {
+ Class> cls = am.getRawParameterType(0);
+ if (cls == String.class || CharSequence.class.isAssignableFrom(cls)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testDeserializeKeyViaFactory() throws Exception
+ {
+ Map map =
+ new ObjectMapper().readValue(""{\""first.last\"": 42}"",
+ new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final Object deserializeKey(String key, DeserializationContext ctxt)
+ throws IOException
+ {
+ if (key == null) { // is this even legal call?
+ return null;
+ }
+ try {
+ // Ugh... should not have to give parser which may or may not be correct one...
+ Object result = _delegate.deserialize(ctxt.getParser(), ctxt);
+ if (result != null) {
+ return result;
+ }
+ return ctxt.handleWeirdKey(_keyClass, key, ""not a valid representation"");
+ } catch (Exception re) {
+ return ctxt.handleWeirdKey(_keyClass, key, ""not a valid representation: %s"", re.getMessage());
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testCustomEnumKeySerializerWithPolymorphic() throws IOException
+ {
+ SimpleModule simpleModule = new SimpleModule();
+ simpleModule.addDeserializer(SuperTypeEnum.class, new JsonDeserializer() {
+ @Override
+ public SuperTypeEnum deserialize(JsonParser p, DeserializationContext deserializationContext)
+ throws IOException
+ {
+ return SuperTypeEnum.valueOf(p.getText());
+ }
+ });
+ ObjectMapper mapper = new ObjectMapper()
+ .registerModule(simpleModule);
+
+ SuperType superType = mapper.readValue(""{\""someMap\"": {\""FOO\"": \""bar\""}}"",
+ SuperType.class);
+ assertEquals(""Deserialized someMap.FOO should equal bar"", ""bar"",
+ superType.someMap.get(SuperTypeEnum.FOO));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,
+ JavaType type)
+ throws JsonMappingException
+ {
+ final DeserializationConfig config = ctxt.getConfig();
+ KeyDeserializer deser = null;
+ if (_factoryConfig.hasKeyDeserializers()) {
+ BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass());
+ for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {
+ deser = d.findKeyDeserializer(type, config, beanDesc);
+ if (deser != null) {
+ break;
+ }
+ }
+ }
+ // the only non-standard thing is this:
+ if (deser == null) {
+ if (type.isEnumType()) {
+ return _createEnumKeyDeserializer(ctxt, type);
+ }
+ deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);
+ }
+ // and then post-processing
+ if (deser != null) {
+ if (_factoryConfig.hasDeserializerModifiers()) {
+ for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
+ deser = mod.modifyKeyDeserializer(config, type, deser);
+ }
+ }
+ }
+ return deser;
+ }
+
+// Test Case
+[/INST]
+ @SuppressWarnings({ ""unchecked"", ""rawtypes"" })
+ public void testCustomEnumValueAndKeyViaModifier() throws IOException
+ {
+ SimpleModule module = new SimpleModule();
+ module.setDeserializerModifier(new BeanDeserializerModifier() {
+ @Override
+ public JsonDeserializer modifyEnumDeserializer(DeserializationConfig config,
+ final JavaType type, BeanDescription beanDesc,
+ final JsonDeserializer> deserializer) {
+ return new JsonDeserializer() {
+ @Override
+ public Enum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
+ Class extends Enum> rawClass = (Class>) type.getRawClass();
+ final String str = p.getValueAsString().toLowerCase();
+ return KeyEnum.valueOf(rawClass, str);
+ }
+ };
+ }
+
+ @Override
+ public KeyDeserializer modifyKeyDeserializer(DeserializationConfig config,
+ final JavaType type, KeyDeserializer deserializer)
+ {
+ if (!type.isEnumType()) {
+ return deserializer;
+ }
+ return new KeyDeserializer() {
+ @Override
+ public Object deserializeKey(String key, DeserializationContext ctxt)
+ throws IOException
+ {
+ Class extends Enum> rawClass = (Class>) type.getRawClass();
+ return Enum.valueOf(rawClass, key.toLowerCase());
+ }
+ };
+ }
+ });
+ ObjectMapper mapper = new ObjectMapper()
+ .registerModule(module);
+
+ // First, enum value as is
+ KeyEnum key = mapper.readValue(quote(KeyEnum.replacements.name().toUpperCase()),
+ KeyEnum.class);
+ assertSame(KeyEnum.replacements, key);
+
+ // and then as key
+ EnumMap map = mapper.readValue(
+ aposToQuotes(""{'REPlaceMENTS':'foobar'}""),
+ new TypeReference>() { });
+ assertEquals(1, map.size());
+ assertSame(KeyEnum.replacements, map.keySet().iterator().next());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object deserializeFromObjectUsingNonDefault(JsonParser p,
+ DeserializationContext ctxt) throws IOException
+ {
+ if (_delegateDeserializer != null) {
+ return _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ }
+ if (_propertyBasedCreator != null) {
+ return _deserializeUsingPropertyBased(p, ctxt);
+ }
+ // should only occur for abstract types...
+ if (_beanType.isAbstract()) {
+ return ctxt.handleMissingInstantiator(handledType(), p,
+ ""abstract type (need to add/enable type information?)"");
+ }
+ return ctxt.handleMissingInstantiator(_beanType.getRawClass(), p,
+ ""no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)"");
+ }
+
+// Test Case
+[/INST]
+ public void testSuccessfulDeserializationOfObjectWithChainedArrayCreators() throws IOException
+ {
+ MAPPER.readValue(JSON, Bean1421A.class);
+ }
+
+ public void testWithSingleString() throws Exception {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ Bean1421B> a = objectMapper.readValue(quote(""test2""),
+ new TypeReference>>() {});
+ List expected = new ArrayList<>();
+ expected.add(""test2"");
+ assertEquals(expected, a.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""incomplete-switch"")
+ public Object deserializeFromNumber(JsonParser p, DeserializationContext ctxt)
+ throws IOException
+ {
+ // First things first: id Object Id is used, most likely that's it
+ if (_objectIdReader != null) {
+ return deserializeFromObjectId(p, ctxt);
+ }
+ switch (p.getNumberType()) {
+ case INT:
+ if (_delegateDeserializer != null) {
+ if (!_valueInstantiator.canCreateFromInt()) {
+ Object bean = _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ }
+ }
+ return _valueInstantiator.createFromInt(ctxt, p.getIntValue());
+ case LONG:
+ if (_delegateDeserializer != null) {
+ if (!_valueInstantiator.canCreateFromInt()) {
+ Object bean = _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ }
+ }
+ return _valueInstantiator.createFromLong(ctxt, p.getLongValue());
+ }
+ // actually, could also be BigInteger, so:
+ if (_delegateDeserializer != null) {
+ Object bean = _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ }
+ return ctxt.handleMissingInstantiator(handledType(), p,
+ ""no suitable creator method found to deserialize from Number value (%s)"",
+ p.getNumberValue());
+ }
+
+// Test Case
+[/INST]
+ public void testSuccessfulDeserializationOfObjectWithChainedArrayCreators() throws IOException
+ {
+ MAPPER.readValue(JSON, Bean1421A.class);
+ }
+
+ public void testWithSingleString() throws Exception {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ Bean1421B> a = objectMapper.readValue(quote(""test2""),
+ new TypeReference>>() {});
+ List expected = new ArrayList<>();
+ expected.add(""test2"");
+ assertEquals(expected, a.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object deserializeFromString(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ // First things first: id Object Id is used, most likely that's it
+ if (_objectIdReader != null) {
+ return deserializeFromObjectId(p, ctxt);
+ }
+ /* Bit complicated if we have delegating creator; may need to use it,
+ * or might not...
+ */
+ if (_delegateDeserializer != null) {
+ if (!_valueInstantiator.canCreateFromString()) {
+ Object bean = _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ }
+ }
+ return _valueInstantiator.createFromString(ctxt, p.getText());
+ }
+
+// Test Case
+[/INST]
+ public void testSuccessfulDeserializationOfObjectWithChainedArrayCreators() throws IOException
+ {
+ MAPPER.readValue(JSON, Bean1421A.class);
+ }
+
+ public void testWithSingleString() throws Exception {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ Bean1421B> a = objectMapper.readValue(quote(""test2""),
+ new TypeReference>>() {});
+ List expected = new ArrayList<>();
+ expected.add(""test2"");
+ assertEquals(expected, a.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object deserializeFromDouble(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ NumberType t = p.getNumberType();
+ // no separate methods for taking float...
+ if ((t == NumberType.DOUBLE) || (t == NumberType.FLOAT)) {
+ if (_delegateDeserializer != null) {
+ if (!_valueInstantiator.canCreateFromDouble()) {
+ Object bean = _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ }
+ }
+ return _valueInstantiator.createFromDouble(ctxt, p.getDoubleValue());
+ }
+ // actually, could also be BigDecimal, so:
+ if (_delegateDeserializer != null) {
+ return _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ }
+ return ctxt.handleMissingInstantiator(handledType(), p,
+ ""no suitable creator method found to deserialize from Number value (%s)"",
+ p.getNumberValue());
+ }
+
+// Test Case
+[/INST]
+ public void testSuccessfulDeserializationOfObjectWithChainedArrayCreators() throws IOException
+ {
+ MAPPER.readValue(JSON, Bean1421A.class);
+ }
+
+ public void testWithSingleString() throws Exception {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ Bean1421B> a = objectMapper.readValue(quote(""test2""),
+ new TypeReference>>() {});
+ List expected = new ArrayList<>();
+ expected.add(""test2"");
+ assertEquals(expected, a.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object deserializeFromBoolean(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ if (_delegateDeserializer != null) {
+ if (!_valueInstantiator.canCreateFromBoolean()) {
+ Object bean = _valueInstantiator.createUsingDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ }
+ }
+ boolean value = (p.getCurrentToken() == JsonToken.VALUE_TRUE);
+ return _valueInstantiator.createFromBoolean(ctxt, value);
+ }
+
+// Test Case
+[/INST]
+ public void testSuccessfulDeserializationOfObjectWithChainedArrayCreators() throws IOException
+ {
+ MAPPER.readValue(JSON, Bean1421A.class);
+ }
+
+ public void testWithSingleString() throws Exception {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ Bean1421B> a = objectMapper.readValue(quote(""test2""),
+ new TypeReference>>() {});
+ List expected = new ArrayList<>();
+ expected.add(""test2"");
+ assertEquals(expected, a.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object deserializeFromArray(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ // note: can not call `_delegateDeserializer()` since order reversed here:
+ if (_arrayDelegateDeserializer != null) {
+ try {
+ Object bean = _valueInstantiator.createUsingArrayDelegate(ctxt, _arrayDelegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ } catch (Exception e) {
+ return wrapInstantiationProblem(e, ctxt);
+ }
+ }
+ // fallback to non-array delegate
+ if (_delegateDeserializer != null) {
+ try {
+ Object bean = _valueInstantiator.createUsingArrayDelegate(ctxt,
+ _delegateDeserializer.deserialize(p, ctxt));
+ if (_injectables != null) {
+ injectValues(ctxt, bean);
+ }
+ return bean;
+ } catch (Exception e) {
+ wrapInstantiationProblem(e, ctxt);
+ return null;
+ }
+ }
+ if (ctxt.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
+ JsonToken t = p.nextToken();
+ if (t == JsonToken.END_ARRAY && ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)) {
+ return null;
+ }
+ final Object value = deserialize(p, ctxt);
+ if (p.nextToken() != JsonToken.END_ARRAY) {
+ handleMissingEndArrayForSingle(p, ctxt);
+ }
+ return value;
+ }
+ if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)) {
+ JsonToken t = p.nextToken();
+ if (t == JsonToken.END_ARRAY) {
+ return null;
+ }
+ return ctxt.handleUnexpectedToken(handledType(),
+ JsonToken.START_ARRAY, p, null);
+ }
+ return ctxt.handleUnexpectedToken(handledType(), p);
+ }
+
+// Test Case
+[/INST]
+ public void testSuccessfulDeserializationOfObjectWithChainedArrayCreators() throws IOException
+ {
+ MAPPER.readValue(JSON, Bean1421A.class);
+ }
+
+ public void testWithSingleString() throws Exception {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+ Bean1421B> a = objectMapper.readValue(quote(""test2""),
+ new TypeReference>>() {});
+ List expected = new ArrayList<>();
+ expected.add(""test2"");
+ assertEquals(expected, a.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void addDelegatingCreator(AnnotatedWithParams creator, boolean explicit,
+ SettableBeanProperty[] injectables)
+ {
+ if (creator.getParameterType(0).isCollectionLikeType()) {
+ verifyNonDup(creator, C_ARRAY_DELEGATE, explicit);
+ _arrayDelegateArgs = injectables;
+ } else {
+ verifyNonDup(creator, C_DELEGATE, explicit);
+ _delegateArgs = injectables;
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testConstructorChoice() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ SimplePojo pojo = mapper.readValue(""{ \""intField\"": 1, \""stringField\"": \""foo\"" }"", SimplePojo.class);
+
+ assertEquals(1, pojo.getIntField());
+ assertEquals(""foo"", pojo.getStringField());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void addPropertyCreator(AnnotatedWithParams creator, boolean explicit,
+ SettableBeanProperty[] properties)
+ {
+ verifyNonDup(creator, C_PROPS, explicit);
+ // Better ensure we have no duplicate names either...
+ if (properties.length > 1) {
+ HashMap names = new HashMap();
+ for (int i = 0, len = properties.length; i < len; ++i) {
+ String name = properties[i].getName();
+ /* [Issue-13]: Need to consider Injectables, which may not have
+ * a name at all, and need to be skipped
+ */
+ if (name.length() == 0 && properties[i].getInjectableValueId() != null) {
+ continue;
+ }
+ Integer old = names.put(name, Integer.valueOf(i));
+ if (old != null) {
+ throw new IllegalArgumentException(""Duplicate creator property \""""+name+""\"" (index ""+old+"" vs ""+i+"")"");
+ }
+ }
+ }
+ _propertyBasedArgs = properties;
+ }
+
+// Test Case
+[/INST]
+ public void testConstructorChoice() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ SimplePojo pojo = mapper.readValue(""{ \""intField\"": 1, \""stringField\"": \""foo\"" }"", SimplePojo.class);
+
+ assertEquals(1, pojo.getIntField());
+ assertEquals(""foo"", pojo.getStringField());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)
+ {
+ final int mask = (1 << typeIndex);
+ _hasNonDefaultCreator = true;
+ AnnotatedWithParams oldOne = _creators[typeIndex];
+ // already had an explicitly marked one?
+ if (oldOne != null) {
+ boolean verify;
+ if ((_explicitCreators & mask) != 0) { // already had explicitly annotated, leave as-is
+ // but skip, if new one not annotated
+ if (!explicit) {
+ return;
+ }
+ // both explicit: verify
+ verify = true;
+ } else {
+ // otherwise only verify if neither explicitly annotated.
+ verify = !explicit;
+ }
+
+ // one more thing: ok to override in sub-class
+ if (verify && (oldOne.getClass() == newOne.getClass())) {
+ // [databind#667]: avoid one particular class of bogus problems
+ Class> oldType = oldOne.getRawParameterType(0);
+ Class> newType = newOne.getRawParameterType(0);
+
+ if (oldType == newType) {
+ throw new IllegalArgumentException(""Conflicting ""+TYPE_DESCS[typeIndex]
+ +"" creators: already had explicitly marked ""+oldOne+"", encountered ""+newOne);
+ }
+ // otherwise, which one to choose?
+ if (newType.isAssignableFrom(oldType)) {
+ // new type more generic, use old
+ return;
+ }
+ // new type more specific, use it
+ }
+ }
+ if (explicit) {
+ _explicitCreators |= mask;
+ }
+ _creators[typeIndex] = _fixAccess(newOne);
+ }
+
+// Test Case
+[/INST]
+ public void testConstructorChoice() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ SimplePojo pojo = mapper.readValue(""{ \""intField\"": 1, \""stringField\"": \""foo\"" }"", SimplePojo.class);
+
+ assertEquals(1, pojo.getIntField());
+ assertEquals(""foo"", pojo.getStringField());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
+ {
+ copyCurrentStructure(jp);
+ /* 28-Oct-2014, tatu: As per #592, need to support a special case of starting from
+ * FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need
+ * to assume one did exist.
+ */
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testDelegateWithTokenBuffer() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ Value592 value = mapper.readValue(""{\""a\"":1,\""b\"":2}"", Value592.class);
+ assertNotNull(value);
+ Object ob = value.stuff;
+ assertEquals(TokenBuffer.class, ob.getClass());
+ JsonParser jp = ((TokenBuffer) ob).asParser();
+ assertToken(JsonToken.START_OBJECT, jp.nextToken());
+ assertToken(JsonToken.FIELD_NAME, jp.nextToken());
+ assertEquals(""a"", jp.getCurrentName());
+ assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
+ assertEquals(1, jp.getIntValue());
+ assertToken(JsonToken.FIELD_NAME, jp.nextToken());
+ assertEquals(""b"", jp.getCurrentName());
+ assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
+ assertEquals(2, jp.getIntValue());
+ assertToken(JsonToken.END_OBJECT, jp.nextToken());
+ jp.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void remove(SettableBeanProperty propToRm)
+ {
+ ArrayList props = new ArrayList(_size);
+ String key = getPropertyName(propToRm);
+ boolean found = false;
+
+ for (int i = 1, end = _hashArea.length; i < end; i += 2) {
+ SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];
+ if (prop == null) {
+ continue;
+ }
+ if (!found) {
+ // 09-Jan-2017, tatu: Important: must check name slot and NOT property name,
+ // as only former is lower-case in case-insensitive case
+ found = key.equals(prop.getName());
+ if (found) {
+ // need to leave a hole here
+ _propsInOrder[_findFromOrdered(prop)] = null;
+ continue;
+ }
+ }
+ props.add(prop);
+ }
+ if (!found) {
+ throw new NoSuchElementException(""No entry '""+propToRm.getName()+""' found, can't remove"");
+ }
+ init(props);
+ }
+
+// Test Case
+[/INST]
+ public void testCaseInsensitiveUnwrap() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
+ Person p = mapper.readValue(""{ }"", Person.class);
+ assertNotNull(p);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public static StdKeyDeserializer forType(Class> raw)
+ {
+ int kind;
+
+ // first common types:
+ if (raw == String.class || raw == Object.class) {
+ return StringKD.forType(raw);
+ } else if (raw == UUID.class) {
+ kind = TYPE_UUID;
+ } else if (raw == Integer.class) {
+ kind = TYPE_INT;
+ } else if (raw == Long.class) {
+ kind = TYPE_LONG;
+ } else if (raw == Date.class) {
+ kind = TYPE_DATE;
+ } else if (raw == Calendar.class) {
+ kind = TYPE_CALENDAR;
+ // then less common ones...
+ } else if (raw == Boolean.class) {
+ kind = TYPE_BOOLEAN;
+ } else if (raw == Byte.class) {
+ kind = TYPE_BYTE;
+ } else if (raw == Character.class) {
+ kind = TYPE_CHAR;
+ } else if (raw == Short.class) {
+ kind = TYPE_SHORT;
+ } else if (raw == Float.class) {
+ kind = TYPE_FLOAT;
+ } else if (raw == Double.class) {
+ kind = TYPE_DOUBLE;
+ } else if (raw == URI.class) {
+ kind = TYPE_URI;
+ } else if (raw == URL.class) {
+ kind = TYPE_URL;
+ } else if (raw == Class.class) {
+ kind = TYPE_CLASS;
+ } else if (raw == Locale.class) {
+ FromStringDeserializer> deser = FromStringDeserializer.findDeserializer(Locale.class);
+ return new StdKeyDeserializer(TYPE_LOCALE, raw, deser);
+ } else if (raw == Currency.class) {
+ FromStringDeserializer> deser = FromStringDeserializer.findDeserializer(Currency.class);
+ return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser);
+ } else {
+ return null;
+ }
+ return new StdKeyDeserializer(kind, raw);
+ }
+
+// Test Case
+[/INST]
+ public void testcharSequenceKeyMap() throws Exception {
+ String JSON = aposToQuotes(""{'a':'b'}"");
+ Map result = MAPPER.readValue(JSON, new TypeReference"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ Object writeReplace() {
+ // need to construct a fake instance to support serialization
+ if (_annotated != null) {
+ return this;
+ }
+ return new InnerClassProperty(this, new AnnotatedConstructor(null, _creator, null, null));
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1501() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
+ String ser = mapper.writeValueAsString(new Something());
+ mapper.readValue(ser, Something.class);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void removeNonVisible(boolean inferMutators)
+ {
+ /* 07-Jun-2015, tatu: With 2.6, we will allow optional definition
+ * of explicit access type for property; if not ""AUTO"", it will
+ * dictate how visibility checks are applied.
+ */
+ JsonProperty.Access acc = findAccess();
+ if (acc == null) {
+ acc = JsonProperty.Access.AUTO;
+ }
+ switch (acc) {
+ case READ_ONLY:
+ // Remove setters, creators for sure, but fields too if deserializing
+ _setters = null;
+ _ctorParameters = null;
+ if (!_forSerialization) {
+ _fields = null;
+ }
+ break;
+ case READ_WRITE:
+ // no trimming whatsoever?
+ break;
+ case WRITE_ONLY:
+ // remove getters, definitely, but also fields if serializing
+ _getters = null;
+ if (_forSerialization) {
+ _fields = null;
+ }
+ break;
+ default:
+ case AUTO: // the default case: base it on visibility
+ _getters = _removeNonVisible(_getters);
+ _ctorParameters = _removeNonVisible(_ctorParameters);
+
+ if (!inferMutators || (_getters == null)) {
+ _fields = _removeNonVisible(_fields);
+ _setters = _removeNonVisible(_setters);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testReadOnlyAndWriteOnly() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new ReadXWriteY());
+ assertEquals(""{\""x\"":1}"", json);
+
+ ReadXWriteY result = MAPPER.readValue(""{\""x\"":5, \""y\"":6}"", ReadXWriteY.class);
+ assertNotNull(result);
+ assertEquals(1, result.x);
+ assertEquals(6, result.y);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _removeUnwantedAccessor(Map props)
+ {
+ final boolean inferMutators = _config.isEnabled(MapperFeature.INFER_PROPERTY_MUTATORS);
+ Iterator it = props.values().iterator();
+
+ while (it.hasNext()) {
+ POJOPropertyBuilder prop = it.next();
+ // 26-Jan-2017, tatu: [databind#935]: need to denote removal of
+ prop.removeNonVisible(inferMutators);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testReadOnlyAndWriteOnly() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new ReadXWriteY());
+ assertEquals(""{\""x\"":1}"", json);
+
+ ReadXWriteY result = MAPPER.readValue(""{\""x\"":5, \""y\"":6}"", ReadXWriteY.class);
+ assertNotNull(result);
+ assertEquals(1, result.x);
+ assertEquals(6, result.y);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt,
+ TokenBuffer tb) throws IOException
+ {
+ // As per [JACKSON-614], may have default implementation to use
+ JsonDeserializer deser = _findDefaultImplDeserializer(ctxt);
+ if (deser != null) {
+ if (tb != null) {
+ tb.writeEndObject();
+ p = tb.asParser(p);
+ // must move to point to the first token:
+ p.nextToken();
+ }
+ return deser.deserialize(p, ctxt);
+ }
+ // or, perhaps we just bumped into a ""natural"" value (boolean/int/double/String)?
+ Object result = TypeDeserializer.deserializeIfNatural(p, ctxt, _baseType);
+ if (result != null) {
+ return result;
+ }
+ // or, something for which ""as-property"" won't work, changed into ""wrapper-array"" type:
+ if (p.getCurrentToken() == JsonToken.START_ARRAY) {
+ return super.deserializeTypedFromAny(p, ctxt);
+ }
+ ctxt.reportWrongTokenException(p, JsonToken.FIELD_NAME,
+ ""missing property '""+_typePropertyName+""' that is to contain type id (for class ""+baseTypeName()+"")"");
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testWithEmptyStringAsNullObject1533() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
+ AsPropertyWrapper wrapper = mapper.readValue(""{ \""value\"": \""\"" }"", AsPropertyWrapper.class);
+ assertNull(wrapper.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""unchecked"")
+ public static EnumSerializer construct(Class> enumClass, SerializationConfig config,
+ BeanDescription beanDesc, JsonFormat.Value format)
+ {
+ /* 08-Apr-2015, tatu: As per [databind#749], we can not statically determine
+ * between name() and toString(), need to construct `EnumValues` with names,
+ * handle toString() case dynamically (for example)
+ */
+ EnumValues v = EnumValues.constructFromName(config, (Class>) enumClass);
+ Boolean serializeAsIndex = _isShapeWrittenUsingIndex(enumClass, format, true);
+ return new EnumSerializer(v, serializeAsIndex);
+ }
+
+// Test Case
+[/INST]
+ public void testEnumPropertyAsNumber() throws Exception {
+ assertEquals(String.format(aposToQuotes(""{'color':%s}""), Color.GREEN.ordinal()),
+ MAPPER.writeValueAsString(new ColorWrapper(Color.GREEN)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonSerializer> createContextual(SerializerProvider serializers,
+ BeanProperty property) throws JsonMappingException
+ {
+ if (property != null) {
+ JsonFormat.Value format = findFormatOverrides(serializers,
+ property, handledType());
+ if (format != null) {
+ Boolean serializeAsIndex = _isShapeWrittenUsingIndex(property.getType().getRawClass(),
+ format, false);
+ if (serializeAsIndex != _serializeAsIndex) {
+ return new EnumSerializer(_values, serializeAsIndex);
+ }
+ }
+ }
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testEnumPropertyAsNumber() throws Exception {
+ assertEquals(String.format(aposToQuotes(""{'color':%s}""), Color.GREEN.ordinal()),
+ MAPPER.writeValueAsString(new ColorWrapper(Color.GREEN)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected static Boolean _isShapeWrittenUsingIndex(Class> enumClass,
+ JsonFormat.Value format, boolean fromClass)
+ {
+ JsonFormat.Shape shape = (format == null) ? null : format.getShape();
+ if (shape == null) {
+ return null;
+ }
+ // i.e. ""default"", check dynamically
+ if (shape == Shape.ANY || shape == Shape.SCALAR) {
+ return null;
+ }
+ // 19-May-2016, tatu: also consider ""natural"" shape
+ if (shape == Shape.STRING || shape == Shape.NATURAL) {
+ return Boolean.FALSE;
+ }
+ // 01-Oct-2014, tatu: For convenience, consider ""as-array"" to also mean 'yes, use index')
+ if (shape.isNumeric() || (shape == Shape.ARRAY)) {
+ return Boolean.TRUE;
+ }
+ // 07-Mar-2017, tatu: Also means `OBJECT` not available as property annotation...
+ throw new IllegalArgumentException(String.format(
+ ""Unsupported serialization shape (%s) for Enum %s, not supported as %s annotation"",
+ shape, enumClass.getName(), (fromClass? ""class"" : ""property"")));
+ }
+
+// Test Case
+[/INST]
+ public void testEnumPropertyAsNumber() throws Exception {
+ assertEquals(String.format(aposToQuotes(""{'color':%s}""), Color.GREEN.ordinal()),
+ MAPPER.writeValueAsString(new ColorWrapper(Color.GREEN)));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,
+ DeserializationContext ctxt)
+ throws IOException, JsonProcessingException
+ {
+ final PropertyBasedCreator creator = _propertyBasedCreator;
+ PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
+
+ TokenBuffer tokens = new TokenBuffer(p, ctxt);
+ tokens.writeStartObject();
+
+ JsonToken t = p.getCurrentToken();
+ for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
+ String propName = p.getCurrentName();
+ p.nextToken(); // to point to value
+ // creator property?
+ SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
+ if (creatorProp != null) {
+ if (buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt))) {
+ t = p.nextToken();
+ Object bean;
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
+ continue;
+ }
+ while (t == JsonToken.FIELD_NAME) {
+ p.nextToken();
+ tokens.copyCurrentStructure(p);
+ t = p.nextToken();
+ }
+ tokens.writeEndObject();
+ if (bean.getClass() != _beanType.getRawClass()) {
+ ctxt.reportMappingException(""Can not create polymorphic instances with unwrapped values"");
+ return null;
+ }
+ return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
+ }
+ continue;
+ }
+ // Object Id property?
+ if (buffer.readIdProperty(propName)) {
+ continue;
+ }
+ // regular property? needs buffering
+ SettableBeanProperty prop = _beanProperties.find(propName);
+ if (prop != null) {
+ buffer.bufferProperty(prop, prop.deserialize(p, ctxt));
+ continue;
+ }
+ if (_ignorableProps != null && _ignorableProps.contains(propName)) {
+ handleIgnoredProperty(p, ctxt, handledType(), propName);
+ continue;
+ }
+ tokens.writeFieldName(propName);
+ tokens.copyCurrentStructure(p);
+ // ""any property""?
+ if (_anySetter != null) {
+ buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
+ }
+ }
+
+ // We hit END_OBJECT, so:
+ Object bean;
+ // !!! 15-Feb-2012, tatu: Need to modify creator to use Builder!
+ try {
+ bean = creator.build(ctxt, buffer);
+ } catch (Exception e) {
+ return wrapInstantiationProblem(e, ctxt);
+ }
+ return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
+ }
+
+// Test Case
+[/INST]
+ public void testWithUnwrappedAndCreatorSingleParameterAtBeginning() throws Exception {
+ final String json = aposToQuotes(""{'person_id':1234,'first_name':'John','last_name':'Doe','years_old':30,'living':true}"");
+
+ final ObjectMapper mapper = new ObjectMapper();
+ Person person = mapper.readValue(json, Person.class);
+ assertEquals(1234, person.getId());
+ assertNotNull(person.getName());
+ assertEquals(""John"", person.getName().getFirst());
+ assertEquals(""Doe"", person.getName().getLast());
+ assertEquals(30, person.getAge());
+ assertEquals(true, person.isAlive());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonDeserializer createBeanDeserializer(DeserializationContext ctxt,
+ JavaType type, BeanDescription beanDesc)
+ throws JsonMappingException
+ {
+ final DeserializationConfig config = ctxt.getConfig();
+ // We may also have custom overrides:
+ JsonDeserializer custom = _findCustomBeanDeserializer(type, config, beanDesc);
+ if (custom != null) {
+ return custom;
+ }
+ /* One more thing to check: do we have an exception type
+ * (Throwable or its sub-classes)? If so, need slightly
+ * different handling.
+ */
+ if (type.isThrowable()) {
+ return buildThrowableDeserializer(ctxt, type, beanDesc);
+ }
+ /* Or, for abstract types, may have alternate means for resolution
+ * (defaulting, materialization)
+ */
+ // 29-Nov-2015, tatu: Also, filter out calls to primitive types, they are
+ // not something we could materialize anything for
+ if (type.isAbstract() && !type.isPrimitive()) {
+ // Let's make it possible to materialize abstract types.
+ JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc);
+ if (concreteType != null) {
+ /* important: introspect actual implementation (abstract class or
+ * interface doesn't have constructors, for one)
+ */
+ beanDesc = config.introspect(concreteType);
+ return buildBeanDeserializer(ctxt, concreteType, beanDesc);
+ }
+ }
+
+ // Otherwise, may want to check handlers for standard types, from superclass:
+ @SuppressWarnings(""unchecked"")
+ JsonDeserializer deser = (JsonDeserializer) findStdDeserializer(ctxt, type, beanDesc);
+ if (deser != null) {
+ return deser;
+ }
+
+ // Otherwise: could the class be a Bean class? If not, bail out
+ if (!isPotentialBeanType(type.getRawClass())) {
+ return null;
+ }
+ // For checks like [databind#1599]
+ // Use generic bean introspection to build deserializer
+ return buildBeanDeserializer(ctxt, type, beanDesc);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1599() throws Exception
+ {
+ final String JSON = aposToQuotes(
+ ""{'id': 124,\n""
++"" 'obj':[ 'com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl',\n""
++"" {\n""
++"" 'transletBytecodes' : [ 'AAIAZQ==' ],\n""
++"" 'transletName' : 'a.b',\n""
++"" 'outputProperties' : { }\n""
++"" }\n""
++"" ]\n""
++""}""
+ );
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enableDefaultTyping();
+ try {
+ mapper.readValue(JSON, Bean1599.class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Illegal type"");
+ verifyException(e, ""to deserialize"");
+ verifyException(e, ""prevented for security reasons"");
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JsonDeserializer createBeanDeserializer(DeserializationContext ctxt,
+ JavaType type, BeanDescription beanDesc)
+ throws JsonMappingException
+ {
+ final DeserializationConfig config = ctxt.getConfig();
+ // We may also have custom overrides:
+ JsonDeserializer custom = _findCustomBeanDeserializer(type, config, beanDesc);
+ if (custom != null) {
+ return custom;
+ }
+ /* One more thing to check: do we have an exception type
+ * (Throwable or its sub-classes)? If so, need slightly
+ * different handling.
+ */
+ if (type.isThrowable()) {
+ return buildThrowableDeserializer(ctxt, type, beanDesc);
+ }
+ /* Or, for abstract types, may have alternate means for resolution
+ * (defaulting, materialization)
+ */
+ // 29-Nov-2015, tatu: Also, filter out calls to primitive types, they are
+ // not something we could materialize anything for
+ if (type.isAbstract() && !type.isPrimitive() && !type.isEnumType()) {
+ // Let's make it possible to materialize abstract types.
+ JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc);
+ if (concreteType != null) {
+ /* important: introspect actual implementation (abstract class or
+ * interface doesn't have constructors, for one)
+ */
+ beanDesc = config.introspect(concreteType);
+ return buildBeanDeserializer(ctxt, concreteType, beanDesc);
+ }
+ }
+ // Otherwise, may want to check handlers for standard types, from superclass:
+ @SuppressWarnings(""unchecked"")
+ JsonDeserializer deser = (JsonDeserializer) findStdDeserializer(ctxt, type, beanDesc);
+ if (deser != null) {
+ return deser;
+ }
+
+ // Otherwise: could the class be a Bean class? If not, bail out
+ if (!isPotentialBeanType(type.getRawClass())) {
+ return null;
+ }
+ // For checks like [databind#1599]
+ // Use generic bean introspection to build deserializer
+ return buildBeanDeserializer(ctxt, type, beanDesc);
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1599() throws Exception
+ {
+ final String JSON = aposToQuotes(
+ ""{'id': 124,\n""
++"" 'obj':[ 'com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl',\n""
++"" {\n""
++"" 'transletBytecodes' : [ 'AAIAZQ==' ],\n""
++"" 'transletName' : 'a.b',\n""
++"" 'outputProperties' : { }\n""
++"" }\n""
++"" ]\n""
++""}""
+ );
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enableDefaultTyping();
+ try {
+ mapper.readValue(JSON, Bean1599.class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""Illegal type"");
+ verifyException(e, ""to deserialize"");
+ verifyException(e, ""prevented for security reasons"");
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @SuppressWarnings(""incomplete-switch"")
+ @Override
+ public JsonSerializer> createContextual(SerializerProvider provider,
+ BeanProperty property)
+ throws JsonMappingException
+ {
+ final AnnotationIntrospector intr = provider.getAnnotationIntrospector();
+ final AnnotatedMember accessor = (property == null || intr == null)
+ ? null : property.getMember();
+ final SerializationConfig config = provider.getConfig();
+
+ // Let's start with one big transmutation: Enums that are annotated
+ // to serialize as Objects may want to revert
+ JsonFormat.Shape shape = null;
+ if (accessor != null) {
+ JsonFormat.Value format = intr.findFormat((Annotated) accessor);
+
+ if (format != null) {
+ shape = format.getShape();
+ // or, alternatively, asked to revert ""back to"" other representations...
+ if (shape != _serializationShape) {
+ if (_handledType.isEnum()) {
+ switch (shape) {
+ case STRING:
+ case NUMBER:
+ case NUMBER_INT:
+ // 12-Oct-2014, tatu: May need to introspect full annotations... but
+ // for now, just do class ones
+ BeanDescription desc = config.introspectClassAnnotations(_handledType);
+ JsonSerializer> ser = EnumSerializer.construct(_handledType,
+ provider.getConfig(), desc, format);
+ return provider.handlePrimaryContextualization(ser, property);
+ }
+ }
+ }
+ }
+ }
+
+ ObjectIdWriter oiw = _objectIdWriter;
+ String[] ignorals = null;
+ Object newFilterId = null;
+
+ // Then we may have an override for Object Id
+ if (accessor != null) {
+ ignorals = intr.findPropertiesToIgnore(accessor, true);
+ ObjectIdInfo objectIdInfo = intr.findObjectIdInfo(accessor);
+ if (objectIdInfo == null) {
+ // no ObjectId override, but maybe ObjectIdRef?
+ if (oiw != null) {
+ objectIdInfo = intr.findObjectReferenceInfo(accessor,
+ new ObjectIdInfo(NAME_FOR_OBJECT_REF, null, null, null));
+ oiw = _objectIdWriter.withAlwaysAsId(objectIdInfo.getAlwaysAsId());
+ }
+ } else {
+ // Ugh: mostly copied from BeanDeserializerBase: but can't easily change it
+ // to be able to move to SerializerProvider (where it really belongs)
+
+ // 2.1: allow modifications by ""id ref"" annotations as well:
+ objectIdInfo = intr.findObjectReferenceInfo(accessor, objectIdInfo);
+ ObjectIdGenerator> gen;
+ Class> implClass = objectIdInfo.getGeneratorType();
+ JavaType type = provider.constructType(implClass);
+ JavaType idType = provider.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0];
+ // Property-based generator is trickier
+ if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work
+ String propName = objectIdInfo.getPropertyName().getSimpleName();
+ BeanPropertyWriter idProp = null;
+
+ for (int i = 0, len = _props.length ;; ++i) {
+ if (i == len) {
+ throw new IllegalArgumentException(""Invalid Object Id definition for ""+_handledType.getName()
+ +"": can not find property with name '""+propName+""'"");
+ }
+ BeanPropertyWriter prop = _props[i];
+ if (propName.equals(prop.getName())) {
+ idProp = prop;
+ /* Let's force it to be the first property to output
+ * (although it may still get rearranged etc)
+ */
+ if (i > 0) { // note: must shuffle both regular properties and filtered
+ System.arraycopy(_props, 0, _props, 1, i);
+ _props[0] = idProp;
+ if (_filteredProps != null) {
+ BeanPropertyWriter fp = _filteredProps[i];
+ System.arraycopy(_filteredProps, 0, _filteredProps, 1, i);
+ _filteredProps[0] = fp;
+ }
+ }
+ break;
+ }
+ }
+ idType = idProp.getType();
+ gen = new PropertyBasedObjectIdGenerator(objectIdInfo, idProp);
+ oiw = ObjectIdWriter.construct(idType, (PropertyName) null, gen, objectIdInfo.getAlwaysAsId());
+ } else { // other types need to be simpler
+ gen = provider.objectIdGeneratorInstance(accessor, objectIdInfo);
+ oiw = ObjectIdWriter.construct(idType, objectIdInfo.getPropertyName(), gen,
+ objectIdInfo.getAlwaysAsId());
+ }
+ }
+
+ // Or change Filter Id in use?
+ Object filterId = intr.findFilterId(accessor);
+ if (filterId != null) {
+ // but only consider case of adding a new filter id (no removal via annotation)
+ if (_propertyFilterId == null || !filterId.equals(_propertyFilterId)) {
+ newFilterId = filterId;
+ }
+ }
+ }
+ // either way, need to resolve serializer:
+ BeanSerializerBase contextual = this;
+ if (oiw != null) {
+ JsonSerializer> ser = provider.findValueSerializer(oiw.idType, property);
+ oiw = oiw.withSerializer(ser);
+ if (oiw != _objectIdWriter) {
+ contextual = contextual.withObjectIdWriter(oiw);
+ }
+ }
+ // And possibly add more properties to ignore
+ if (ignorals != null && ignorals.length != 0) {
+ contextual = contextual.withIgnorals(ignorals);
+ }
+ if (newFilterId != null) {
+ contextual = contextual.withFilterId(newFilterId);
+ }
+ if (shape == null) {
+ shape = _serializationShape;
+ }
+ if (shape == JsonFormat.Shape.ARRAY) {
+ return contextual.asArraySerializer();
+ }
+ return contextual;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1607() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new ReallyAlwaysContainer());
+ assertEquals(aposToQuotes(""{'alwaysClass':1,'alwaysProp':2}""), json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo) {
+ JsonIdentityReference ref = _findAnnotation(ann, JsonIdentityReference.class);
+ if (ref != null) {
+ objectIdInfo = objectIdInfo.withAlwaysAsId(ref.alwaysAsId());
+ }
+ return objectIdInfo;
+ }
+
+// Test Case
+[/INST]
+ public void testIssue1607() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new ReallyAlwaysContainer());
+ assertEquals(aposToQuotes(""{'alwaysClass':1,'alwaysProp':2}""), json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testIssue1607() throws Exception
+ {
+ String json = MAPPER.writeValueAsString(new ReallyAlwaysContainer());
+ assertEquals(aposToQuotes(""{'alwaysClass':1,'alwaysProp':2}""), json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)
+ {
+ final int mask = (1 << typeIndex);
+ _hasNonDefaultCreator = true;
+ AnnotatedWithParams oldOne = _creators[typeIndex];
+ // already had an explicitly marked one?
+ if (oldOne != null) {
+
+ if ((_explicitCreators & mask) != 0) { // already had explicitly annotated, leave as-is
+ // but skip, if new one not annotated
+ if (!explicit) {
+ return;
+ }
+ // both explicit: verify
+ // otherwise only verify if neither explicitly annotated.
+ }
+
+ // one more thing: ok to override in sub-class
+ if (oldOne.getClass() == newOne.getClass()) {
+ // [databind#667]: avoid one particular class of bogus problems
+
+ throw new IllegalArgumentException(""Conflicting ""+TYPE_DESCS[typeIndex]
+ +"" creators: already had explicitly marked ""+oldOne+"", encountered ""+newOne);
+ // otherwise, which one to choose?
+ // new type more generic, use old
+ // new type more specific, use it
+ }
+ }
+ if (explicit) {
+ _explicitCreators |= mask;
+ }
+ _creators[typeIndex] = _fixAccess(newOne);
+ }
+
+// Test Case
+[/INST]
+ public void testStringBuilder() throws Exception
+ {
+ StringBuilder sb = MAPPER.readValue(quote(""abc""), StringBuilder.class);
+ assertEquals(""abc"", sb.toString());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Collection collectAndResolveSubtypesByClass(MapperConfig> config,
+ AnnotatedMember property, JavaType baseType)
+ {
+ final AnnotationIntrospector ai = config.getAnnotationIntrospector();
+ // for backwards compatibility, must allow null here:
+ Class> rawBase = (baseType == null) ? property.getRawType() : baseType.getRawClass();
+
+ HashMap collected = new HashMap();
+ // start with registered subtypes (which have precedence)
+ if (_registeredSubtypes != null) {
+ for (NamedType subtype : _registeredSubtypes) {
+ // is it a subtype of root type?
+ if (rawBase.isAssignableFrom(subtype.getType())) { // yes
+ AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config,
+ subtype.getType());
+ _collectAndResolve(curr, subtype, config, ai, collected);
+ }
+ }
+ }
+
+ // then annotated types for property itself
+ Collection st = ai.findSubtypes(property);
+ if (st != null) {
+ for (NamedType nt : st) {
+ AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config,
+ nt.getType());
+ _collectAndResolve(ac, nt, config, ai, collected);
+ }
+ }
+
+ NamedType rootType = new NamedType(rawBase, null);
+ AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config, rawBase);
+
+ // and finally subtypes via annotations from base type (recursively)
+ _collectAndResolve(ac, rootType, config, ai, collected);
+
+ return new ArrayList(collected.values());
+ }
+
+// Test Case
+[/INST]
+ public void testBaseTypeId1616() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ Collection subtypes = new StdSubtypeResolver().collectAndResolveSubtypesByTypeId(
+ mapper.getDeserializationConfig(),
+ // note: `null` is fine here as `AnnotatedMember`:
+ null,
+ mapper.constructType(Base1616.class));
+ assertEquals(2, subtypes.size());
+ Set ok = new HashSet<>(Arrays.asList(""A"", ""B""));
+ for (NamedType type : subtypes) {
+ String id = type.getName();
+ if (!ok.contains(id)) {
+ fail(""Unexpected id '""+id+""' (mapping to: ""+type.getType()+""), should be one of: ""+ok);
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public Collection collectAndResolveSubtypesByTypeId(MapperConfig> config,
+ AnnotatedMember property, JavaType baseType)
+ {
+ final AnnotationIntrospector ai = config.getAnnotationIntrospector();
+ Class> rawBase = baseType.getRawClass();
+
+ // Need to keep track of classes that have been handled already
+ Set> typesHandled = new HashSet>();
+ Map byName = new LinkedHashMap();
+
+ // start with lowest-precedence, which is from type hierarchy
+ NamedType rootType = new NamedType(rawBase, null);
+ AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config,
+ rawBase);
+ _collectAndResolveByTypeId(ac, rootType, config, typesHandled, byName);
+
+ // then with definitions from property
+ Collection st = ai.findSubtypes(property);
+ if (st != null) {
+ for (NamedType nt : st) {
+ ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config, nt.getType());
+ _collectAndResolveByTypeId(ac, nt, config, typesHandled, byName);
+ }
+ }
+ // and finally explicit type registrations (highest precedence)
+ if (_registeredSubtypes != null) {
+ for (NamedType subtype : _registeredSubtypes) {
+ // is it a subtype of root type?
+ if (rawBase.isAssignableFrom(subtype.getType())) { // yes
+ AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config,
+ subtype.getType());
+ _collectAndResolveByTypeId(curr, subtype, config, typesHandled, byName);
+ }
+ }
+ }
+ return _combineNamedAndUnnamed(rawBase, typesHandled, byName);
+ }
+
+// Test Case
+[/INST]
+ public void testBaseTypeId1616() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ Collection subtypes = new StdSubtypeResolver().collectAndResolveSubtypesByTypeId(
+ mapper.getDeserializationConfig(),
+ // note: `null` is fine here as `AnnotatedMember`:
+ null,
+ mapper.constructType(Base1616.class));
+ assertEquals(2, subtypes.size());
+ Set ok = new HashSet<>(Arrays.asList(""A"", ""B""));
+ for (NamedType type : subtypes) {
+ String id = type.getName();
+ if (!ok.contains(id)) {
+ fail(""Unexpected id '""+id+""' (mapping to: ""+type.getType()+""), should be one of: ""+ok);
+ }
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JavaType refineSerializationType(final MapperConfig> config,
+ final Annotated a, final JavaType baseType) throws JsonMappingException
+ {
+ JavaType type = baseType;
+ final TypeFactory tf = config.getTypeFactory();
+
+ final JsonSerialize jsonSer = _findAnnotation(a, JsonSerialize.class);
+
+ // Ok: start by refining the main type itself; common to all types
+
+ final Class> serClass = (jsonSer == null) ? null : _classIfExplicit(jsonSer.as());
+ if (serClass != null) {
+ if (type.hasRawClass(serClass)) {
+ // 30-Nov-2015, tatu: As per [databind#1023], need to allow forcing of
+ // static typing this way
+ type = type.withStaticTyping();
+ } else {
+ Class> currRaw = type.getRawClass();
+ try {
+ // 11-Oct-2015, tatu: For deser, we call `TypeFactory.constructSpecializedType()`,
+ // may be needed here too in future?
+ if (serClass.isAssignableFrom(currRaw)) { // common case
+ type = tf.constructGeneralizedType(type, serClass);
+ } else if (currRaw.isAssignableFrom(serClass)) { // specialization, ok as well
+ type = tf.constructSpecializedType(type, serClass);
+ // 27-Apr-2017, tatu: [databind#1592] ignore primitive<->wrapper refinements
+ } else {
+ throw new JsonMappingException(null,
+ String.format(""Can not refine serialization type %s into %s; types not related"",
+ type, serClass.getName()));
+ }
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to widen type %s with annotation (value %s), from '%s': %s"",
+ type, serClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ }
+ // Then further processing for container types
+
+ // First, key type (for Maps, Map-like types):
+ if (type.isMapLikeType()) {
+ JavaType keyType = type.getKeyType();
+ final Class> keyClass = (jsonSer == null) ? null : _classIfExplicit(jsonSer.keyAs());
+ if (keyClass != null) {
+ if (keyType.hasRawClass(keyClass)) {
+ keyType = keyType.withStaticTyping();
+ } else {
+ Class> currRaw = keyType.getRawClass();
+ try {
+ // 19-May-2016, tatu: As per [databind#1231], [databind#1178] may need to actually
+ // specialize (narrow) type sometimes, even if more commonly opposite
+ // is needed.
+ if (keyClass.isAssignableFrom(currRaw)) { // common case
+ keyType = tf.constructGeneralizedType(keyType, keyClass);
+ } else if (currRaw.isAssignableFrom(keyClass)) { // specialization, ok as well
+ keyType = tf.constructSpecializedType(keyType, keyClass);
+ // 27-Apr-2017, tatu: [databind#1592] ignore primitive<->wrapper refinements
+ } else {
+ throw new JsonMappingException(null,
+ String.format(""Can not refine serialization key type %s into %s; types not related"",
+ keyType, keyClass.getName()));
+ }
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s"",
+ type, keyClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ type = ((MapLikeType) type).withKeyType(keyType);
+ }
+ }
+
+ JavaType contentType = type.getContentType();
+ if (contentType != null) { // collection[like], map[like], array, reference
+ // And then value types for all containers:
+ final Class> contentClass = (jsonSer == null) ? null : _classIfExplicit(jsonSer.contentAs());
+ if (contentClass != null) {
+ if (contentType.hasRawClass(contentClass)) {
+ contentType = contentType.withStaticTyping();
+ } else {
+ // 03-Apr-2016, tatu: As per [databind#1178], may need to actually
+ // specialize (narrow) type sometimes, even if more commonly opposite
+ // is needed.
+ Class> currRaw = contentType.getRawClass();
+ try {
+ if (contentClass.isAssignableFrom(currRaw)) { // common case
+ contentType = tf.constructGeneralizedType(contentType, contentClass);
+ } else if (currRaw.isAssignableFrom(contentClass)) { // specialization, ok as well
+ contentType = tf.constructSpecializedType(contentType, contentClass);
+ // 27-Apr-2017, tatu: [databind#1592] ignore primitive<->wrapper refinements
+ } else {
+ throw new JsonMappingException(null,
+ String.format(""Can not refine serialization content type %s into %s; types not related"",
+ contentType, contentClass.getName()));
+ }
+ } catch (IllegalArgumentException iae) { // shouldn't really happen
+ throw new JsonMappingException(null,
+ String.format(""Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s"",
+ type, contentClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ type = type.withContentType(contentType);
+ }
+ }
+ return type;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeCoercion1592() throws Exception
+ {
+ // first, serialize
+ MAPPER.writeValueAsString(new Bean1592());
+ Bean1592 result = MAPPER.readValue(""{}"", Bean1592.class);
+ assertNotNull(result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ @Override
+ public JavaType refineDeserializationType(final MapperConfig> config,
+ final Annotated a, final JavaType baseType) throws JsonMappingException
+ {
+ JavaType type = baseType;
+ final TypeFactory tf = config.getTypeFactory();
+
+ final JsonDeserialize jsonDeser = _findAnnotation(a, JsonDeserialize.class);
+
+ // Ok: start by refining the main type itself; common to all types
+ final Class> valueClass = (jsonDeser == null) ? null : _classIfExplicit(jsonDeser.as());
+ if ((valueClass != null) && !type.hasRawClass(valueClass)) {
+ try {
+ type = tf.constructSpecializedType(type, valueClass);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to narrow type %s with annotation (value %s), from '%s': %s"",
+ type, valueClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ // Then further processing for container types
+
+ // First, key type (for Maps, Map-like types):
+ if (type.isMapLikeType()) {
+ JavaType keyType = type.getKeyType();
+ final Class> keyClass = (jsonDeser == null) ? null : _classIfExplicit(jsonDeser.keyAs());
+ if (keyClass != null) {
+ try {
+ keyType = tf.constructSpecializedType(keyType, keyClass);
+ type = ((MapLikeType) type).withKeyType(keyType);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to narrow key type of %s with concrete-type annotation (value %s), from '%s': %s"",
+ type, keyClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ }
+ JavaType contentType = type.getContentType();
+ if (contentType != null) { // collection[like], map[like], array, reference
+ // And then value types for all containers:
+ final Class> contentClass = (jsonDeser == null) ? null : _classIfExplicit(jsonDeser.contentAs());
+ if (contentClass != null) {
+ try {
+ contentType = tf.constructSpecializedType(contentType, contentClass);
+ type = type.withContentType(contentType);
+ } catch (IllegalArgumentException iae) {
+ throw new JsonMappingException(null,
+ String.format(""Failed to narrow value type of %s with concrete-type annotation (value %s), from '%s': %s"",
+ type, contentClass.getName(), a.getName(), iae.getMessage()),
+ iae);
+ }
+ }
+ }
+ return type;
+ }
+
+// Test Case
+[/INST]
+ public void testTypeCoercion1592() throws Exception
+ {
+ // first, serialize
+ MAPPER.writeValueAsString(new Bean1592());
+ Bean1592 result = MAPPER.readValue(""{}"", Bean1592.class);
+ assertNotNull(result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void addBeanProps(DeserializationContext ctxt,
+ BeanDescription beanDesc, BeanDeserializerBuilder builder)
+ throws JsonMappingException
+ {
+ final boolean isConcrete = !beanDesc.getType().isAbstract();
+ final SettableBeanProperty[] creatorProps = isConcrete
+ ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())
+ : null;
+ final boolean hasCreatorProps = (creatorProps != null);
+
+ // 01-May-2016, tatu: Which base type to use here gets tricky, since
+ // it may often make most sense to use general type for overrides,
+ // but what we have here may be more specific impl type. But for now
+ // just use it as is.
+ JsonIgnoreProperties.Value ignorals = ctxt.getConfig()
+ .getDefaultPropertyIgnorals(beanDesc.getBeanClass(),
+ beanDesc.getClassInfo());
+ Set ignored;
+
+ if (ignorals != null) {
+ boolean ignoreAny = ignorals.getIgnoreUnknown();
+ builder.setIgnoreUnknownProperties(ignoreAny);
+ // Or explicit/implicit definitions?
+ ignored = ignorals.getIgnored();
+ for (String propName : ignored) {
+ builder.addIgnorable(propName);
+ }
+ } else {
+ ignored = Collections.emptySet();
+ }
+
+ // Also, do we have a fallback ""any"" setter?
+ AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();
+ AnnotatedMember anySetterField = null;
+ if (anySetterMethod != null) {
+ builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));
+ }
+ else {
+ anySetterField = beanDesc.findAnySetterField();
+ if(anySetterField != null) {
+ builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));
+ }
+ }
+ // NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter
+ // Implicit ones via @JsonIgnore and equivalent?
+ if (anySetterMethod == null && anySetterField == null) {
+ Collection ignored2 = beanDesc.getIgnoredPropertyNames();
+ if (ignored2 != null) {
+ for (String propName : ignored2) {
+ // allow ignoral of similarly named JSON property, but do not force;
+ // latter means NOT adding this to 'ignored':
+ builder.addIgnorable(propName);
+ }
+ }
+ }
+ final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
+ && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);
+
+ // Ok: let's then filter out property definitions
+ List propDefs = filterBeanProps(ctxt,
+ beanDesc, builder, beanDesc.findProperties(), ignored);
+
+ // After which we can let custom code change the set
+ if (_factoryConfig.hasDeserializerModifiers()) {
+ for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
+ propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
+ }
+ }
+
+ // At which point we still have all kinds of properties; not all with mutators:
+ for (BeanPropertyDefinition propDef : propDefs) {
+ SettableBeanProperty prop = null;
+ /* 18-Oct-2013, tatu: Although constructor parameters have highest precedence,
+ * we need to do linkage (as per [databind#318]), and so need to start with
+ * other types, and only then create constructor parameter, if any.
+ */
+ if (propDef.hasSetter()) {
+ JavaType propertyType = propDef.getSetter().getParameterType(0);
+ prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
+ } else if (propDef.hasField()) {
+ JavaType propertyType = propDef.getField().getType();
+ prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
+ } else if (useGettersAsSetters && propDef.hasGetter()) {
+ /* May also need to consider getters
+ * for Map/Collection properties; but with lowest precedence
+ */
+ AnnotatedMethod getter = propDef.getGetter();
+ // should only consider Collections and Maps, for now?
+ Class> rawPropertyType = getter.getRawType();
+ if (Collection.class.isAssignableFrom(rawPropertyType)
+ || Map.class.isAssignableFrom(rawPropertyType)) {
+ prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
+ }
+ }
+ // 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types
+ // (since they are never used anyway)
+ if (hasCreatorProps && propDef.hasConstructorParameter()) {
+ /* If property is passed via constructor parameter, we must
+ * handle things in special way. Not sure what is the most optimal way...
+ * for now, let's just call a (new) method in builder, which does nothing.
+ */
+ // but let's call a method just to allow custom builders to be aware...
+ final String name = propDef.getName();
+ CreatorProperty cprop = null;
+ if (creatorProps != null) {
+ for (SettableBeanProperty cp : creatorProps) {
+ if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
+ cprop = (CreatorProperty) cp;
+ break;
+ }
+ }
+ }
+ if (cprop == null) {
+ List n = new ArrayList<>();
+ for (SettableBeanProperty cp : creatorProps) {
+ n.add(cp.getName());
+ }
+ ctxt.reportBadPropertyDefinition(beanDesc, propDef,
+ ""Could not find creator property with name '%s' (known Creator properties: %s)"",
+ name, n);
+ continue;
+ }
+ if (prop != null) {
+ cprop.setFallbackSetter(prop);
+ }
+ prop = cprop;
+ builder.addCreatorProperty(cprop);
+ continue;
+ }
+
+ if (prop != null) {
+ Class>[] views = propDef.findViews();
+ if (views == null) {
+ // one more twist: if default inclusion disabled, need to force empty set of views
+ if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
+ views = NO_VIEWS;
+ }
+ }
+ // one more thing before adding to builder: copy any metadata
+ prop.setViews(views);
+ builder.addProperty(prop);
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testIgnoreGetterNotSetter1595() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ Simple1595 config = new Simple1595();
+ config.setId(123);
+ config.setName(""jack"");
+ String json = mapper.writeValueAsString(config);
+ assertEquals(aposToQuotes(""{'id':123}""), json);
+ Simple1595 des = mapper.readValue(aposToQuotes(""{'id':123,'name':'jack'}""), Simple1595.class);
+ assertEquals(""jack"", des.getName());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
+ {
+ // 22-Sep-2012, tatu: For 2.1, use this new method, may force coercion:
+ String text = p.getValueAsString();
+ if (text != null) { // has String representation
+ if (text.length() == 0 || (text = text.trim()).length() == 0) {
+ // 04-Feb-2013, tatu: Usually should become null; but not always
+ return _deserializeFromEmptyString();
+ }
+ Exception cause = null;
+ try {
+ // 19-May-2017, tatu: Used to require non-null result (assuming `null`
+ // indicated error; but that seems wrong. Should be able to return
+ // `null` as value.
+ if (_deserialize(text, ctxt) != null) {
+ return _deserialize(text, ctxt);
+ }
+ } catch (IllegalArgumentException iae) {
+ cause = iae;
+ } catch (MalformedURLException me) {
+ cause = me;
+ }
+ String msg = ""not a valid textual representation"";
+ if (cause != null) {
+ String m2 = cause.getMessage();
+ if (m2 != null) {
+ msg = msg + "", problem: ""+m2;
+ }
+ }
+ // 05-May-2016, tatu: Unlike most usage, this seems legit, so...
+ JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg);
+ if (cause != null) {
+ e.initCause(cause);
+ }
+ throw e;
+ // nothing to do here, yet? We'll fail anyway
+ }
+ JsonToken t = p.getCurrentToken();
+ // [databind#381]
+ if (t == JsonToken.START_ARRAY) {
+ return _deserializeFromArray(p, ctxt);
+ }
+ if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {
+ // Trivial cases; null to null, instance of type itself returned as is
+ Object ob = p.getEmbeddedObject();
+ if (ob == null) {
+ return null;
+ }
+ if (_valueClass.isAssignableFrom(ob.getClass())) {
+ return (T) ob;
+ }
+ return _deserializeEmbedded(ob, ctxt);
+ }
+ return (T) ctxt.handleUnexpectedToken(_valueClass, p);
+ }
+
+// Test Case
+[/INST]
+ public void testWeirdStringHandling() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper()
+ .addHandler(new WeirdStringHandler(SingleValuedEnum.A))
+ ;
+ SingleValuedEnum result = mapper.readValue(""\""B\"""", SingleValuedEnum.class);
+ assertEquals(SingleValuedEnum.A, result);
+
+ // also, write [databind#1629] try this
+ mapper = new ObjectMapper()
+ .addHandler(new WeirdStringHandler(null));
+ UUID result2 = mapper.readValue(quote(""not a uuid!""), UUID.class);
+ assertNull(result2);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testBasePropertiesIncludedWhenSerializingSubWhenSubTypeLoadedAfterBaseType() throws IOException {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ tf.constructType(Base.class);
+ tf.constructType(Sub.class);
+ Sub sub = new Sub();
+ String serialized = objectMapper().writeValueAsString(sub);
+ assertEquals(""{\""base\"":1,\""sub\"":2}"", serialized);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonSerializer> createContextual(SerializerProvider serializers,
+ BeanProperty property) throws JsonMappingException
+ {
+ if (property == null) {
+ return this;
+ }
+ JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
+ if (format == null) {
+ return this;
+ }
+ // Simple case first: serialize as numeric timestamp?
+ JsonFormat.Shape shape = format.getShape();
+ if (shape.isNumeric()) {
+ return withFormat(Boolean.TRUE, null);
+ }
+
+ // 08-Jun-2017, tatu: With [databind#1648], this gets bit tricky..
+ // First: custom pattern will override things
+ if ((shape == JsonFormat.Shape.STRING) || format.hasPattern()
+ || format.hasLocale() || format.hasTimeZone()) {
+ TimeZone tz = format.getTimeZone();
+ final String pattern = format.hasPattern()
+ ? format.getPattern()
+ : StdDateFormat.DATE_FORMAT_STR_ISO8601;
+ final Locale loc = format.hasLocale()
+ ? format.getLocale()
+ : serializers.getLocale();
+ SimpleDateFormat df = new SimpleDateFormat(pattern, loc);
+ if (tz == null) {
+ tz = serializers.getTimeZone();
+ }
+ df.setTimeZone(tz);
+ return withFormat(Boolean.FALSE, df);
+ }
+
+ // Otherwise, need one of these changes:
+
+
+ // Jackson's own `StdDateFormat` is quite easy to deal with...
+
+ // 08-Jun-2017, tatu: Unfortunately there's no generally usable
+ // mechanism for changing `DateFormat` instances (or even clone()ing)
+ // So: require it be `SimpleDateFormat`; can't config other types
+// serializers.reportBadDefinition(handledType(), String.format(
+ // Ugh. No way to change `Locale`, create copy; must re-crete completely:
+ return this;
+ }
+
+// Test Case
+[/INST]
+ public void testFormatWithoutPattern() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setDateFormat(new SimpleDateFormat(""yyyy-MM-dd'X'HH:mm:ss""));
+ String json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
+ assertEquals(aposToQuotes(""{'date':'1970-01-01X01:00:00'}""), json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testSuperClassWithReferencedJavaType() {
+ TypeFactory tf = objectMapper().getTypeFactory();
+ tf.constructType(Base.class); // must be constructed before sub to set the cache correctly
+ JavaType subType = tf.constructType(Sub.class);
+ // baseTypeFromSub should be a ResolvedRecursiveType in this test
+ JavaType baseTypeFromSub = subType.getSuperClass();
+ assertNotNull(baseTypeFromSub.getSuperClass());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testDateUtilISO8601NoTimezoneNonDefault() throws Exception
+ {
+ // In first case, no timezone -> SHOULD use configured timezone
+ ObjectReader r = MAPPER.readerFor(Date.class);
+ TimeZone tz = TimeZone.getTimeZone(""GMT-2"");
+ Date date1 = r.with(tz)
+ .readValue(quote(""1970-01-01T00:00:00.000""));
+ // Second case, should use specified timezone, not configured
+ Date date2 = r.with(TimeZone.getTimeZone(""GMT+5""))
+ .readValue(quote(""1970-01-01T00:00:00.000-02:00""));
+ assertEquals(date1, date2);
+
+ // also verify actual value, in GMT
+ Calendar c = Calendar.getInstance(TimeZone.getTimeZone(""GMT""));
+ c.setTime(date1);
+ assertEquals(1970, c.get(Calendar.YEAR));
+ assertEquals(Calendar.JANUARY, c.get(Calendar.MONTH));
+ assertEquals(1, c.get(Calendar.DAY_OF_MONTH));
+ assertEquals(2, c.get(Calendar.HOUR_OF_DAY));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException
+ {
+ /* 30-Jan-2010, tatu: Most ids are basic class names; so let's first
+ * check if any generics info is added; and only then ask factory
+ * to do translation when necessary
+ */
+ TypeFactory tf = ctxt.getTypeFactory();
+ if (id.indexOf('<') > 0) {
+ // note: may want to try combining with specialization (esp for EnumMap)?
+ // 17-Aug-2017, tatu: As per [databind#1735] need to ensure assignment
+ // compatibility -- needed later anyway, and not doing so may open
+ // security issues.
+ JavaType t = tf.constructFromCanonical(id);
+ // Probably cleaner to have a method in `TypeFactory` but can't add in patch
+ return t;
+ }
+ Class> cls;
+ try {
+ cls = tf.findClass(id);
+ } catch (ClassNotFoundException e) {
+ // 24-May-2016, tatu: Ok, this is pretty ugly, but we should always get
+ // DeserializationContext, just playing it safe
+ if (ctxt instanceof DeserializationContext) {
+ DeserializationContext dctxt = (DeserializationContext) ctxt;
+ // First: we may have problem handlers that can deal with it?
+ return dctxt.handleUnknownTypeId(_baseType, id, this, ""no such class found"");
+ }
+ // ... meaning that we really should never get here.
+ return null;
+ } catch (Exception e) {
+ throw new IllegalArgumentException(""Invalid type id '""+id+""' (for id type 'Id.class'): ""+e.getMessage(), e);
+ }
+ return tf.constructSpecializedType(_baseType, cls);
+ }
+
+// Test Case
+[/INST]
+ public void testNestedTypeCheck1735() throws Exception
+ {
+ try {
+ MAPPER.readValue(aposToQuotes(
+""{'w':{'type':'java.util.HashMap'}}""),
+ Wrapper1735.class);
+ fail(""Should not pass"");
+ } catch (JsonMappingException e) {
+ verifyException(e, ""not subtype of"");
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testJDKTypes1737() throws Exception
+ {
+ _testTypes1737(java.util.logging.FileHandler.class);
+ _testTypes1737(java.rmi.server.UnicastRemoteObject.class);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
+ String str;
+
+ if (value instanceof Date) {
+ provider.defaultSerializeDateKey((Date) value, jgen);
+ return;
+ } else {
+ str = value.toString();
+ }
+ jgen.writeFieldName(str);
+ }
+
+// Test Case
+[/INST]
+ public void testClassKey() throws IOException
+ {
+ Map,Integer> map = new LinkedHashMap,Integer>();
+ map.put(String.class, 2);
+ String json = MAPPER.writeValueAsString(map);
+ assertEquals(aposToQuotes(""{'java.lang.String':2}""), json);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean canInstantiate() {
+ return canCreateUsingDefault()
+ || canCreateUsingDelegate()
+ || canCreateFromObjectWith() || canCreateFromString()
+ || canCreateFromInt() || canCreateFromLong()
+ || canCreateFromDouble() || canCreateFromBoolean();
+ }
+
+// Test Case
+[/INST]
+ public void testDelegatingArray1804() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ MyType thing = mapper.readValue(""[]"", MyType.class);
+ assertNotNull(thing);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testDelegatingArray1804() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ MyType thing = mapper.readValue(""[]"", MyType.class);
+ assertNotNull(thing);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private boolean _hasCustomHandlers(JavaType t) {
+ if (t.isContainerType()) {
+ // First: value types may have both value and type handlers
+ JavaType ct = t.getContentType();
+ if (ct != null) {
+ return (ct.getValueHandler() != null) || (ct.getTypeHandler() != null);
+ // Second: map(-like) types may have value handler for key (but not type; keys are untyped)
+ }
+ }
+ return false;
+ }
+
+// Test Case
+[/INST]
+ public void testCachedSerialize() throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ String json = aposToQuotes(""{'data':{'1st':'onedata','2nd':'twodata'}}"");
+
+ // Do deserialization with non-annotated map property
+ NonAnnotatedMapHolderClass ignored = mapper.readValue(json, NonAnnotatedMapHolderClass.class);
+ assertTrue(ignored.data.containsKey(""1st""));
+ assertTrue(ignored.data.containsKey(""2nd""));
+
+//mapper = new ObjectMapper();
+
+ MapHolder model2 = mapper.readValue(json, MapHolder.class);
+ if (!model2.data.containsKey(""1st (CUSTOM)"")
+ || !model2.data.containsKey(""2nd (CUSTOM)"")) {
+ fail(""Not using custom key deserializer for input: ""+json+""; resulted in: ""+model2.data);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testJDKTypes1737() throws Exception
+ {
+ _testTypes1737(java.util.logging.FileHandler.class);
+ _testTypes1737(java.rmi.server.UnicastRemoteObject.class);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
+ {
+ // There are certain nasty classes that could cause problems, mostly
+ // via default typing -- catch them here.
+ final Class> raw = type.getRawClass();
+ String full = raw.getName();
+
+ main_check:
+ do {
+ if (_cfgIllegalClassNames.contains(full)) {
+ break;
+ }
+
+ // 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
+ // for some Spring framework types
+ // 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
+ if (full.startsWith(PREFIX_STRING)) {
+ for (Class> cls = raw; cls != Object.class; cls = cls.getSuperclass()) {
+ String name = cls.getSimpleName();
+ // looking for ""AbstractBeanFactoryPointcutAdvisor"" but no point to allow any is there?
+ if (""AbstractPointcutAdvisor"".equals(name)
+ // ditto for ""FileSystemXmlApplicationContext"": block all ApplicationContexts
+ || ""AbstractApplicationContext"".equals(name)) {
+ break main_check;
+ }
+ }
+ }
+ return;
+ } while (false);
+
+ throw JsonMappingException.from(ctxt,
+ String.format(""Illegal type (%s) to deserialize: prevented for security reasons"", full));
+ }
+
+// Test Case
+[/INST]
+ public void testJDKTypes1872() throws Exception
+ {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
+
+ String json = aposToQuotes(String.format(""{'@class':'%s','authorities':['java.util.ArrayList',[]]}"",
+ Authentication1872.class.getName()));
+ Authentication1872 result = mapper.readValue(json, Authentication1872.class);
+ assertNotNull(result);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
+ {
+ // There are certain nasty classes that could cause problems, mostly
+ // via default typing -- catch them here.
+ final Class> raw = type.getRawClass();
+ String full = raw.getName();
+
+ main_check:
+ do {
+ if (_cfgIllegalClassNames.contains(full)) {
+ break;
+ }
+
+ // 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
+ // for some Spring framework types
+ // 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
+ if (raw.isInterface()) {
+ ;
+ } else if (full.startsWith(PREFIX_SPRING)) {
+ for (Class> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
+ String name = cls.getSimpleName();
+ // looking for ""AbstractBeanFactoryPointcutAdvisor"" but no point to allow any is there?
+ if (""AbstractPointcutAdvisor"".equals(name)
+ // ditto for ""FileSystemXmlApplicationContext"": block all ApplicationContexts
+ || ""AbstractApplicationContext"".equals(name)) {
+ break main_check;
+ }
+ // [databind#1737]; more 3rd party
+ // s.add(""com.mchange.v2.c3p0.JndiRefForwardingDataSource"");
+ // s.add(""com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"");
+ // [databind#1931]; more 3rd party
+ // com.mchange.v2.c3p0.ComboPooledDataSource
+ // com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
+ }
+ }
+ return;
+ } while (false);
+
+ throw JsonMappingException.from(ctxt,
+ String.format(""Illegal type (%s) to deserialize: prevented for security reasons"", full));
+ }
+
+// Test Case
+[/INST]
+ public void testC3P0Types() throws Exception
+ {
+ _testIllegalType(ComboPooledDataSource.class); // [databind#1931]
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected JavaType parseType(MyTokenizer tokens)
+ throws IllegalArgumentException
+ {
+ if (!tokens.hasMoreTokens()) {
+ throw _problem(tokens, ""Unexpected end-of-string"");
+ }
+ Class> base = findClass(tokens.nextToken(), tokens);
+
+ // either end (ok, non generic type), or generics
+ if (tokens.hasMoreTokens()) {
+ String token = tokens.nextToken();
+ if (""<"".equals(token)) {
+ List parameterTypes = parseTypes(tokens);
+ TypeBindings b = TypeBindings.create(base, parameterTypes);
+ return _factory._fromClass(null, base, b);
+ }
+ // can be comma that separates types, or closing '>'
+ tokens.pushBack(token);
+ }
+ return _factory._fromClass(null, base, null);
+ }
+
+// Test Case
+[/INST]
+ public void testCanonicalNames()
+ {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ JavaType t = tf.constructType(java.util.Calendar.class);
+ String can = t.toCanonical();
+ assertEquals(""java.util.Calendar"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // Generic maps and collections will default to Object.class if type-erased
+ t = tf.constructType(java.util.ArrayList.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.ArrayList"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ t = tf.constructType(java.util.TreeMap.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.TreeMap"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // And then EnumMap (actual use case for us)
+ t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.EnumMap"",
+ can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // [databind#1941]: allow ""raw"" types too
+
+ t = tf.constructFromCanonical(""java.util.List"");
+ assertEquals(List.class, t.getRawClass());
+ assertEquals(CollectionType.class, t.getClass());
+ // 01-Mar-2018, tatu: not 100% should we expect type parameters here...
+ // But currently we do NOT get any
+ /*
+ assertEquals(1, t.containedTypeCount());
+ assertEquals(Object.class, t.containedType(0).getRawClass());
+ */
+ assertEquals(Object.class, t.getContentType().getRawClass());
+ can = t.toCanonical();
+ assertEquals(""java.util.List"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JavaType constructSpecializedType(JavaType baseType, Class> subclass)
+ {
+ // simple optimization to avoid costly introspection if type-erased type does NOT differ
+ final Class> rawBase = baseType.getRawClass();
+ if (rawBase == subclass) {
+ return baseType;
+ }
+
+ JavaType newType;
+
+ // also: if we start from untyped, not much to save
+ do { // bogus loop to be able to break
+ if (rawBase == Object.class) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ if (!rawBase.isAssignableFrom(subclass)) {
+ throw new IllegalArgumentException(String.format(
+ ""Class %s not subtype of %s"", subclass.getName(), baseType));
+ }
+ // A few special cases where we can simplify handling:
+
+ // (1) Original target type has no generics -- just resolve subtype
+ if (baseType.getBindings().isEmpty()) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ // (2) A small set of ""well-known"" List/Map subtypes where can take a short-cut
+ if (baseType.isContainerType()) {
+ if (baseType.isMapLikeType()) {
+ if ((subclass == HashMap.class)
+ || (subclass == LinkedHashMap.class)
+ || (subclass == EnumMap.class)
+ || (subclass == TreeMap.class)) {
+ newType = _fromClass(null, subclass,
+ TypeBindings.create(subclass, baseType.getKeyType(), baseType.getContentType()));
+ break;
+ }
+ } else if (baseType.isCollectionLikeType()) {
+ if ((subclass == ArrayList.class)
+ || (subclass == LinkedList.class)
+ || (subclass == HashSet.class)
+ || (subclass == TreeSet.class)) {
+ newType = _fromClass(null, subclass,
+ TypeBindings.create(subclass, baseType.getContentType()));
+ break;
+ }
+ // 29-Oct-2015, tatu: One further shortcut: there are variants of `EnumSet`,
+ // but they are impl details and we basically do not care...
+ if (rawBase == EnumSet.class) {
+ return baseType;
+ }
+ }
+ }
+ // (3) Sub-class does not take type parameters -- just resolve subtype
+ int typeParamCount = subclass.getTypeParameters().length;
+ if (typeParamCount == 0) {
+ newType = _fromClass(null, subclass, TypeBindings.emptyBindings());
+ break;
+ }
+ // (4) If all else fails, do the full traversal using placeholders
+ TypeBindings tb = _bindingsForSubtype(baseType, typeParamCount, subclass);
+ newType = _fromClass(null, subclass, tb);
+
+ } while (false);
+
+ // 25-Sep-2016, tatu: As per [databind#1384] also need to ensure handlers get
+ // copied as well
+ newType = newType.withHandlersFrom(baseType);
+ return newType;
+ }
+
+// Test Case
+[/INST]
+ public void testCanonicalNames()
+ {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ JavaType t = tf.constructType(java.util.Calendar.class);
+ String can = t.toCanonical();
+ assertEquals(""java.util.Calendar"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // Generic maps and collections will default to Object.class if type-erased
+ t = tf.constructType(java.util.ArrayList.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.ArrayList"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ t = tf.constructType(java.util.TreeMap.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.TreeMap"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // And then EnumMap (actual use case for us)
+ t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.EnumMap"",
+ can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // [databind#1941]: allow ""raw"" types too
+
+ t = tf.constructFromCanonical(""java.util.List"");
+ assertEquals(List.class, t.getRawClass());
+ assertEquals(CollectionType.class, t.getClass());
+ // 01-Mar-2018, tatu: not 100% should we expect type parameters here...
+ // But currently we do NOT get any
+ /*
+ assertEquals(1, t.containedTypeCount());
+ assertEquals(Object.class, t.containedType(0).getRawClass());
+ */
+ assertEquals(Object.class, t.getContentType().getRawClass());
+ can = t.toCanonical();
+ assertEquals(""java.util.List"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JavaType constructParametricType(Class> parametrized, Class>... parameterClasses) {
+ int len = parameterClasses.length;
+ JavaType[] pt = new JavaType[len];
+ for (int i = 0; i < len; ++i) {
+ pt[i] = _fromClass(null, parameterClasses[i], null);
+ }
+ return constructParametricType(parametrized, pt);
+ }
+
+// Test Case
+[/INST]
+ public void testCanonicalNames()
+ {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ JavaType t = tf.constructType(java.util.Calendar.class);
+ String can = t.toCanonical();
+ assertEquals(""java.util.Calendar"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // Generic maps and collections will default to Object.class if type-erased
+ t = tf.constructType(java.util.ArrayList.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.ArrayList"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ t = tf.constructType(java.util.TreeMap.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.TreeMap"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // And then EnumMap (actual use case for us)
+ t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.EnumMap"",
+ can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // [databind#1941]: allow ""raw"" types too
+
+ t = tf.constructFromCanonical(""java.util.List"");
+ assertEquals(List.class, t.getRawClass());
+ assertEquals(CollectionType.class, t.getClass());
+ // 01-Mar-2018, tatu: not 100% should we expect type parameters here...
+ // But currently we do NOT get any
+ /*
+ assertEquals(1, t.containedTypeCount());
+ assertEquals(Object.class, t.containedType(0).getRawClass());
+ */
+ assertEquals(Object.class, t.getContentType().getRawClass());
+ can = t.toCanonical();
+ assertEquals(""java.util.List"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _addExplicitAnyCreator(DeserializationContext ctxt,
+ BeanDescription beanDesc, CreatorCollector creators,
+ CreatorCandidate candidate)
+ throws JsonMappingException
+ {
+ // Looks like there's bit of magic regarding 1-parameter creators; others simpler:
+ if (1 != candidate.paramCount()) {
+ // Ok: for delegates, we want one and exactly one parameter without
+ // injection AND without name
+ int oneNotInjected = candidate.findOnlyParamWithoutInjection();
+ if (oneNotInjected >= 0) {
+ // getting close; but most not have name
+ if (candidate.paramName(oneNotInjected) == null) {
+ _addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);
+ return;
+ }
+ }
+ _addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);
+ return;
+ }
+ AnnotatedParameter param = candidate.parameter(0);
+ JacksonInject.Value injectId = candidate.injection(0);
+ PropertyName paramName = candidate.explicitParamName(0);
+ BeanPropertyDefinition paramDef = candidate.propertyDef(0);
+
+ // If there's injection or explicit name, should be properties-based
+ boolean useProps = (paramName != null) || (injectId != null);
+ if (!useProps && (paramDef != null)) {
+ // One more thing: if implicit name matches property with a getter
+ // or field, we'll consider it property-based as well
+
+ // 25-May-2018, tatu: as per [databind#2051], looks like we have to get
+ // not implicit name, but name with possible strategy-based-rename
+// paramName = candidate.findImplicitParamName(0);
+ paramName = candidate.findImplicitParamName(0);
+ useProps = (paramName != null) && paramDef.couldSerialize();
+ }
+ if (useProps) {
+ SettableBeanProperty[] properties = new SettableBeanProperty[] {
+ constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)
+ };
+ creators.addPropertyCreator(candidate.creator(), true, properties);
+ return;
+ }
+ _handleSingleArgumentCreator(creators, candidate.creator(), true, true);
+
+ // one more thing: sever link to creator property, to avoid possible later
+ // problems with ""unresolved"" constructor property
+ if (paramDef != null) {
+ ((POJOPropertyBuilder) paramDef).removeConstructors();
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testSnakeCaseWithOneArg() throws Exception
+ {
+ final String MSG = ""1st"";
+ OneProperty actual = MAPPER.readValue(
+ ""{\""param_name0\"":\""""+MSG+""\""}"",
+ OneProperty.class);
+ assertEquals(""CTOR:""+MSG, actual.paramName0);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException
+ {
+ if (_value == null) {
+ ctxt.defaultSerializeNull(gen);
+ } else if (_value instanceof JsonSerializable) {
+ ((JsonSerializable) _value).serialize(gen, ctxt);
+ } else {
+ // 25-May-2018, tatu: [databind#1991] do not call via generator but through context;
+ // this to preserve contextual information
+ gen.writeObject(_value);
+ }
+ }
+
+// Test Case
+[/INST]
+ public void testPOJONodeCustomSer() throws Exception
+ {
+ Data data = new Data();
+ data.aStr = ""Hello"";
+
+ Map mapTest = new HashMap<>();
+ mapTest.put(""data"", data);
+
+ ObjectNode treeTest = MAPPER.createObjectNode();
+ treeTest.putPOJO(""data"", data);
+
+ final String EXP = ""{\""data\"":{\""aStr\"":\""The value is: Hello!\""}}"";
+
+ String mapOut = MAPPER.writer().withAttribute(""myAttr"", ""Hello!"").writeValueAsString(mapTest);
+ assertEquals(EXP, mapOut);
+
+ String treeOut = MAPPER.writer().withAttribute(""myAttr"", ""Hello!"").writeValueAsString(treeTest);
+ assertEquals(EXP, treeOut);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public Object complete(JsonParser p, DeserializationContext ctxt,
+ PropertyValueBuffer buffer, PropertyBasedCreator creator)
+ throws IOException
+ {
+ // first things first: deserialize all data buffered:
+ final int len = _properties.length;
+ Object[] values = new Object[len];
+ for (int i = 0; i < len; ++i) {
+ String typeId = _typeIds[i];
+ final ExtTypedProperty extProp = _properties[i];
+ if (typeId == null) {
+ // let's allow missing both type and property (may already have been set, too)
+ if (_tokens[i] == null) {
+ continue;
+ }
+ // but not just one
+ // 26-Oct-2012, tatu: As per [databind#94], must allow use of 'defaultImpl'
+ if (!extProp.hasDefaultType()) {
+ ctxt.reportInputMismatch(_beanType,
+ ""Missing external type id property '%s'"",
+ extProp.getTypePropertyName());
+ } else {
+ typeId = extProp.getDefaultTypeId();
+ }
+ } else if (_tokens[i] == null) {
+ SettableBeanProperty prop = extProp.getProperty();
+ ctxt.reportInputMismatch(_beanType,
+ ""Missing property '%s' for external type id '%s'"",
+ prop.getName(), _properties[i].getTypePropertyName());
+ }
+ values[i] = _deserialize(p, ctxt, i, typeId);
+
+ final SettableBeanProperty prop = extProp.getProperty();
+ // also: if it's creator prop, fill in
+ if (prop.getCreatorIndex() >= 0) {
+ buffer.assignParameter(prop, values[i]);
+
+ // [databind#999] And maybe there's creator property for type id too?
+ SettableBeanProperty typeProp = extProp.getTypeProperty();
+ // for now, should only be needed for creator properties, too
+ if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) {
+ // 31-May-2018, tatu: [databind#1328] if id is NOT plain `String`, need to
+ // apply deserializer... fun fun.
+ buffer.assignParameter(typeProp, typeId);
+ }
+ }
+ }
+ Object bean = creator.build(ctxt, buffer);
+ // third: assign non-creator properties
+ for (int i = 0; i < len; ++i) {
+ SettableBeanProperty prop = _properties[i].getProperty();
+ if (prop.getCreatorIndex() < 0) {
+ prop.set(bean, values[i]);
+ }
+ }
+ return bean;
+ }
+
+// Test Case
+[/INST]
+ public void testExample() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+
+ String json = mapper.writerWithDefaultPrettyPrinter()
+ .writeValueAsString(Arrays.asList(new AnimalAndType(AnimalType.Dog, new Dog())));
+ List list = mapper.readerFor(new TypeReference>() { })
+ .readValue(json);
+ assertNotNull(list);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected String buildCanonicalName()
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.append(_class.getName());
+ sb.append('<');
+ sb.append(_referencedType.toCanonical());
+ return sb.toString();
+ }
+
+// Test Case
+[/INST]
+ public void testCanonicalNames()
+ {
+ TypeFactory tf = TypeFactory.defaultInstance();
+ JavaType t = tf.constructType(java.util.Calendar.class);
+ String can = t.toCanonical();
+ assertEquals(""java.util.Calendar"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // Generic maps and collections will default to Object.class if type-erased
+ t = tf.constructType(java.util.ArrayList.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.ArrayList"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ t = tf.constructType(java.util.TreeMap.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.TreeMap"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // And then EnumMap (actual use case for us)
+ t = tf.constructMapType(EnumMap.class, EnumForCanonical.class, String.class);
+ can = t.toCanonical();
+ assertEquals(""java.util.EnumMap"",
+ can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // [databind#2109]: also ReferenceTypes
+ t = tf.constructType(new TypeReference>() { });
+ can = t.toCanonical();
+ assertEquals(""java.util.concurrent.atomic.AtomicReference"",
+ can);
+ assertEquals(t, tf.constructFromCanonical(can));
+
+ // [databind#1941]: allow ""raw"" types too
+ t = tf.constructFromCanonical(""java.util.List"");
+ assertEquals(List.class, t.getRawClass());
+ assertEquals(CollectionType.class, t.getClass());
+ // 01-Mar-2018, tatu: not 100% should we expect type parameters here...
+ // But currently we do NOT get any
+ /*
+ assertEquals(1, t.containedTypeCount());
+ assertEquals(Object.class, t.containedType(0).getRawClass());
+ */
+ assertEquals(Object.class, t.getContentType().getRawClass());
+ can = t.toCanonical();
+ assertEquals(""java.util.List"", can);
+ assertEquals(t, tf.constructFromCanonical(can));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public JsonToken nextToken() throws IOException
+ {
+ _binaryValue = null;
+ if (_nextToken != null) {
+ JsonToken t = _nextToken;
+ _currToken = t;
+ _nextToken = null;
+ switch (t) {
+ case START_OBJECT:
+ _parsingContext = _parsingContext.createChildObjectContext(-1, -1);
+ break;
+ case START_ARRAY:
+ _parsingContext = _parsingContext.createChildArrayContext(-1, -1);
+ break;
+ case END_OBJECT:
+ case END_ARRAY:
+ _parsingContext = _parsingContext.getParent();
+ _namesToWrap = _parsingContext.getNamesToWrap();
+ break;
+ case FIELD_NAME:
+ _parsingContext.setCurrentName(_xmlTokens.getLocalName());
+ break;
+ default: // VALUE_STRING, VALUE_NULL
+ // should be fine as is?
+ }
+ return t;
+ }
+ int token = _xmlTokens.next();
+
+ // Need to have a loop just because we may have to eat/convert
+ // a start-element that indicates an array element.
+ while (token == XmlTokenStream.XML_START_ELEMENT) {
+ // If we thought we might get leaf, no such luck
+ if (_mayBeLeaf) {
+ // leave _mayBeLeaf set, as we start a new context
+ _nextToken = JsonToken.FIELD_NAME;
+ _parsingContext = _parsingContext.createChildObjectContext(-1, -1);
+ return (_currToken = JsonToken.START_OBJECT);
+ }
+ if (_parsingContext.inArray()) {
+ // Yup: in array, so this element could be verified; but it won't be
+ // reported anyway, and we need to process following event.
+ token = _xmlTokens.next();
+ _mayBeLeaf = true;
+ continue;
+ }
+ String name = _xmlTokens.getLocalName();
+ _parsingContext.setCurrentName(name);
+
+ // Ok: virtual wrapping can be done by simply repeating current START_ELEMENT.
+ // Couple of ways to do it; but start by making _xmlTokens replay the thing...
+ if (_namesToWrap != null && _namesToWrap.contains(name)) {
+ _xmlTokens.repeatStartElement();
+ }
+
+ _mayBeLeaf = true;
+ // Ok: in array context we need to skip reporting field names.
+ // But what's the best way to find next token?
+ return (_currToken = JsonToken.FIELD_NAME);
+ }
+
+ // Ok; beyond start element, what do we get?
+ switch (token) {
+ case XmlTokenStream.XML_END_ELEMENT:
+ // Simple, except that if this is a leaf, need to suppress end:
+ if (_mayBeLeaf) {
+ _mayBeLeaf = false;
+ // 06-Jan-2015, tatu: as per [dataformat-xml#180], need to
+ // expose as empty Object, not null
+ return (_currToken = JsonToken.VALUE_NULL);
+ }
+ _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
+ _parsingContext = _parsingContext.getParent();
+ _namesToWrap = _parsingContext.getNamesToWrap();
+ return _currToken;
+
+ case XmlTokenStream.XML_ATTRIBUTE_NAME:
+ // If there was a chance of leaf node, no more...
+ if (_mayBeLeaf) {
+ _mayBeLeaf = false;
+ _nextToken = JsonToken.FIELD_NAME;
+ _currText = _xmlTokens.getText();
+ _parsingContext = _parsingContext.createChildObjectContext(-1, -1);
+ return (_currToken = JsonToken.START_OBJECT);
+ }
+ _parsingContext.setCurrentName(_xmlTokens.getLocalName());
+ return (_currToken = JsonToken.FIELD_NAME);
+ case XmlTokenStream.XML_ATTRIBUTE_VALUE:
+ _currText = _xmlTokens.getText();
+ return (_currToken = JsonToken.VALUE_STRING);
+ case XmlTokenStream.XML_TEXT:
+ _currText = _xmlTokens.getText();
+ if (_mayBeLeaf) {
+ _mayBeLeaf = false;
+ /* One more refinement (pronunced like ""hack"") is that if
+ * we had an empty String (or all white space), and we are
+ * deserializing an array, we better hide the empty text.
+ */
+ // Also: must skip following END_ELEMENT
+ _xmlTokens.skipEndElement();
+ if (_parsingContext.inArray()) {
+ if (_isEmpty(_currText)) {
+ // 06-Jan-2015, tatu: as per [dataformat-xml#180], need to
+ // expose as empty Object, not null (or, worse, as used to
+ // be done, by swallowing the token)
+ _currToken = JsonToken.END_ARRAY;
+ _parsingContext = _parsingContext.getParent();
+ _namesToWrap = _parsingContext.getNamesToWrap();
+ return _currToken;
+ }
+ }
+ return (_currToken = JsonToken.VALUE_STRING);
+ } else {
+ // [dataformat-xml#177]: empty text may also need to be skipped
+ if (_parsingContext.inObject()
+ && (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {
+ _currToken = JsonToken.END_OBJECT;
+ _parsingContext = _parsingContext.getParent();
+ _namesToWrap = _parsingContext.getNamesToWrap();
+ return _currToken;
+ }
+ }
+ // If not a leaf (or otherwise ignorable), need to transform into property...
+ _parsingContext.setCurrentName(_cfgNameForTextElement);
+ _nextToken = JsonToken.VALUE_STRING;
+ return (_currToken = JsonToken.FIELD_NAME);
+ case XmlTokenStream.XML_END:
+ return (_currToken = null);
+ }
+
+ // should never get here
+ _throwInternal();
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testNestedUnwrappedLists180() throws Exception
+ {
+ /*
+ Records recs = new Records();
+ recs.records.add(new Record());
+ recs.records.add(new Record());
+ recs.records.add(new Record());
+ recs.records.get(0).fields.add(new Field(""a""));
+ recs.records.get(2).fields.add(new Field(""b""));
+
+ String xml = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(recs);
+ */
+
+ String xml =
+""\n""
+// Important: it's the empty CDATA here that causes breakage -- empty element alone would be fine
+//+""\n\n""
++""\n""
++"" \n""
++"" \n""
++"" \n""
++""\n""
+;
+
+//System.out.println(""XML: ""+xml);
+
+ Records result = MAPPER.readValue(xml, Records.class);
+ assertNotNull(result.records);
+ assertEquals(2, result.records.size());
+ assertNotNull(result.records.get(1));
+ assertEquals(1, result.records.get(1).fields.size());
+ assertEquals(""b"", result.records.get(1).fields.get(0).name);
+
+ // also, first one ought not be null should it? Ideally not...
+ assertNotNull(result.records.get(0));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private final int _next() throws XMLStreamException
+ {
+ switch (_currentState) {
+ case XML_ATTRIBUTE_VALUE:
+ ++_nextAttributeIndex;
+ // fall through
+ case XML_START_ELEMENT: // attributes to return?
+ if (_nextAttributeIndex < _attributeCount) {
+ _localName = _xmlReader.getAttributeLocalName(_nextAttributeIndex);
+ _namespaceURI = _xmlReader.getAttributeNamespace(_nextAttributeIndex);
+ _textValue = _xmlReader.getAttributeValue(_nextAttributeIndex);
+ return (_currentState = XML_ATTRIBUTE_NAME);
+ }
+ // otherwise need to find START/END_ELEMENT or text
+ String text = _collectUntilTag();
+ // If we have no/all-whitespace text followed by START_ELEMENT, ignore text
+ if (_xmlReader.getEventType() == XMLStreamReader.START_ELEMENT) {
+ return _initStartElement();
+ }
+ // For END_ELEMENT we will return text, if any
+ if (text != null) {
+ _textValue = text;
+ return (_currentState = XML_TEXT);
+ }
+ return _handleEndElement();
+
+ case XML_ATTRIBUTE_NAME:
+ // if we just returned name, will need to just send value next
+ return (_currentState = XML_ATTRIBUTE_VALUE);
+ case XML_TEXT:
+ // mixed text with other elements
+ // text followed by END_ELEMENT
+ return _handleEndElement();
+ case XML_END:
+ return XML_END;
+// throw new IllegalStateException(""No more XML tokens available (end of input)"");
+ }
+
+ // Ok: must be END_ELEMENT; see what tag we get (or end)
+ switch (_skipUntilTag()) {
+ case XMLStreamConstants.END_DOCUMENT:
+ return (_currentState = XML_END);
+ case XMLStreamConstants.END_ELEMENT:
+ return _handleEndElement();
+ }
+ // START_ELEMENT...
+ return _initStartElement();
+ }
+
+// Test Case
+[/INST]
+ public void testMixedContent() throws Exception
+ {
+ WindSpeed result = MAPPER.readValue("" 27 20"",
+ WindSpeed.class);
+ assertEquals(27, result.value);
+ assertNotNull(result.radius);
+ assertEquals(20, result.radius.value);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String nextTextValue() throws IOException
+ {
+ _binaryValue = null;
+ if (_nextToken != null) {
+ JsonToken t = _nextToken;
+ _currToken = t;
+ _nextToken = null;
+
+ // expected case; yes, got a String
+ if (t == JsonToken.VALUE_STRING) {
+ return _currText;
+ }
+ _updateState(t);
+ return null;
+ }
+
+ int token = _xmlTokens.next();
+
+ // mostly copied from 'nextToken()'
+ while (token == XmlTokenStream.XML_START_ELEMENT) {
+ if (_mayBeLeaf) {
+ _nextToken = JsonToken.FIELD_NAME;
+ _parsingContext = _parsingContext.createChildObjectContext(-1, -1);
+ _currToken = JsonToken.START_OBJECT;
+ return null;
+ }
+ if (_parsingContext.inArray()) {
+ token = _xmlTokens.next();
+ _mayBeLeaf = true;
+ continue;
+ }
+ String name = _xmlTokens.getLocalName();
+ _parsingContext.setCurrentName(name);
+ if (_namesToWrap != null && _namesToWrap.contains(name)) {
+ _xmlTokens.repeatStartElement();
+ }
+ _mayBeLeaf = true;
+ _currToken = JsonToken.FIELD_NAME;
+ return null;
+ }
+
+ // Ok; beyond start element, what do we get?
+ switch (token) {
+ case XmlTokenStream.XML_END_ELEMENT:
+ if (_mayBeLeaf) {
+ // NOTE: this is different from nextToken() -- produce """", NOT null
+ _mayBeLeaf = false;
+ _currToken = JsonToken.VALUE_STRING;
+ return (_currText = """");
+ }
+ _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
+ _parsingContext = _parsingContext.getParent();
+ _namesToWrap = _parsingContext.getNamesToWrap();
+ break;
+ case XmlTokenStream.XML_ATTRIBUTE_NAME:
+ // If there was a chance of leaf node, no more...
+ if (_mayBeLeaf) {
+ _mayBeLeaf = false;
+ _nextToken = JsonToken.FIELD_NAME;
+ _currText = _xmlTokens.getText();
+ _parsingContext = _parsingContext.createChildObjectContext(-1, -1);
+ _currToken = JsonToken.START_OBJECT;
+ } else {
+ _parsingContext.setCurrentName(_xmlTokens.getLocalName());
+ _currToken = JsonToken.FIELD_NAME;
+ }
+ break;
+ case XmlTokenStream.XML_ATTRIBUTE_VALUE:
+ _currText = _xmlTokens.getText();
+ _currToken = JsonToken.VALUE_STRING;
+ break;
+ case XmlTokenStream.XML_TEXT:
+ _currText = _xmlTokens.getText();
+ if (_mayBeLeaf) {
+ _mayBeLeaf = false;
+ // Also: must skip following END_ELEMENT
+ _xmlTokens.skipEndElement();
+
+ // NOTE: this is different from nextToken() -- NO work-around
+ // for otherwise empty List/array
+ _currToken = JsonToken.VALUE_STRING;
+ return _currText;
+ }
+ // If not a leaf, need to transform into property...
+ _parsingContext.setCurrentName(_cfgNameForTextElement);
+ _nextToken = JsonToken.VALUE_STRING;
+ _currToken = JsonToken.FIELD_NAME;
+ break;
+ case XmlTokenStream.XML_END:
+ _currToken = null;
+ }
+ return null;
+ }
+
+// Test Case
+[/INST]
+ public void testXmlAttributesWithNextTextValue() throws Exception
+ {
+ final String XML = """";
+
+ FromXmlParser xp = (FromXmlParser) _xmlFactory.createParser(new StringReader(XML));
+
+ // First: verify handling without forcing array handling:
+ assertToken(JsonToken.START_OBJECT, xp.nextToken()); //
+ assertToken(JsonToken.FIELD_NAME, xp.nextToken()); //
+ assertEquals(""max"", xp.getCurrentName());
+
+ assertEquals(""7"", xp.nextTextValue());
+
+ assertToken(JsonToken.FIELD_NAME, xp.nextToken()); //
+ assertEquals(""offset"", xp.getCurrentName());
+
+ assertEquals(""offset"", xp.getText());
+
+ assertEquals(""9"", xp.nextTextValue());
+
+ assertEquals(""9"", xp.getText());
+
+ assertToken(JsonToken.END_OBJECT, xp.nextToken()); //
+ xp.close();
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected void _serializeXmlNull(JsonGenerator jgen) throws IOException
+ {
+ // 14-Nov-2016, tatu: As per [dataformat-xml#213], we may have explicitly
+ // configured root name...
+ if (jgen instanceof ToXmlGenerator) {
+ _initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL);
+ }
+ super.serializeValue(jgen, null);
+ }
+
+// Test Case
+[/INST]
+ public void testDynamicRootName() throws IOException
+ {
+ String xml;
+
+ ObjectWriter w = _xmlMapper.writer().withRootName(""rudy"");
+
+ xml = w.writeValueAsString(new StringBean(""foo""));
+ assertEquals(""foo"", xml);
+
+ xml = w.writeValueAsString(new StringBean(null));
+ assertEquals("""", xml);
+
+ // and even with null will respect configured root name
+ xml = w.writeValueAsString(null);
+ assertEquals("""", xml);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ protected XmlSerializerProvider(XmlSerializerProvider src) {
+ super(src);
+ // 21-May-2018, tatu: As per [dataformat-xml#282], should NOT really copy
+ // root name lookup as that may link back to diff version, configuration
+ _rootNameLookup = src._rootNameLookup;
+ }
+
+// Test Case
+[/INST]
+ public void testCopyWith() throws Exception
+ {
+ XmlMapper xmlMapper = newMapper();
+ final ObjectMapper xmlMapperNoAnno = xmlMapper.copy()
+ .disable(MapperFeature.USE_ANNOTATIONS)
+ .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
+
+ String xml1 = xmlMapper.writeValueAsString(new Pojo282());
+ String xml2 = xmlMapperNoAnno.writeValueAsString(new Pojo282());
+
+ if (!xml1.contains(""AnnotatedName"")) {
+ fail(""Should use name 'AnnotatedName', xml = ""+xml1);
+ }
+ if (!xml2.contains(""Pojo282"")
+ || xml2.contains(""AnnotatedName"")) {
+ fail(""Should NOT use name 'AnnotatedName' but 'Pojo282', xml = ""+xml1);
+ }
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+x
+
+// Test Case
+[/INST]
+ public void testWith0Bytes() throws Exception
+ {
+ String xml = MAPPER.writeValueAsString(createPojo());
+ assertEquals("""", xml);
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private void normalise(Element element) {
+ List toMove = new ArrayList();
+ for (Node node: element.childNodes) {
+ if (node instanceof TextNode) {
+ TextNode tn = (TextNode) node;
+ if (!tn.isBlank())
+ toMove.add(tn);
+ }
+ }
+
+ for (Node node: toMove) {
+ element.removeChild(node);
+ body().appendChild(new TextNode("" "", """"));
+ body().appendChild(node);
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test public void createsStructureFromBodySnippet() {
+ // the bar baz stuff naturally goes into the body, but the 'foo' goes into root, and the normalisation routine
+ // needs to move into the start of the body
+ String html = ""foo bar baz"";
+ Document doc = Jsoup.parse(html);
+ assertEquals (""foo bar baz"", doc.text());
+
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public String absUrl(String attributeKey) {
+ Validate.notEmpty(attributeKey);
+
+ String relUrl = attr(attributeKey);
+ if (!hasAttr(attributeKey)) {
+ return """"; // nothing to make absolute with
+ } else {
+ URL base;
+ try {
+ try {
+ base = new URL(baseUri);
+ } catch (MalformedURLException e) {
+ // the base is unsuitable, but the attribute may be abs on its own, so try that
+ URL abs = new URL(relUrl);
+ return abs.toExternalForm();
+ }
+ // workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
+ URL abs = new URL(base, relUrl);
+ return abs.toExternalForm();
+ } catch (MalformedURLException e) {
+ return """";
+ }
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test public void absHandlesRelativeQuery() {
+ Document doc = Jsoup.parse(""OneTwo"", ""http://jsoup.org/path/file?bar"");
+
+ Element a1 = doc.select(""a"").first();
+ assertEquals(""http://jsoup.org/path/file?foo"", a1.absUrl(""href""));
+
+ Element a2 = doc.select(""a"").get(1);
+ assertEquals(""http://jsoup.org/path/bar.html?foo"", a2.absUrl(""href""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Elements select() {
+ tq.consumeWhitespace();
+
+ if (tq.matchesAny(combinators)) { // if starts with a combinator, use root as elements
+ elements.add(root);
+ combinator(tq.consume().toString());
+ } else {
+ addElements(findElements()); // chomp first element matcher off queue
+ }
+
+ while (!tq.isEmpty()) {
+ // hierarchy and extras
+ boolean seenWhite = tq.consumeWhitespace();
+
+ if (tq.matchChomp("","")) { // group or
+ while (!tq.isEmpty()) {
+ String subQuery = tq.chompTo("","");
+ elements.addAll(select(subQuery, root));
+ }
+ } else if (tq.matchesAny(combinators)) {
+ combinator(tq.consume().toString());
+ } else if (seenWhite) {
+ combinator("" "");
+ } else { // E.class, E#id, E[attr] etc. AND
+ Elements candidates = findElements(); // take next el, #. etc off queue
+ intersectElements(filterForSelf(elements, candidates));
+ }
+ }
+ return new Elements(elements);
+ }
+
+// Test Case
+[/INST]
+ @Test public void notAll() {
+ Document doc = Jsoup.parse(""
Two
Three
"");
+
+ Elements el1 = doc.body().select("":not(p)""); // should just be the span
+ assertEquals(2, el1.size());
+ assertEquals(""body"", el1.first().tagName());
+ assertEquals(""span"", el1.last().tagName());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Elements findElements() {
+ if (tq.matchChomp(""#"")) {
+ return byId();
+ } else if (tq.matchChomp(""."")) {
+ return byClass();
+ } else if (tq.matchesWord()) {
+ return byTag();
+ } else if (tq.matches(""["")) {
+ return byAttribute();
+ } else if (tq.matchChomp(""*"")) {
+ return allElements();
+ } else if (tq.matchChomp("":lt("")) {
+ return indexLessThan();
+ } else if (tq.matchChomp("":gt("")) {
+ return indexGreaterThan();
+ } else if (tq.matchChomp("":eq("")) {
+ return indexEquals();
+ } else if (tq.matches("":has("")) {
+ return has();
+ } else if (tq.matches("":contains("")) {
+ return contains(false);
+ } else if (tq.matches("":containsOwn("")) {
+ return contains(true);
+ } else if (tq.matches("":matches("")) {
+ return matches(false);
+ } else if (tq.matches("":matchesOwn("")) {
+ return matches(true);
+ } else { // unhandled
+ throw new SelectorParseException(""Could not parse query '%s': unexpected token at '%s'"", query, tq.remainder());
+ }
+ }
+
+// Test Case
+[/INST]
+ @Test public void notAll() {
+ Document doc = Jsoup.parse(""
Two
Three
"");
+
+ Elements el1 = doc.body().select("":not(p)""); // should just be the span
+ assertEquals(2, el1.size());
+ assertEquals(""body"", el1.first().tagName());
+ assertEquals(""span"", el1.last().tagName());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+X
+
+// Test Case
+[/INST]
+ @Test public void notAll() {
+ Document doc = Jsoup.parse(""
Two
Three
"");
+
+ Elements el1 = doc.body().select("":not(p)""); // should just be the span
+ assertEquals(2, el1.size());
+ assertEquals(""body"", el1.first().tagName());
+ assertEquals(""span"", el1.last().tagName());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+X
+
+// Test Case
+[/INST]
+ @Test public void notAll() {
+ Document doc = Jsoup.parse(""
Two
Three
"");
+
+ Elements el1 = doc.body().select("":not(p)""); // should just be the span
+ assertEquals(2, el1.size());
+ assertEquals(""body"", el1.first().tagName());
+ assertEquals(""span"", el1.last().tagName());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ private Elements select() {
+ tq.consumeWhitespace();
+
+ if (tq.matchesAny(combinators)) { // if starts with a combinator, use root as elements
+ elements.add(root);
+ combinator(tq.consume().toString());
+ } else {
+ addElements(findElements()); // chomp first element matcher off queue
+ }
+
+ while (!tq.isEmpty()) {
+ // hierarchy and extras
+ boolean seenWhite = tq.consumeWhitespace();
+
+ if (tq.matchChomp("","")) { // group or
+ while (!tq.isEmpty()) {
+ String subQuery = tq.chompTo("","");
+ elements.addAll(select(subQuery, root));
+ }
+ } else if (tq.matchesAny(combinators)) {
+ combinator(tq.consume().toString());
+ } else if (seenWhite) {
+ combinator("" "");
+ } else { // E.class, E#id, E[attr] etc. AND
+ Elements candidates = findElements(); // take next el, #. etc off queue
+ intersectElements(filterForSelf(elements, candidates));
+ }
+ }
+ return new Elements(elements);
+ }
+
+// Test Case
+[/INST]
+ @Test public void testByAttributeRegexCombined() {
+ Document doc = Jsoup.parse(""
Hello
"");
+ Elements els = doc.select(""div table[class~=x|y]"");
+ assertEquals(1, els.size());
+ assertEquals(""Hello"", els.text());
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+ public boolean hasAttr(String attributeKey) {
+ Validate.notNull(attributeKey);
+
+ return attributes.hasKey(attributeKey);
+ }
+
+// Test Case
+[/INST]
+ @Test public void handlesAbsPrefixOnHasAttr() {
+ // 1: no abs url; 2: has abs url
+ Document doc = Jsoup.parse(""OneTwo"");
+ Element one = doc.select(""#1"").first();
+ Element two = doc.select(""#2"").first();
+
+ assertFalse(one.hasAttr(""abs:href""));
+ assertTrue(one.hasAttr(""href""));
+ assertEquals("""", one.absUrl(""href""));
+
+ assertTrue(two.hasAttr(""abs:href""));
+ assertTrue(two.hasAttr(""href""));
+ assertEquals(""http://jsoup.org/"", two.absUrl(""href""));
+ }
+"
+"[INST] <>
+You are a helpful assistant. Generate a test case that triggers the bug for the buggy function.
+<>
+
+// Buggy Function
+X
+
+// Test Case
+[/INST]
+ @Test public void parsesUnterminatedTextarea() {
+ // don't parse right to end, but break on