task_id stringlengths 5 19 | buggy_code stringlengths 44 3.26k | fixed_code stringlengths 67 3.31k | file_path stringlengths 36 95 | issue_title stringlengths 0 150 | issue_description stringlengths 0 2.85k | start_line int64 9 4.43k | end_line int64 11 4.52k |
|---|---|---|---|---|---|---|---|
Chart-1 | public LegendItemCollection getLegendItems() {
LegendItemCollection result = new LegendItemCollection();
if (this.plot == null) {
return result;
}
int index = this.plot.getIndexOf(this);
CategoryDataset dataset = this.plot.getDataset(index);
if (dataset != null) {
return result;
... | 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;
... | source/org/jfree/chart/renderer/category/AbstractCategoryItemRenderer.java | #983 Potential NPE in AbstractCategoryItemRender.getLegendItems() | Setting up a working copy of the current JFreeChart trunk in Eclipse I got a warning about a null pointer access in this bit of code from AbstractCategoryItemRender.java:
public LegendItemCollection getLegendItems() {
LegendItemCollection result = new LegendItemCollection();
if (this.plot == null) {
return result;
}
in... | 1,790 | 1,822 |
Chart-10 | public String generateToolTipFragment(String toolTipText) {
return " title=\"" + toolTipText
+ "\" alt=\"\"";
} | public String generateToolTipFragment(String toolTipText) {
return " title=\"" + ImageMapUtilities.htmlEscape(toolTipText)
+ "\" alt=\"\"";
} | source/org/jfree/chart/imagemap/StandardToolTipTagFragmentGenerator.java | 64 | 67 | ||
Chart-11 | public static boolean equal(GeneralPath p1, GeneralPath p2) {
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
if (p1.getWindingRule() != p2.getWindingRule()) {
return false;
}
PathIterator iterator1 = p1.getPathIterator(null);
PathIterat... | 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);
PathIterat... | source/org/jfree/chart/util/ShapeUtilities.java | #868 JCommon 1.0.12 ShapeUtilities.equal(path1,path2) | The comparison of two GeneralPath objects uses the same PathIterator for both objects. equal(GeneralPath path1, GeneralPath path2) will thus return true for any pair of non-null GeneralPath instances having the same windingRule. | 264 | 296 |
Chart-12 | public MultiplePiePlot(CategoryDataset dataset) {
super();
this.dataset = dataset;
PiePlot piePlot = new PiePlot(null);
this.pieChart = new JFreeChart(piePlot);
this.pieChart.removeLegend();
this.dataExtractOrder = TableOrder.BY_COLUMN;
this.pieChart.setBackgroundPaint(null);
TextTitle s... | public MultiplePiePlot(CategoryDataset dataset) {
super();
setDataset(dataset);
PiePlot piePlot = new PiePlot(null);
this.pieChart = new JFreeChart(piePlot);
this.pieChart.removeLegend();
this.dataExtractOrder = TableOrder.BY_COLUMN;
this.pieChart.setBackgroundPaint(null);
TextTitle seri... | source/org/jfree/chart/plot/MultiplePiePlot.java | #213 Fix for MultiplePiePlot | When dataset is passed into constructor for MultiplePiePlot, the dataset is not wired to a listener, as it would be if setDataset is called. | 143 | 158 |
Chart-17 | public Object clone() throws CloneNotSupportedException {
Object clone = createCopy(0, getItemCount() - 1);
return clone;
} | public Object clone() throws CloneNotSupportedException {
TimeSeries clone = (TimeSeries) super.clone();
clone.data = (List) ObjectUtilities.deepClone(this.data);
return clone;
} | source/org/jfree/data/time/TimeSeries.java | #803 cloning of TimeSeries | It's just a minor bug!
When I clone a TimeSeries which has no items, I get an IllegalArgumentException ("Requires start <= end").
But I don't think the user should be responsible for checking whether the TimeSeries has any items or not. | 856 | 859 |
Chart-20 | public ValueMarker(double value, Paint paint, Stroke stroke,
Paint outlinePaint, Stroke outlineStroke, float alpha) {
super(paint, stroke, paint, stroke, alpha);
this.value = value;
} | public ValueMarker(double value, Paint paint, Stroke stroke,
Paint outlinePaint, Stroke outlineStroke, float alpha) {
super(paint, stroke, outlinePaint, outlineStroke, alpha);
this.value = value;
} | source/org/jfree/chart/plot/ValueMarker.java | 93 | 97 | ||
Chart-24 | public Paint getPaint(double value) {
double v = Math.max(value, this.lowerBound);
v = Math.min(v, this.upperBound);
int g = (int) ((value - this.lowerBound) / (this.upperBound
- this.lowerBound) * 255.0);
return new Color(g, g, g);
} | public Paint getPaint(double value) {
double v = Math.max(value, this.lowerBound);
v = Math.min(v, this.upperBound);
int g = (int) ((v - this.lowerBound) / (this.upperBound
- this.lowerBound) * 255.0);
return new Color(g, g, g);
} | source/org/jfree/chart/renderer/GrayPaintScale.java | 123 | 129 | ||
Chart-3 | public TimeSeries createCopy(int start, int end)
throws CloneNotSupportedException {
if (start < 0) {
throw new IllegalArgumentException("Requires start >= 0.");
}
if (end < start) {
throw new IllegalArgumentException("Requires start <= end.");
}
TimeSeries copy = (TimeSeries... | 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... | source/org/jfree/data/time/TimeSeries.java | 1,048 | 1,072 | ||
Chart-4 | public Range getDataRange(ValueAxis axis) {
Range result = null;
List mappedDatasets = new ArrayList();
List includedAnnotations = new ArrayList();
boolean isDomainAxis = true;
// is it a domain axis?
int domainIndex = getDomainAxisIndex(axis);
if (domainIndex >= 0) {
isDomainAxis ... | 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 ... | source/org/jfree/chart/plot/XYPlot.java | 4,425 | 4,519 | ||
Chart-6 | public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ShapeList)) {
return false;
}
return super.equals(obj);
} | public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ShapeList)) {
return false;
}
ShapeList that = (ShapeList) obj;
int listSize = size();
for (int i = 0; i < listSize; i++) {
if (!ShapeUtilities.equal((Shape) get(i), (Shape) tha... | source/org/jfree/chart/util/ShapeList.java | 103 | 113 | ||
Chart-7 | private void updateBounds(TimePeriod period, int index) {
long start = period.getStart().getTime();
long end = period.getEnd().getTime();
long middle = start + ((end - start) / 2);
if (this.minStartIndex >= 0) {
long minStart = getDataItem(this.minStartIndex).getPeriod()
.getSt... | 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()
.getSt... | source/org/jfree/data/time/TimePeriodValues.java | 257 | 335 | ||
Chart-8 | public Week(Date time, TimeZone zone) {
// defer argument checking...
this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault());
} | public Week(Date time, TimeZone zone) {
// defer argument checking...
this(time, zone, Locale.getDefault());
} | source/org/jfree/data/time/Week.java | 173 | 176 | ||
Chart-9 | public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)
throws CloneNotSupportedException {
if (start == null) {
throw new IllegalArgumentException("Null 'start' argument.");
}
if (end == null) {
throw new IllegalArgumentException("Null 'end' argument.");
}
... | 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.");
}
... | source/org/jfree/data/time/TimeSeries.java | #818 Error on TimeSeries createCopy() method | The test case at the end fails with :
java.lang.IllegalArgumentException: Requires start <= end.
The problem is in that the int start and end indexes corresponding to given timePeriod are computed incorectly. Here I would expect an empty serie to be returned, not an exception. This is with jfreechart 1.0.7
public class... | 918 | 956 |
Cli-10 | protected void setOptions(final Options options) {
this.options = options;
this.requiredOptions = options.getRequiredOptions();
} | protected void setOptions(final Options options) {
this.options = options;
this.requiredOptions = new ArrayList(options.getRequiredOptions());
} | src/java/org/apache/commons/cli/Parser.java | Missing required options not throwing MissingOptionException | When an Options object is used to parse a second set of command arguments it won't throw a MissingOptionException.
{code:java}
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.common... | 44 | 47 |
Cli-15 | public List getValues(final Option option,
List defaultValues) {
// initialize the return list
List valueList = (List) values.get(option);
// grab the correct default values
if ((valueList == null) || valueList.isEmpty()) {
valueList = defaultValues;
}
// augment ... | public List getValues(final Option option,
List defaultValues) {
// initialize the return list
List valueList = (List) values.get(option);
// grab the correct default values
if (defaultValues == null || defaultValues.isEmpty()) {
defaultValues = (List) this.defaultValues.g... | src/java/org/apache/commons/cli2/commandline/WriteableCommandLineImpl.java | deafult arguments only works if no arguments are submitted | When using multple arguments and defaults, the behaviour is counter-intuitive and will only pick up a default if no args are passed in.
For instance in the code below I have set up so 0, 1, or 2 args may bve accepted, with defaults 100 and 1000.
I expect it to behave as follows.
1. for 2 args, 1 and 2 the values should... | 111 | 130 |
Cli-17 | protected void burstToken(String token, boolean stopAtNonOption)
{
for (int i = 1; i < token.length(); i++)
{
String ch = String.valueOf(token.charAt(i));
if (options.hasOption(ch))
{
tokens.add("-" + ch);
currentOption = options.getOption(ch);
if (c... | 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 (c... | src/java/org/apache/commons/cli/PosixParser.java | PosixParser keeps bursting tokens even if a non option character is found | PosixParser doesn't stop the bursting process of a token if stopAtNonOption is enabled and a non option character is encountered.
For example if the options a and b are defined, with stopAtNonOption=true the following command line:
-azb
is turned into:
-a zb -b
the right output should be:
-a zb | 282 | 310 |
Cli-19 | private void processOptionToken(String token, boolean stopAtNonOption)
{
if (options.hasOption(token))
{
currentOption = options.getOption(token);
tokens.add(token);
}
else if (stopAtNonOption)
{
eatTheRest = true;
tokens.add(token);
}
} | private void processOptionToken(String token, boolean stopAtNonOption)
{
if (options.hasOption(token))
{
currentOption = options.getOption(token);
}
else if (stopAtNonOption)
{
eatTheRest = true;
}
tokens.add(token);
} | src/java/org/apache/commons/cli/PosixParser.java | PosixParser ignores unrecognized tokens starting with '-' | PosixParser doesn't handle properly unrecognized tokens starting with '-' when stopAtNonOption is enabled, the token is simply ignored.
For example, if the option 'a' is defined, the following command line:
-z -a foo
is interpreted as:
-a foo | 227 | 239 |
Cli-2 | protected void burstToken(String token, boolean stopAtNonOption)
{
int tokenLength = token.length();
for (int i = 1; i < tokenLength; i++)
{
String ch = String.valueOf(token.charAt(i));
boolean hasOption = options.hasOption(ch);
if (hasOption)
... | 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)
... | src/java/org/apache/commons/cli/PosixParser.java | [cli] Parameter value "-something" misinterpreted as a parameter | If a parameter value is passed that contains a hyphen as the (delimited) first
character, CLI parses this a parameter. For example using the call
java myclass -t "-something"
Results in the parser creating the invalid parameter -o (noting that it is
skipping the 's')
My code is using the Posix parser as follows
Opti... | 278 | 308 |
Cli-20 | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
init();
this.options = options;
// an iterator for the command line tokens
Iterator iter = Arrays.asList(arguments).iterator();
// process each command line token
while (iter.hasNext())
{
// ... | 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())
{
// ... | src/java/org/apache/commons/cli/PosixParser.java | PosixParser keeps processing tokens after a non unrecognized long option | PosixParser keeps processing tokens after a non unrecognized long option when stopAtNonOption is enabled. The tokens after the unrecognized long option are burst, split around '=', etc.. instead of being kept as is.
For example, with the options 'a' and 'b' defined, 'b' having an argument, the following command line:
... | 97 | 159 |
Cli-23 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | 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))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpFormatter();
... | 805 | 841 |
Cli-24 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | 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))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpFormatter();
... | 809 | 852 |
Cli-25 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | 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))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | infinite loop in the wrapping code of HelpFormatter | If there is not enough space to display a word on a single line, HelpFormatter goes into a infinite loops until the JVM crashes with an OutOfMemoryError.
Test case:
Options options = new Options();
options.addOption("h", "help", false, "This is a looooong description");
HelpFormatter formatter = new HelpFormatter();
... | 809 | 851 |
Cli-26 | public static Option create(String opt) throws IllegalArgumentException
{
// create the option
Option option = new Option(opt, description);
// set the option properties
option.setLongOpt(longopt);
option.setRequired(required);
option.setOptionalArg(optionalArg);
opt... | public static Option create(String opt) throws IllegalArgumentException
{
Option option = null;
try {
// create the option
option = new Option(opt, description);
// set the option properties
option.setLongOpt(longopt);
option.setRequired(required);
option.setOpti... | src/java/org/apache/commons/cli/OptionBuilder.java | OptionBuilder is not reseted in case of an IAE at create | If the call to OptionBuilder.create() fails with an IllegalArgumentException, the OptionBuilder is not resetted and its next usage may contain unwanted settings. Actually this let the CLI-1.2 RCs fail on IBM JDK 6 running on Maven 2.0.10. | 346 | 364 |
Cli-27 | public void setSelected(Option option) throws AlreadySelectedException
{
if (option == null)
{
// reset the option previously selected
selected = null;
return;
}
// if no option has already been selected or the
// same option is being reselected then set the
// sele... | 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
// sele... | src/java/org/apache/commons/cli/OptionGroup.java | Unable to select a pure long option in a group | OptionGroup doesn't play nice with options with a long name and no short name. If the selected option hasn't a short name, group.setSelected(option) has no effect. | 86 | 106 |
Cli-28 | protected void processProperties(Properties properties)
{
if (properties == null)
{
return;
}
for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)
{
String option = e.nextElement().toString();
if (!cmd.hasOption(option))
{
Option opt = ... | 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 = ... | src/java/org/apache/commons/cli/Parser.java | Default options may be partially processed | The Properties instance passed to the Parser.parse() method to initialize the default options may be partially processed. This happens when the properties contains an option that doesn't accept arguments and has a default value that isn't evaluated to "true". When this case occurs the processing of the properties is st... | 252 | 296 |
Cli-29 | static String stripLeadingAndTrailingQuotes(String str)
{
if (str.startsWith("\""))
{
str = str.substring(1, str.length());
}
int length = str.length();
if (str.endsWith("\""))
{
str = str.substring(0, length - 1);
}
return str;
} | static String stripLeadingAndTrailingQuotes(String str)
{
int length = str.length();
if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1)
{
str = str.substring(1, length - 1);
}
return str;
} | src/java/org/apache/commons/cli/Util.java | Commons CLI incorrectly stripping leading and trailing quotes | org.apache.commons.cli.Parser.processArgs() calls Util.stripLeadingAndTrailingQuotes() for all argument values. IMHO this is incorrect and totally broken.
It is trivial to create a simple test for this. Output:
$ java -cp target/clitest.jar Clitest --balloo "this is a \"test\""
Value of argument balloo is 'this... | 63 | 76 |
Cli-3 | public static Number createNumber(String str)
{
try
{
return NumberUtils.createNumber(str);
}
catch (NumberFormatException nfe)
{
System.err.println(nfe.getMessage());
}
return null;
} | public static Number createNumber(String str)
{
try
{
if( str != null )
{
if( str.indexOf('.') != -1 )
{
return Double.valueOf(str);
}
else
{
return Long.va... | src/java/org/apache/commons/cli/TypeHandler.java | PosixParser interupts "-target opt" as "-t arget opt" | This was posted on the Commons-Developer list and confirmed as a bug.
> Is this a bug? Or am I using this incorrectly?
> I have an option with short and long values. Given code that is
> essentially what is below, with a PosixParser I see results as
> follows:
>
> A command line with just "-t" prints out the resu... | 158 | 170 |
Cli-32 | protected int findWrapPos(String text, int width, int startPos)
{
int pos;
// the line ends before the max wrap pos or a new line char found
if (((pos = text.indexOf('\n', startPos)) != -1 && pos <= width)
|| ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width))
{
return... | 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... | src/main/java/org/apache/commons/cli/HelpFormatter.java | StringIndexOutOfBoundsException in HelpFormatter.findWrapPos | In the last while loop in HelpFormatter.findWrapPos, it can pass text.length() to text.charAt(int), which throws a StringIndexOutOfBoundsException. The first expression in that while loop condition should use a <, not a <=.
This is on line 908 in r779646:
http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/o... | 902 | 943 |
Cli-33 | public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text)
{
StringBuffer sb = new StringBuffer(text.length());
renderWrappedText(sb, width, nextLineTabStop, text);
pw.println(sb.toString());
} | public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text)
{
StringBuffer sb = new StringBuffer(text.length());
renderWrappedTextBlock(sb, width, nextLineTabStop, text);
pw.println(sb.toString());
} | src/main/java/org/apache/commons/cli/HelpFormatter.java | HelpFormatter strips leading whitespaces in the footer | I discovered a bug in Commons CLI while using it through Groovy's CliBuilder. See the following issue:
http://jira.codehaus.org/browse/GROOVY-4313?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
Copied:
The following code:
def cli = new CliBuilder(footer: "line1:\n line2:\n")
cli.usage()
Produces ... | 726 | 732 |
Cli-35 | public List<String> getMatchingOptions(String opt)
{
opt = Util.stripLeadingHyphens(opt);
List<String> matchingOpts = new ArrayList<String>();
// for a perfect match return the single option only
for (String longOpt : longOpts.keySet())
{
if (longOpt.startsWith(opt))
{
... | public List<String> getMatchingOptions(String opt)
{
opt = Util.stripLeadingHyphens(opt);
List<String> matchingOpts = new ArrayList<String>();
// for a perfect match return the single option only
if(longOpts.keySet().contains(opt)) {
return Collections.singletonList(opt);
}
for (S... | src/main/java/org/apache/commons/cli/Options.java | LongOpt falsely detected as ambiguous | Options options = new Options();
options.addOption(Option.builder().longOpt("importToOpen").hasArg().argName("FILE").build());
options.addOption(Option.builder("i").longOpt("import").hasArg().argName("FILE").build());
Parsing "--import=FILE" is not possible since 1.3 as it throws a AmbiguousOptionException stating that... | 233 | 250 |
Cli-37 | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
return token.startsWith("-") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2));
// remove leading "-" and "=value"
} | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = pos == -1 ? token.substring(1) : toke... | src/main/java/org/apache/commons/cli/DefaultParser.java | Optional argument picking up next regular option as its argument | I'm not sure if this is a complete fix. It seems to miss the case where short options are concatenated after an option that takes an optional argument.
A failing test case for this would be to modify {{setUp()}} in BugCLI265Test.java to include short options "a" and "b":
{code:java}
@Before
public void setUp... | 299 | 305 |
Cli-38 | private boolean isShortOption(String token)
{
// short options (-S, -SV, -S=V, -SV1=V2, -S1S2)
if (!token.startsWith("-") || token.length() == 1)
{
return false;
}
// remove leading "-" and "=value"
int pos = token.indexOf("=");
String optName = pos == -1 ? token.substring(1) : toke... | 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) : toke... | src/main/java/org/apache/commons/cli/DefaultParser.java | Optional argument picking up next regular option as its argument | I have recently migrated a project from CLI 1.2 to 1.3.1 and have encountered what may be a bug or difference in the way optional arguments are being processed.
I have a command that opens several different kinds of databases by type, or alternately, the last opened database of that type.
Option TYPE1 = Option.builde... | 299 | 312 |
Cli-39 | public static Object createValue(final String str, final Class<?> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return createObject(str);
}
... | 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);
}
... | src/main/java/org/apache/commons/cli/TypeHandler.java | Option parser type EXISTING_FILE_VALUE not check file existing | When the user pass option type FileInputStream.class, I think the expected behavior for the return value is the same type, which the user passed.
Options options = new Options();
options.addOption(Option.builder("f").hasArg().type(FileInputStream.class).build());
CommandLine cline = new DefaultParser().parse(options, ... | 64 | 106 |
Cli-4 | private void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (requiredOptions.size() > 0)
{
Iterator iter = requiredOptions.iterator();
StringBuffer buff = new StringBuffer();
// loop through the re... | private void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (requiredOptions.size() > 0)
{
Iterator iter = requiredOptions.iterator();
StringBuffer buff = new StringBuffer("Missing required option");
... | src/java/org/apache/commons/cli/Parser.java | PosixParser interupts "-target opt" as "-t arget opt" | This was posted on the Commons-Developer list and confirmed as a bug.
> Is this a bug? Or am I using this incorrectly?
> I have an option with short and long values. Given code that is
> essentially what is below, with a PosixParser I see results as
> follows:
>
> A command line with just "-t" prints out the resul... | 290 | 309 |
Cli-40 | public static <T> T createValue(final String str, final Class<T> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return (T) str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return (T) createObject(str);
}
else if (PatternOptionBui... | public static <T> T createValue(final String str, final Class<T> clazz) throws ParseException
{
if (PatternOptionBuilder.STRING_VALUE == clazz)
{
return (T) str;
}
else if (PatternOptionBuilder.OBJECT_VALUE == clazz)
{
return (T) createObject(str);
}
else if (PatternOptionBui... | src/main/java/org/apache/commons/cli/TypeHandler.java | TypeHandler should throw ParseException for an unsupported class | JavaDoc for TypeHandler states that createValue will
* @throws ParseException if the value creation for the given object type failedtype
However createValue(String str, Class<?> clazz) will return null if the clazz is unknown. | 63 | 105 |
Cli-5 | static String stripLeadingHyphens(String str)
{
if (str.startsWith("--"))
{
return str.substring(2, str.length());
}
else if (str.startsWith("-"))
{
return str.substring(1, str.length());
}
return str;
} | static String stripLeadingHyphens(String str)
{
if (str == null) {
return null;
}
if (str.startsWith("--"))
{
return str.substring(2, str.length());
}
else if (str.startsWith("-"))
{
return str.substring(1, str.length());
}
return str;
} | src/java/org/apache/commons/cli/Util.java | NullPointerException in Util.stripLeadingHyphens when passed a null argument | If you try to do a hasOption(null), you get a NPE:
java.lang.NullPointerException
at org.apache.commons.cli.Util.stripLeadingHyphens(Util.java:39)
at org.apache.commons.cli.CommandLine.resolveOption(CommandLine.java:166)
at org.apache.commons.cli.CommandLine.hasOption(CommandLine.java:68)
Either hasOption should rej... | 34 | 46 |
Cli-8 | protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).a... | 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))).a... | src/java/org/apache/commons/cli/HelpFormatter.java | HelpFormatter wraps incorrectly on every line beyond the first | The method findWrapPos(...) in the HelpFormatter is a couple of bugs in the way that it deals with the "startPos" variable. This causes it to format every line beyond the first line by "startPos" to many characters, beyond the specified width.
To see this, create an option with a long description, and then use the h... | 792 | 823 |
Cli-9 | protected void checkRequiredOptions()
throws MissingOptionException
{
// if there are required options that have not been
// processsed
if (getRequiredOptions().size() > 0)
{
Iterator iter = getRequiredOptions().iterator();
StringBuffer buff = new StringBuffer("Missing required optio... | 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 optio... | src/java/org/apache/commons/cli/Parser.java | MissingOptionException.getMessage() changed from CLI 1.0 > 1.1 | The MissingOptionException.getMessage() string changed from CLI 1.0 > 1.1.
CLI 1.0 was poorly formatted but readable:
Missing required options: -format-source-properties
CLI 1.1 is almost unreadable:
Missing required options: formatsourceproperties
In CLI 1.0 Options.addOption(Option) prefixed the stored options with ... | 303 | 324 |
Closure-1 | private void removeUnreferencedFunctionArgs(Scope fnScope) {
// Notice that removing unreferenced function args breaks
// Function.prototype.length. In advanced mode, we don't really care
// about this: we consider "length" the equivalent of reflecting on
// the function's lexical source.
//
// Rather than ... | 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 ... | src/com/google/javascript/jscomp/RemoveUnusedVars.java | function arguments should not be optimized away | Function arguments should not be optimized away, as this comprimizes the function's length property.
What steps will reproduce the problem?
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==
function foo (bar, baz) {
return bar;
}
alert ... | 369 | 406 |
Closure-10 | static boolean mayBeString(Node n, boolean recurse) {
if (recurse) {
return allResultsMatch(n, MAY_BE_STRING_PREDICATE);
} else {
return mayBeStringHelper(n);
}
} | static boolean mayBeString(Node n, boolean recurse) {
if (recurse) {
return anyResultsMatch(n, MAY_BE_STRING_PREDICATE);
} else {
return mayBeStringHelper(n);
}
} | src/com/google/javascript/jscomp/NodeUtil.java | Wrong code generated if mixing types in ternary operator | What steps will reproduce the problem?
1. Use Google Closure Compiler to compile this code:
var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;
You can either simple or advanced. It doesn't matter
What is the expected output? What do you see instead?
I'm seeing this as a result:
var a = (0.5 < Math.random() ?... | 1,415 | 1,421 |
Closure-101 | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new ClosureCodingConvention());
CompilationLevel level = flags.compilation_level;
level.setOptionsForCompilationLevel(options);
if (flags.debug) {
level.setDebugOptionsForCompilationLev... | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new ClosureCodingConvention());
CompilationLevel level = flags.compilation_level;
level.setOptionsForCompilationLevel(options);
if (flags.debug) {
level.setDebugOptionsForCompilationLev... | src/com/google/javascript/jscomp/CommandLineRunner.java | --process_closure_primitives can't be set to false | What steps will reproduce the problem?
1. compile a file with "--process_closure_primitives false"
2. compile a file with "--process_closure_primitives true" (default)
3. result: primitives are processed in both cases.
What is the expected output? What do you see instead?
The file should still have its goog.provide... | 419 | 439 |
Closure-102 | public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
if (MAKE_LOCAL_NAMES_UNIQUE) {
MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
NodeTraversal t = new NodeTraversal(compiler, renamer);
t.traverseRoots(externs, root);
}
removeDuplicateDeclar... | public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
removeDuplicateDeclarations(root);
if (MAKE_LOCAL_NAMES_UNIQUE) {
MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
NodeTraversal t = new NodeTraversal(compiler, renamer);
t.traverseRoots(extern... | src/com/google/javascript/jscomp/Normalize.java | compiler assumes that 'arguments' can be shadowed | The code:
function name() {
var arguments = Array.prototype.slice.call(arguments, 0);
}
gets compiled to:
function name(){ var c=Array.prototype.slice.call(c,0); }
Thanks to tescosquirrel for the report. | 87 | 97 |
Closure-104 | JSType meet(JSType that) {
UnionTypeBuilder builder = new UnionTypeBuilder(registry);
for (JSType alternate : alternates) {
if (alternate.isSubtype(that)) {
builder.addAlternate(alternate);
}
}
if (that instanceof UnionType) {
for (JSType otherAlternate : ((UnionType) that).alternates) {
... | 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) {
... | src/com/google/javascript/rhino/jstype/UnionType.java | Typos in externs/html5.js | Line 354:
CanvasRenderingContext2D.prototype.globalCompositingOperation;
Line 366:
CanvasRenderingContext2D.prototype.mitreLimit;
They should be globalCompositeOperation and miterLimit, respectively. | 273 | 298 |
Closure-107 | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
if (flags.processJqueryPrimitives) {
options.setCodingConvention(new JqueryCodingConvention());
} else {
options.setCodingConvention(new ClosureCodingConvention());
}
options.setExtraAnnotationNames(flags.ext... | protected CompilerOptions createOptions() {
CompilerOptions options = new CompilerOptions();
if (flags.processJqueryPrimitives) {
options.setCodingConvention(new JqueryCodingConvention());
} else {
options.setCodingConvention(new ClosureCodingConvention());
}
options.setExtraAnnotationNames(flags.ext... | src/com/google/javascript/jscomp/CommandLineRunner.java | Variable names prefixed with MSG_ cause error with advanced optimizations | Variables named something with MSG_ seem to cause problems with the module system, even if no modules are used in the code.
$ echo "var MSG_foo='bar'" | closure --compilation_level ADVANCED_OPTIMIZATIONS
stdin:1: ERROR - message not initialized using goog.getMsg
var MSG_foo='bar'
^
It works fine with msg_foo... | 806 | 865 |
Closure-109 | private Node parseContextTypeExpression(JsDocToken token) {
return parseTypeName(token);
} | private Node parseContextTypeExpression(JsDocToken token) {
if (token == JsDocToken.QMARK) {
return newNode(Token.QMARK);
} else {
return parseBasicTypeExpression(token);
}
} | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | Constructor types that return all or unknown fail to parse | Constructor types that return the all type or the unknown type currently fail to parse:
/** @type {function(new:?)} */ var foo = function() {};
/** @type {function(new:*)} */ var bar = function() {};
foo.js:1: ERROR - Bad type annotation. type not recognized due to syntax error
/** @type {function(new:?)} */ var ... | 1,907 | 1,909 |
Closure-11 | private void visitGetProp(NodeTraversal t, Node n, Node parent) {
// obj.prop or obj.method()
// Lots of types can appear on the left, a call to a void function can
// never be on the left. getPropertyType will decide what is acceptable
// and what isn't.
Node property = n.getLastChild();
Node objNode = n.g... | 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.g... | src/com/google/javascript/jscomp/TypeCheck.java | Record type invalid property not reported on function with @this annotation | Code:
var makeClass = function(protoMethods) {
var clazz = function() {
this.initialize.apply(this, arguments);
}
for (var i in protoMethods) {
clazz.prototype[i] = protoMethods[i];
}
return clazz;
}
/**
* @constructor
* @param {{name: string, height: number}} options
*/
var Person... | 1,303 | 1,321 |
Closure-111 | protected JSType caseTopType(JSType topType) {
return topType;
} | protected JSType caseTopType(JSType topType) {
return topType.isAllType() ?
getNativeType(ARRAY_TYPE) : topType;
} | src/com/google/javascript/jscomp/type/ClosureReverseAbstractInterpreter.java | goog.isArray doesn't hint compiler | What steps will reproduce the problem?
1.
/**
* @param {*} object
* @return {*}
*/
var test = function(object) {
if (goog.isArray(object)) {
/** @type {Array} */ var x = object;
return x;
}
};
2. ADVANCED_OPTIMIZATIONS
What is the expected output? What do you see instead?
ERROR - initializ... | 53 | 55 |
Closure-112 | private boolean inferTemplatedTypesForCall(
Node n, FunctionType fnType) {
final ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap()
.getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> inferred =
inferTemplateT... | private boolean inferTemplatedTypesForCall(
Node n, FunctionType fnType) {
final ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap()
.getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> inferred = Maps.filterKeys(
... | src/com/google/javascript/jscomp/TypeInference.java | Template types on methods incorrectly trigger inference of a template on the class if that template type is unknown | See i.e.
/**
* @constructor
* @template CLASS
*/
var Class = function() {};
/**
* @param {function(CLASS):CLASS} a
* @template T
*/
Class.prototype.foo = function(a) {
return 'string';
};
/** @param {number} a
* @return {string} */
var a = function(a) { return '' };
new Class().foo(a... | 1,183 | 1,210 |
Closure-113 | private void processRequireCall(NodeTraversal t, Node n, Node parent) {
Node left = n.getFirstChild();
Node arg = left.getNext();
if (verifyLastArgumentIsString(t, left, arg)) {
String ns = arg.getString();
ProvidedName provided = providedNames.get(ns);
if (provided == null || !provided.isExplicitlyPr... | 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.isExplicitlyPr... | src/com/google/javascript/jscomp/ProcessClosurePrimitives.java | Bug in require calls processing | The Problem
ProcessClosurePrimitives pass has a bug in processRequireCall method.
The method processes goog.require calls. If a require symbol is invalid i.e is not provided anywhere, the method collects it for further error reporting. If the require symbol is valid, the method removes it from the ast.
All invalid... | 295 | 334 |
Closure-117 | String getReadableJSTypeName(Node n, boolean dereference) {
// The best type name is the actual type name.
// If we're analyzing a GETPROP, the property may be inherited by the
// prototype chain. So climb the prototype chain and find out where
// the property was originally defined.
if (n.isGetProp()) {
... | String getReadableJSTypeName(Node n, boolean dereference) {
JSType type = getJSType(n);
if (dereference) {
ObjectType dereferenced = type.dereference();
if (dereferenced != null) {
type = dereferenced;
}
}
// The best type name is the actual type name.
if (type.isFunctionPrototypeType() ||
... | src/com/google/javascript/jscomp/TypeValidator.java | Wrong type name reported on missing property error. | /**
* @constructor
*/
function C2() {}
/**
* @constructor
*/
function C3(c2) {
/**
* @type {C2}
* @private
*/
this.c2_;
use(this.c2_.prop);
}
Produces:
Property prop never defined on C3.c2_
But should be:
Property prop never defined on C2 | 724 | 777 |
Closure-118 | private void handleObjectLit(NodeTraversal t, Node n) {
for (Node child = n.getFirstChild();
child != null;
child = child.getNext()) {
// Maybe STRING, GET, SET
// We should never see a mix of numbers and strings.
String name = child.getString();
T type = typeSystem.getType(getScope(), n,... | private void handleObjectLit(NodeTraversal t, Node n) {
for (Node child = n.getFirstChild();
child != null;
child = child.getNext()) {
// Maybe STRING, GET, SET
if (child.isQuotedString()) {
continue;
}
// We should never see a mix of numbers and strings.
String name = child.get... | src/com/google/javascript/jscomp/DisambiguateProperties.java | Prototype method incorrectly removed | // ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// ==/ClosureCompiler==
/** @const */
var foo = {};
foo.bar = {
'bar1': function() { console.log('bar1'); }
}
/** @constructor */
function foobar() {}
foobar.prototype = foo.ba... | 490 | 513 |
Closure-12 | private boolean hasExceptionHandler(Node cfgNode) {
return false;
} | private boolean hasExceptionHandler(Node cfgNode) {
List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(cfgNode);
for (DiGraphEdge<Node, Branch> edge : branchEdges) {
if (edge.getValue() == Branch.ON_EX) {
return true;
}
}
return false;
} | src/com/google/javascript/jscomp/MaybeReachingVariableUse.java | Try/catch blocks incorporate code not inside original blocks | What steps will reproduce the problem?
Starting with this code:
-----
function a() {
var x = '1';
try {
x += somefunction();
} catch(e) {
}
x += "2";
try {
x += somefunction();
} catch(e) {
}
document.write(x);
}
a();
a();
-----
It gets compiled to:
-----
function b() {
var a;
... | 159 | 161 |
Closure-120 | boolean isAssignedOnceInLifetime() {
Reference ref = getOneAndOnlyAssignment();
if (ref == null) {
return false;
}
// Make sure this assignment is not in a loop.
for (BasicBlock block = ref.getBasicBlock();
block != null; block = block.getParent()) {
if (block.isFunction) {
break;
} ... | boolean isAssignedOnceInLifetime() {
Reference ref = getOneAndOnlyAssignment();
if (ref == null) {
return false;
}
// Make sure this assignment is not in a loop.
for (BasicBlock block = ref.getBasicBlock();
block != null; block = block.getParent()) {
if (block.isFunction) {
if (ref.getSy... | src/com/google/javascript/jscomp/ReferenceCollectingCallback.java | Overzealous optimization confuses variables | The following code:
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==
var uid;
function reset() {
uid = Math.random();
}
function doStuff() {
reset();
var _uid = uid;
if (uid < 0.5) {
doStuff();
}
if (_uid !== uid) {
throw 'reset() was... | 421 | 438 |
Closure-122 | private void handleBlockComment(Comment comment) {
if (comment.getValue().indexOf("/* @") != -1 || comment.getValue().indexOf("\n * @") != -1) {
errorReporter.warning(
SUSPICIOUS_COMMENT_WARNING,
sourceName,
comment.getLineno(), "", 0);
}
} | private void handleBlockComment(Comment comment) {
Pattern p = Pattern.compile("(/|(\n[ \t]*))\\*[ \t]*@[a-zA-Z]");
if (p.matcher(comment.getValue()).find()) {
errorReporter.warning(
SUSPICIOUS_COMMENT_WARNING,
sourceName,
comment.getLineno(), "", 0);
}
} | src/com/google/javascript/jscomp/parsing/IRFactory.java | Inconsistent handling of non-JSDoc comments | What steps will reproduce the problem?
1.
2.
3.
What is the expected output? What do you see instead?
When given:
/* @preserve Foo License */
alert("foo");
It spits out:
stdin:1: WARNING - Parse error. Non-JSDoc comment has annotations. Did you mean to start it with '/**'?
/* @license Foo Licen... | 251 | 258 |
Closure-124 | private boolean isSafeReplacement(Node node, Node replacement) {
// No checks are needed for simple names.
if (node.isName()) {
return true;
}
Preconditions.checkArgument(node.isGetProp());
node = node.getFirstChild();
if (node.isName()
&& isNameAssignedTo(node.getString(), replacement)) {
... | private boolean isSafeReplacement(Node node, Node replacement) {
// No checks are needed for simple names.
if (node.isName()) {
return true;
}
Preconditions.checkArgument(node.isGetProp());
while (node.isGetProp()) {
node = node.getFirstChild();
}
if (node.isName()
&& isNameAssignedTo(node.... | src/com/google/javascript/jscomp/ExploitAssigns.java | Different output from RestAPI and command line jar | When I compile using the jar file from the command line I get a result that is not correct. However, when I test it via the REST API or the Web UI I get a correct output. I've attached a file with the code that we are compiling.
What steps will reproduce the problem?
1. Compile the attached file with "java -jar compi... | 206 | 220 |
Closure-128 | static boolean isSimpleNumber(String s) {
int len = s.length();
for (int index = 0; index < len; index++) {
char c = s.charAt(index);
if (c < '0' || c > '9') {
return false;
}
}
return len > 0 && s.charAt(0) != '0';
} | static boolean isSimpleNumber(String s) {
int len = s.length();
if (len == 0) {
return false;
}
for (int index = 0; index < len; index++) {
char c = s.charAt(index);
if (c < '0' || c > '9') {
return false;
}
}
return len == 1 || s.charAt(0) != '0';
} | src/com/google/javascript/jscomp/CodeGenerator.java | The compiler quotes the "0" keys in object literals | What steps will reproduce the problem?
1. Compile alert({0:0, 1:1});
What is the expected output?
alert({0:0, 1:1});
What do you see instead?
alert({"0":0, 1:1});
What version of the product are you using? On what operating system?
Latest version on Goobuntu. | 783 | 792 |
Closure-129 | private void annotateCalls(Node n) {
Preconditions.checkState(n.isCall());
// Keep track of of the "this" context of a call. A call without an
// explicit "this" is a free call.
Node first = n.getFirstChild();
// ignore cast nodes.
if (!NodeUtil.isGet(first)) {
n.putBooleanProp(Node.FREE_CALL, true)... | private void annotateCalls(Node n) {
Preconditions.checkState(n.isCall());
// Keep track of of the "this" context of a call. A call without an
// explicit "this" is a free call.
Node first = n.getFirstChild();
// ignore cast nodes.
while (first.isCast()) {
first = first.getFirstChild();
}
if (!N... | src/com/google/javascript/jscomp/PrepareAst.java | Casting a function before calling it produces bad code and breaks plugin code | 1. Compile this code with ADVANCED_OPTIMIZATIONS:
console.log( /** @type {function(!string):!string} */ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable'])( '$version' ) );
produces:
'use strict';console.log((0,(new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable)("$ve... | 158 | 177 |
Closure-13 | private void traverse(Node node) {
// The goal here is to avoid retraversing
// the entire AST to catch newly created opportunities.
// So we track whether a "unit of code" has changed,
// and revisit immediately.
if (!shouldVisit(node)) {
return;
}
int visits = 0;
do {
Node c = node.getFirstCh... | 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.getFirstCh... | src/com/google/javascript/jscomp/PeepholeOptimizationsPass.java | true/false are not always replaced for !0/!1 | What steps will reproduce the problem?
function some_function() {
var fn1;
var fn2;
if (any_expression) {
fn2 = external_ref;
fn1 = function (content) {
return fn2();
}
}
return {
method1: function () {
if (fn1) fn1();
return true;
},
method2: functio... | 113 | 138 |
Closure-130 | private void inlineAliases(GlobalNamespace namespace) {
// Invariant: All the names in the worklist meet condition (a).
Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest());
while (!workList.isEmpty()) {
Name name = workList.pop();
// Don't attempt to inline a getter or setter property ... | private void inlineAliases(GlobalNamespace namespace) {
// Invariant: All the names in the worklist meet condition (a).
Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest());
while (!workList.isEmpty()) {
Name name = workList.pop();
// Don't attempt to inline a getter or setter property ... | src/com/google/javascript/jscomp/CollapseProperties.java | arguments is moved to another scope | Using ADVANCED_OPTIMIZATIONS with CompilerOptions.collapsePropertiesOnExternTypes = true a script I used broke, it was something like:
function () {
return function () {
var arg = arguments;
setTimeout(function() { alert(args); }, 0);
}
}
Unfortunately it was rewritten to:
function () {
return... | 161 | 197 |
Closure-131 | public static boolean isJSIdentifier(String s) {
int length = s.length();
if (length == 0 ||
!Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < length; i++) {
if (
!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return tr... | public static boolean isJSIdentifier(String s) {
int length = s.length();
if (length == 0 ||
Character.isIdentifierIgnorable(s.charAt(0)) ||
!Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < length; i++) {
if (Character.isIdentifierIgnorable(s.charAt(i)) ... | src/com/google/javascript/rhino/TokenStream.java | unicode characters in property names result in invalid output | What steps will reproduce the problem?
1. use unicode characters in a property name for an object, like this:
var test={"a\u0004b":"c"};
2. compile
What is the expected output? What do you see instead?
Because unicode characters are not allowed in property names without quotes, the output should be the same as the... | 190 | 206 |
Closure-133 | private String getRemainingJSDocLine() {
String result = stream.getRemainingJSDocLine();
return result;
} | private String getRemainingJSDocLine() {
String result = stream.getRemainingJSDocLine();
unreadToken = NO_UNREAD_TOKEN;
return result;
} | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | Exception when parsing erroneous jsdoc: /**@return {@code foo} bar * baz. */ | The following causes an exception in JSDocInfoParser.
/**
* @return {@code foo} bar
* baz. */
var x;
Fix to follow. | 2,399 | 2,402 |
Closure-145 | private boolean isOneExactlyFunctionOrDo(Node n) {
// For labels with block children, we need to ensure that a
// labeled FUNCTION or DO isn't generated when extraneous BLOCKs
// are skipped.
// Either a empty statement or an block with more than one child,
// way it isn't a FUNCTION... | private boolean isOneExactlyFunctionOrDo(Node n) {
if (n.getType() == Token.LABEL) {
Node labeledStatement = n.getLastChild();
if (labeledStatement.getType() != Token.BLOCK) {
return isOneExactlyFunctionOrDo(labeledStatement);
} else {
// For labels with block children, we need to ensure that ... | src/com/google/javascript/jscomp/CodeGenerator.java | Bug with labeled loops and breaks | What steps will reproduce the problem?
Try to compile this code with the closure compiler :
var i = 0;
lab1: do{
lab2: do{
i++;
if (1) {
break lab2;
} else {
break lab1;
}
} while(false);
} while(false);
console.log(i);
What is ... | 708 | 715 |
Closure-146 | public TypePair getTypesUnderInequality(JSType that) {
// unions types
if (that instanceof UnionType) {
TypePair p = that.getTypesUnderInequality(this);
return new TypePair(p.typeB, p.typeA);
}
// other types
switch (this.testForEquality(that)) {
case TRUE:
return new TypePair(null, null);
... | public TypePair getTypesUnderInequality(JSType that) {
// unions types
if (that instanceof UnionType) {
TypePair p = that.getTypesUnderInequality(this);
return new TypePair(p.typeB, p.typeA);
}
// other types
switch (this.testForEquality(that)) {
case TRUE:
JSType noType = getNativeType(JST... | src/com/google/javascript/rhino/jstype/JSType.java | bad type inference for != undefined | What steps will reproduce the problem?
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==
/** @param {string} x */
function g(x) {}
/** @param {undefined} x */
function f(x) {
if (x != undefined) { g(x); }
}
What is the expected ou... | 696 | 715 |
Closure-15 | public boolean apply(Node n) {
// When the node is null it means, we reached the implicit return
// where the function returns (possibly without an return statement)
if (n == null) {
return false;
}
// TODO(user): We only care about calls to functions that
// passes one of the dependent variable to a n... | 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 n... | src/com/google/javascript/jscomp/FlowSensitiveInlineVariables.java | Switched order of "delete key" and "key in" statements changes semantic | // Input:
var customData = { key: 'value' };
function testRemoveKey( key ) {
var dataSlot = customData,
retval = dataSlot && dataSlot[ key ],
hadKey = dataSlot && ( key in dataSlot );
if ( dataSlot )
delete dataSlot[ key ];
return hadKey ? retval : null;
};
console.log( testRemoveKey( 'key' ) );... | 84 | 109 |
Closure-150 | @Override public void visit(NodeTraversal t, Node n, Node parent) {
if (n == scope.getRootNode()) return;
if (n.getType() == Token.LP && parent == scope.getRootNode()) {
handleFunctionInputs(parent);
return;
}
attachLiteralTypes(n);
switch (n.getType()) {
case Token.FUNCTION:
if (parent.ge... | @Override public void visit(NodeTraversal t, Node n, Node parent) {
if (n == scope.getRootNode()) return;
if (n.getType() == Token.LP && parent == scope.getRootNode()) {
handleFunctionInputs(parent);
return;
}
super.visit(t, n, parent);
} | src/com/google/javascript/jscomp/TypedScopeCreator.java | Type checker misses annotations on functions defined within functions | What steps will reproduce the problem?
1. Compile the following code under --warning_level VERBOSE
var ns = {};
/** @param {string=} b */
ns.a = function(b) {}
function d() {
ns.a();
ns.a(123);
}
2. Observe that the type checker correctly emits one warning, as 123
doesn't match the type {string}
... | 1,443 | 1,466 |
Closure-159 | private void findCalledFunctions(
Node node, Set<String> changed) {
Preconditions.checkArgument(changed != null);
// For each referenced function, add a new reference
if (node.getType() == Token.CALL) {
Node child = node.getFirstChild();
if (child.getType() == Token.NAME) {
changed.add(child.get... | private void findCalledFunctions(
Node node, Set<String> changed) {
Preconditions.checkArgument(changed != null);
// For each referenced function, add a new reference
if (node.getType() == Token.NAME) {
if (isCandidateUsage(node)) {
changed.add(node.getString());
}
}
for (Node c = node.getF... | src/com/google/javascript/jscomp/InlineFunctions.java | Closure Compiler failed to translate all instances of a function name | What steps will reproduce the problem?
1. Compile the attached jQuery Multicheck plugin using SIMPLE optimization.
What is the expected output? What do you see instead?
You expect that the function preload_check_all() gets its name translated appropriately. In fact, the Closure Compiler breaks the code by changing th... | 773 | 787 |
Closure-161 | private Node tryFoldArrayAccess(Node n, Node left, Node right) {
Node parent = n.getParent();
// If GETPROP/GETELEM is used as assignment target the array literal is
// acting as a temporary we can't fold it here:
// "[][0] += 1"
if (right.getType() != Token.NUMBER) {
// Sometimes people like to use c... | private Node tryFoldArrayAccess(Node n, Node left, Node right) {
Node parent = n.getParent();
// If GETPROP/GETELEM is used as assignment target the array literal is
// acting as a temporary we can't fold it here:
// "[][0] += 1"
if (isAssignmentTarget(n)) {
return n;
}
if (right.getType() != Toke... | src/com/google/javascript/jscomp/PeepholeFoldConstants.java | peephole constants folding pass is trying to fold [][11] as if it were a property lookup instead of a property assignment | What steps will reproduce the problem?
1.Try on line CC with Advance
2.On the following 2-line code
3.
What is the expected output? What do you see instead?
// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==
var Mdt=[];
Mdt[11] = ['22','19... | 1,278 | 1,322 |
Closure-166 | public void matchConstraint(JSType constraint) {
// We only want to match constraints on anonymous types.
if (hasReferenceName()) {
return;
}
// Handle the case where the constraint object is a record type.
//
// param constraint {{prop: (number|undefined)}}
// function f(constraint) {}
// f({});
... | 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({});
... | src/com/google/javascript/rhino/jstype/PrototypeObjectType.java | anonymous object type inference inconsistency when used in union | Code:
/** @param {{prop: string, prop2: (string|undefined)}} record */
var func = function(record) {
window.console.log(record.prop);
}
/** @param {{prop: string, prop2: (string|undefined)}|string} record */
var func2 = function(record) {
if (typeof record == 'string') {
window.console.log(record);
... | 556 | 574 |
Closure-172 | private boolean isQualifiedNameInferred(
String qName, Node n, JSDocInfo info,
Node rhsValue, JSType valueType) {
if (valueType == null) {
return true;
}
// Prototypes of constructors and interfaces are always declared.
if (qName != null && qName.endsWith(".prototype")) {
return false;
}
... | private boolean isQualifiedNameInferred(
String qName, Node n, JSDocInfo info,
Node rhsValue, JSType valueType) {
if (valueType == null) {
return true;
}
// Prototypes of constructors and interfaces are always declared.
if (qName != null && qName.endsWith(".prototype")) {
String className = qNa... | src/com/google/javascript/jscomp/TypedScopeCreator.java | Type of prototype property incorrectly inferred to string | What steps will reproduce the problem?
1. Compile the following code:
/** @param {Object} a */
function f(a) {
a.prototype = '__proto';
}
/** @param {Object} a */
function g(a) {
a.prototype = function(){};
}
What is the expected output? What do you see instead?
Should type check. Instead, gives error:... | 1,661 | 1,709 |
Closure-20 | private Node tryFoldSimpleFunctionCall(Node n) {
Preconditions.checkState(n.isCall());
Node callTarget = n.getFirstChild();
if (callTarget != null && callTarget.isName() &&
callTarget.getString().equals("String")) {
// Fold String(a) to '' + (a) on immutable literals,
// which allows further optim... | 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 optim... | src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java | String conversion optimization is incorrect | What steps will reproduce the problem?
var f = {
valueOf: function() { return undefined; }
}
String(f)
What is the expected output? What do you see instead?
Expected output: "[object Object]"
Actual output: "undefined"
What version of the product are you using? On what operating system?
All versions (http:... | 208 | 230 |
Closure-23 | private Node tryFoldArrayAccess(Node n, Node left, Node right) {
Node parent = n.getParent();
// If GETPROP/GETELEM is used as assignment target the array literal is
// acting as a temporary we can't fold it here:
// "[][0] += 1"
if (isAssignmentTarget(n)) {
return n;
}
if (!right.isNumber()) {
... | 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()) {
... | src/com/google/javascript/jscomp/PeepholeFoldConstants.java | tryFoldArrayAccess does not check for side effects | What steps will reproduce the problem?
1. Compile the following program with simple or advanced optimization:
console.log([console.log('hello, '), 'world!'][1]);
What is the expected output? What do you see instead?
The expected output would preserve side effects. It would not transform the program at all or transfo... | 1,422 | 1,472 |
Closure-24 | private void findAliases(NodeTraversal t) {
Scope scope = t.getScope();
for (Var v : scope.getVarIterable()) {
Node n = v.getNode();
int type = n.getType();
Node parent = n.getParent();
if (parent.isVar()) {
if (n.hasChildren() && n.getFirstChild().isQualifiedName()) {
String name = n.ge... | private void findAliases(NodeTraversal t) {
Scope scope = t.getScope();
for (Var v : scope.getVarIterable()) {
Node n = v.getNode();
int type = n.getType();
Node parent = n.getParent();
if (parent.isVar() &&
n.hasChildren() && n.getFirstChild().isQualifiedName()) {
String name = n.getS... | src/com/google/javascript/jscomp/ScopedAliases.java | goog.scope doesn't properly check declared functions | The following code is a compiler error:
goog.scope(function() {
var x = function(){};
});
but the following code is not:
goog.scope(function() {
function x() {}
});
Both code snippets should be a compiler error, because they prevent the goog.scope from being unboxed. | 272 | 297 |
Closure-25 | private FlowScope traverseNew(Node n, FlowScope scope) {
Node constructor = n.getFirstChild();
scope = traverse(constructor, scope);
JSType constructorType = constructor.getJSType();
JSType type = null;
if (constructorType != null) {
constructorType = constructorType.restrictByNotNullOrUndefined();
i... | private FlowScope traverseNew(Node n, FlowScope scope) {
scope = traverseChildren(n, scope);
Node constructor = n.getFirstChild();
JSType constructorType = constructor.getJSType();
JSType type = null;
if (constructorType != null) {
constructorType = constructorType.restrictByNotNullOrUndefined();
if ... | src/com/google/javascript/jscomp/TypeInference.java | anonymous object type inference behavior is different when calling constructors | The following compiles fine with:
java -jar build/compiler.jar --compilation_level=ADVANCED_OPTIMIZATIONS --jscomp_error=accessControls --jscomp_error=checkTypes --jscomp_error=checkVars --js ~/Desktop/reverse.js
reverse.js:
/**
* @param {{prop1: string, prop2: (number|undefined)}} parry
*/
function callz(parr... | 1,035 | 1,063 |
Closure-32 | private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
WhitespaceOption option) {
if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
token == JsDocToken.EOF) {
return new ExtractionInfo("", token);
}
stream.update();
int start... | private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,
WhitespaceOption option) {
if (token == JsDocToken.EOC || token == JsDocToken.EOL ||
token == JsDocToken.EOF) {
return new ExtractionInfo("", token);
}
stream.update();
int start... | src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java | Preserve doesn't preserve whitespace at start of line | What steps will reproduce the problem?
Code such as:
/**
* @preserve
This
was
ASCII
Art
*/
What is the expected output? What do you see instead?
The words line up on the left:
/*
This
was
ASCII
Art
*/
What version of the product are you using? On what operating system?
Live web veris... | 1,329 | 1,429 |
Closure-33 | public void matchConstraint(ObjectType constraintObj) {
// We only want to match contraints on anonymous types.
// Handle the case where the constraint object is a record type.
//
// param constraintObj {{prop: (number|undefined)}}
// function f(constraintObj) {}
// f({});
//
// We want to modify the o... | public void matchConstraint(ObjectType constraintObj) {
// We only want to match contraints on anonymous types.
if (hasReferenceName()) {
return;
}
// Handle the case where the constraint object is a record type.
//
// param constraintObj {{prop: (number|undefined)}}
// function f(constraintObj) {}
... | src/com/google/javascript/rhino/jstype/PrototypeObjectType.java | weird object literal invalid property error on unrelated object prototype | Apologies in advance for the convoluted repro case and the vague summary.
Compile the following code (attached as repro.js) with:
java -jar build/compiler.jar --compilation_level=ADVANCED_OPTIMIZATIONS --jscomp_error=accessControls --jscomp_error=checkTypes --jscomp_error=checkVars --js repro.js *
/**
* @param {... | 555 | 580 |
Closure-35 | private void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
}
ObjectType constraintObj =
ObjectType.cast(constraint.restrictByNotNullOrUndefined());
if (constraintObj != null && constraintObj.isRecordType()) {
ObjectTyp... | private void inferPropertyTypesToMatchConstraint(
JSType type, JSType constraint) {
if (type == null || constraint == null) {
return;
}
ObjectType constraintObj =
ObjectType.cast(constraint.restrictByNotNullOrUndefined());
if (constraintObj != null) {
type.matchConstraint(constraintObj);
}
... | src/com/google/javascript/jscomp/TypeInference.java | assignment to object in conditional causes type error on function w/ record type return type | slightly dodgy code :)
/** @returns {{prop1: (Object|undefined), prop2: (string|undefined), prop3: (string|undefined)}} */
function func(a, b) {
var results;
if (a) {
results = {};
results.prop1 = {a: 3};
}
if (b) {
results = results || {};
results.prop2 = 'prop2';
} else {
re... | 1,113 | 1,137 |
Closure-36 | private boolean canInline(
Reference declaration,
Reference initialization,
Reference reference) {
if (!isValidDeclaration(declaration)
|| !isValidInitialization(initialization)
|| !isValidReference(reference)) {
return false;
}
// If the value is read more than once, skip it.
// VA... | 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.
// VA... | src/com/google/javascript/jscomp/InlineVariables.java | goog.addSingletonGetter prevents unused class removal | What steps will reproduce the problem?
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// @formatting pretty_print,print_input_delimiter
// @warning_level VERBOSE
// @debug true
// ==/ClosureCompiler==
goog.provide('foo');
var ... | 519 | 580 |
Closure-38 | void addNumber(double x) {
// This is not pretty printing. This is to prevent misparsing of x- -4 as
// x--4 (which is a syntax error).
char prev = getLastChar();
boolean negativeZero = isNegativeZero(x);
if (x < 0 && prev == '-') {
add(" ");
}
if ((long) x == x && !negativeZero) {
long value = (... | void addNumber(double x) {
// This is not pretty printing. This is to prevent misparsing of x- -4 as
// x--4 (which is a syntax error).
char prev = getLastChar();
boolean negativeZero = isNegativeZero(x);
if ((x < 0 || negativeZero) && prev == '-') {
add(" ");
}
if ((long) x == x && !negativeZero) {
... | src/com/google/javascript/jscomp/CodeConsumer.java | Identifier minus a negative number needs a space between the "-"s | What steps will reproduce the problem?
1. Compile the attached file with java -jar build/compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js bulletfail.js --js_output_file cc.js
2. Try to run the file in a JS engine, for example node cc.js
What is the expected output? What do you see instead?... | 240 | 267 |
Closure-39 | String toStringHelper(boolean forAnnotations) {
if (hasReferenceName()) {
return getReferenceName();
} else if (prettyPrint) {
// Don't pretty print recursively.
prettyPrint = false;
// Use a tree set so that the properties are sorted.
Set<String> propertyNames = Sets.newTreeSet();
for (Obj... | String toStringHelper(boolean forAnnotations) {
if (hasReferenceName()) {
return getReferenceName();
} else if (prettyPrint) {
// Don't pretty print recursively.
prettyPrint = false;
// Use a tree set so that the properties are sorted.
Set<String> propertyNames = Sets.newTreeSet();
for (Obj... | src/com/google/javascript/rhino/jstype/PrototypeObjectType.java | externExport with @typedef can generate invalid externs | What steps will reproduce the problem?
1. Create a file that has a @typedef and code referencing the type def above and below the typedef declaration.
2. Run the closure compiler and grab the externExport string stored on the last result for review.
3. I have attached both source and output files displaying the issue... | 353 | 396 |
Closure-4 | JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) {
// TODO(user): Investigate whether it is really necessary to keep two
// different mechanisms for resolving named types, and if so, which order
// makes more sense. Now, resolution via registry is first in order to
// avoid triggering the ... | JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) {
// TODO(user): Investigate whether it is really necessary to keep two
// different mechanisms for resolving named types, and if so, which order
// makes more sense. Now, resolution via registry is first in order to
// avoid triggering the ... | src/com/google/javascript/rhino/jstype/NamedType.java | Converting from an interface type to a constructor which @implements itself causes stack overflow. | // Options: --externs externs/es3.js --property_renaming OFF --variable_renaming OFF --jscomp_warning=checkTypes --js=t.js
// File: t.js
/**
* @interface
*/
var OtherType = function() {}
/**
* @implements {MyType}
* @constructor
*/
var MyType = function() {}
/**
* @type {MyType}
*/
var x = /** @... | 184 | 212 |
Closure-40 | public void visit(NodeTraversal t, Node n, Node parent) {
// Record global variable and function declarations
if (t.inGlobalScope()) {
if (NodeUtil.isVarDeclaration(n)) {
NameInformation ns = createNameInformation(t, n, parent);
Preconditions.checkNotNull(ns);
recordSet(ns.name, n);
} els... | 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);
} els... | src/com/google/javascript/jscomp/NameAnalyzer.java | smartNameRemoval causing compiler crash | What steps will reproduce the problem?
Compiler the following code in advanced mode:
{{{
var goog = {};
goog.inherits = function(x, y) {};
var ns = {};
/** @constructor */ ns.PageSelectionModel = function(){};
/** @constructor */
ns.PageSelectionModel.FooEvent = function() {};
/** @constructor */
ns.PageSe... | 596 | 642 |
Closure-42 | Node processForInLoop(ForInLoop loopNode) {
// Return the bare minimum to put the AST in a valid state.
return newNode(
Token.FOR,
transform(loopNode.getIterator()),
transform(loopNode.getIteratedObject()),
transformBlock(loopNode.getBody()));
} | Node processForInLoop(ForInLoop loopNode) {
if (loopNode.isForEach()) {
errorReporter.error(
"unsupported language extension: for each",
sourceName,
loopNode.getLineno(), "", 0);
// Return the bare minimum to put the AST in a valid state.
return newNode(Token.EXPR_RESULT, Node.new... | src/com/google/javascript/jscomp/parsing/IRFactory.java | Simple "Whitespace only" compression removing "each" keyword from "for each (var x in arr)" loop | What steps will reproduce the problem?
See below code snippet before after compression
---Before---
contactcenter.screenpop.updatePopStatus = function(stamp, status) {
for each ( var curTiming in this.timeLog.timings ) {
if ( curTiming.callId == stamp ) {
curTiming.flag = status;
break;
}
}
};
---After---
c... | 567 | 575 |
Closure-44 | void add(String newcode) {
maybeEndStatement();
if (newcode.length() == 0) {
return;
}
char c = newcode.charAt(0);
if ((isWordChar(c) || c == '\\') &&
isWordChar(getLastChar())) {
// need space to separate. This is not pretty printing.
// For example: "return foo;"
append(" ");
// ... | 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(" ");
} els... | src/com/google/javascript/jscomp/CodeConsumer.java | alert(/ / / / /) | alert(/ / / / /);
output: alert(/ /// /);
should be: alert(/ // / /); | 181 | 202 |
Closure-51 | void addNumber(double x) {
// This is not pretty printing. This is to prevent misparsing of x- -4 as
// x--4 (which is a syntax error).
char prev = getLastChar();
if (x < 0 && prev == '-') {
add(" ");
}
if ((long) x == x) {
long value = (long) x;
long mantissa = value;
int exp = 0;
if (... | void addNumber(double x) {
// This is not pretty printing. This is to prevent misparsing of x- -4 as
// x--4 (which is a syntax error).
char prev = getLastChar();
if (x < 0 && prev == '-') {
add(" ");
}
if ((long) x == x && !isNegativeZero(x)) {
long value = (long) x;
long mantissa = value;
... | src/com/google/javascript/jscomp/CodeConsumer.java | -0.0 becomes 0 even in whitespace mode | Affects dart: http://code.google.com/p/dart/issues/detail?id=146 | 233 | 260 |
Closure-53 | private void replaceAssignmentExpression(Var v, Reference ref,
Map<String, String> varmap) {
// Compute all of the assignments necessary
List<Node> nodes = Lists.newArrayList();
Node val = ref.getAssignedValue();
blacklistVarReferencesInTree(val, v.scope);
Precondition... | private void replaceAssignmentExpression(Var v, Reference ref,
Map<String, String> varmap) {
// Compute all of the assignments necessary
List<Node> nodes = Lists.newArrayList();
Node val = ref.getAssignedValue();
blacklistVarReferencesInTree(val, v.scope);
Precondition... | src/com/google/javascript/jscomp/InlineObjectLiterals.java | compiler-20110811 crashes with index(1) must be less than size(1) | What steps will reproduce the problem?
Run compiler on https://raw.github.com/scottschiller/SoundManager2/master/script/soundmanager2-nodebug.js
You can copy this into the Appspot closure compiler to see the error:
// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level SIMPLE_OPTIMIZATIONS
/... | 303 | 360 |
Closure-57 | private static String extractClassNameIfGoog(Node node, Node parent,
String functionName){
String className = null;
if (NodeUtil.isExprCall(parent)) {
Node callee = node.getFirstChild();
if (callee != null && callee.getType() == Token.GETPROP) {
String qualifiedName = callee.getQualifiedName();
... | 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();
... | src/com/google/javascript/jscomp/ClosureCodingConvention.java | compiler crashes when goog.provide used with non string | What steps will reproduce the problem?
1. insert goog.provide(some.function);
2. compile.
3.
What is the expected output? What do you see instead?
This should give an error diagnostic. What it gives is:
java.lang.RuntimeException: java.lang.RuntimeException: INTERNAL COMPILER ERROR.
Please email js-compiler@goog... | 188 | 204 |
Closure-58 | private void computeGenKill(Node n, BitSet gen, BitSet kill,
boolean conditional) {
switch (n.getType()) {
case Token.SCRIPT:
case Token.BLOCK:
case Token.FUNCTION:
return;
case Token.WHILE:
case Token.DO:
case Token.IF:
computeGenKill(NodeUtil.getConditionExpression(n), gen,... | 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,... | src/com/google/javascript/jscomp/LiveVariablesAnalysis.java | Online CC bug: report java error. | What steps will reproduce the problem?
1. open http://closure-compiler.appspot.com/
2. input js code:
function keys(obj) {
var a = [], i = 0;
for (a[i++] in obj)
;
return a;
}
3. press [compile] button.
What is the expected output? What do you see instead?
Except OK. See java error.
Wh... | 178 | 263 |
Closure-61 | static boolean functionCallHasSideEffects(
Node callNode, @Nullable AbstractCompiler compiler) {
if (callNode.getType() != Token.CALL) {
throw new IllegalStateException(
"Expected CALL node, got " + Token.name(callNode.getType()));
}
if (callNode.isNoSideEffectsCall()) {
return false;
}
... | 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;
}
... | src/com/google/javascript/jscomp/NodeUtil.java | Closure removes needed code. | What steps will reproduce the problem?
1. Try the following code, in Simple mode
Math.blah = function(test) { test.a = 5; };
var test = new Object();
Math.blah(test);
2. The output is
Math.blah=function(a){a.a=5};var test={};
What is the expected output? What do you see instead?
Note that Math.blah(test) was re... | 926 | 976 |
Closure-62 | private String format(JSError error, boolean warning) {
// extract source excerpt
SourceExcerptProvider source = getSource();
String sourceExcerpt = source == null ? null :
excerpt.get(
source, error.sourceName, error.lineNumber, excerptFormatter);
// formatting the message
StringBuilder b = ... | 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 = ... | src/com/google/javascript/jscomp/LightweightMessageFormatter.java | Column-indicating caret is sometimes not in error output | For some reason, the caret doesn't always show up in the output when there are errors.
When test.js looks like this:
>alert(1;
, the output is this:
>java -jar compiler.jar --js test.js
test.js:1: ERROR - Parse error. missing ) after argument list
1 error(s), 0 warning(s)
However, when test.js looks like t... | 66 | 111 |
Closure-67 | private boolean isPrototypePropertyAssign(Node assign) {
Node n = assign.getFirstChild();
if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)
&& n.getType() == Token.GETPROP
) {
// We want to exclude the assignment itself from the usage list
boolean isChainedProperty =
n.getFirst... | private boolean isPrototypePropertyAssign(Node assign) {
Node n = assign.getFirstChild();
if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)
&& n.getType() == Token.GETPROP
&& assign.getParent().getType() == Token.EXPR_RESULT) {
// We want to exclude the assignment itself from the usage lis... | src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java | Advanced compilations renames a function and then deletes it, leaving a reference to a renamed but non-existent function | If we provide the below code to advanced:
function A() {
this._x = 1;
}
A.prototype['func1'] = // done to save public reference to func1
A.prototype.func1 = function() {
this._x = 2;
this.func2();
}
A.prototype.func2 = function() {
this._x = 3;
this.func3();
}
window['A'] = A;
We get the outp... | 314 | 334 |
Closure-69 | private void visitCall(NodeTraversal t, Node n) {
Node child = n.getFirstChild();
JSType childType = getJSType(child).restrictByNotNullOrUndefined();
if (!childType.canBeCalled()) {
report(t, n, NOT_CALLABLE, childType.toString());
ensureTyped(t, n);
return;
}
// A couple of types can be called ... | 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 ... | src/com/google/javascript/jscomp/TypeCheck.java | Compiler should warn/error when instance methods are operated on | What steps will reproduce the problem?
1. Compile and run the following code:
goog.require('goog.graphics.Path');
function demo() {
var path = new goog.graphics.Path();
var points = [[1,1], [2,2]];
for (var i = 0; i < points.length; i++) {
(i == 0 ? path.moveTo : path.lineTo)(points[i][0], p... | 1,544 | 1,590 |
Closure-7 | public JSType caseObjectType(ObjectType type) {
if (value.equals("function")) {
JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);
return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null;
// Objects are restricted to "Function", subtypes are left
// Only filter out subtypes of "... | public JSType caseObjectType(ObjectType type) {
if (value.equals("function")) {
JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);
if (resultEqualsValue) {
// Objects are restricted to "Function", subtypes are left
return ctorType.getGreatestSubtype(type);
} else {
// Only filter out... | src/com/google/javascript/jscomp/type/ChainableReverseAbstractInterpreter.java | Bad type inference with goog.isFunction and friends | experimental/johnlenz/typeerror/test.js:16: WARNING - Property length
never defined on Number
var i = object.length;
This is the reduced test case:
/**
* @param {*} object Any object.
* @return {boolean}
*/
test.isMatched = function(object) {
if (goog.isDef(object)) {
if (goog.isFunction(obje... | 610 | 618 |
Closure-70 | private void declareArguments(Node functionNode) {
Node astParameters = functionNode.getFirstChild().getNext();
Node body = astParameters.getNext();
FunctionType functionType = (FunctionType) functionNode.getJSType();
if (functionType != null) {
Node jsDocParameters = functionType.getParametersNode();
i... | 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();
i... | src/com/google/javascript/jscomp/TypedScopeCreator.java | unexpected typed coverage of less than 100% | What steps will reproduce the problem?
1. Create JavaScript file:
/*global window*/
/*jslint sub: true*/
/**
* @constructor
* @param {!Element} element
*/
function Example(element) {
/**
* @param {!string} ns
* @param {!string} name
* @return {undefined}
*/
this.appendElement... | 1,734 | 1,753 |
Closure-81 | Node processFunctionNode(FunctionNode functionNode) {
Name name = functionNode.getFunctionName();
Boolean isUnnamedFunction = false;
if (name == null) {
name = new Name();
name.setIdentifier("");
isUnnamedFunction = true;
}
Node node = newNode(Token.FUNCTION);
Node newName = transform(name);
i... | 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 fu... | src/com/google/javascript/jscomp/parsing/IRFactory.java | An unnamed function statement statements should generate a parse error | An unnamed function statement statements should generate a parse error, but it does not, for example:
function () {};
Note: Unnamed function expression are legal:
(function(){}); | 513 | 562 |
Closure-82 | public final boolean isEmptyType() {
return isNoType() || isNoObjectType() || isNoResolvedType();
} | public final boolean isEmptyType() {
return isNoType() || isNoObjectType() || isNoResolvedType() ||
(registry.getNativeFunctionType(
JSTypeNative.LEAST_FUNCTION_TYPE) == this);
} | src/com/google/javascript/rhino/jstype/JSType.java | .indexOf fails to produce missing property warning | The following code compiled with VERBOSE warnings or with the missingProperties check enabled fails to produce a warning or error:
var s = new String("hello");
alert(s.toLowerCase.indexOf("l"));
However, other string functions do properly produce the warning:
var s = new String("hello");
alert(s.toLowerCase.sub... | 162 | 164 |
Closure-83 | public int parseArguments(Parameters params) throws CmdLineException {
String param = params.getParameter(0);
if (param == null) {
setter.addValue(true);
return 0;
} else {
String lowerParam = param.toLowerCase();
if (TRUES.contains(lowerParam)) {
setter.addValue(true);
} else if (FALSE... | public int parseArguments(Parameters params) throws CmdLineException {
String param = null;
try {
param = params.getParameter(0);
} catch (CmdLineException e) {}
if (param == null) {
setter.addValue(true);
return 0;
} else {
String lowerParam = param.toLowerCase();
if (TRUES.contains(lowe... | src/com/google/javascript/jscomp/CommandLineRunner.java | Cannot see version with --version | What steps will reproduce the problem?
1. Download sources of latest (r698) command-line version of closure compiler.
2. Build (with ant from command line).
3. Run compiler (java -jar compiler.jar --version).
What is the expected output?
Closure Compiler (http://code.google.com/closure/compiler)
Version: 698
Bui... | 333 | 351 |
Closure-86 | static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) {
switch (value.getType()) {
case Token.ASSIGN:
// A result that is aliased by a non-local name, is the effectively the
// same as returning a non-local name, but this doesn't matter if the
// value is immutable.
retu... | static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) {
switch (value.getType()) {
case Token.ASSIGN:
// A result that is aliased by a non-local name, is the effectively the
// same as returning a non-local name, but this doesn't matter if the
// value is immutable.
retu... | src/com/google/javascript/jscomp/NodeUtil.java | side-effects analysis incorrectly removing function calls with side effects | Sample Code:
---
/** @constructor */
function Foo() {
var self = this;
window.setTimeout(function() {
window.location = self.location;
}, 0);
}
Foo.prototype.setLocation = function(loc) {
this.location = loc;
};
(new Foo()).setLocation('http://www.google.com/');
---
The setLocation call wil... | 2,424 | 2,489 |
Closure-87 | private boolean isFoldableExpressBlock(Node n) {
if (n.getType() == Token.BLOCK) {
if (n.hasOneChild()) {
Node maybeExpr = n.getFirstChild();
// IE has a bug where event handlers behave differently when
// their return value is used vs. when their return value is in
// an EXPR_RESULT... | private boolean isFoldableExpressBlock(Node n) {
if (n.getType() == Token.BLOCK) {
if (n.hasOneChild()) {
Node maybeExpr = n.getFirstChild();
if (maybeExpr.getType() == Token.EXPR_RESULT) {
// IE has a bug where event handlers behave differently when
// their return value is used vs. w... | src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java | IE8 error: Object doesn't support this action | What steps will reproduce the problem?
1. Use script with fragment like
if (e.onchange) {
e.onchange({
_extendedByPrototype: Prototype.emptyFunction,
target: e
});
}
2. Compile with Compiler (command-line, latest version)
3. Use in IE8
What is the expected output?
Script:
... | 519 | 538 |
Closure-88 | private VariableLiveness isVariableReadBeforeKill(
Node n, String variable) {
if (NodeUtil.isName(n) && variable.equals(n.getString())) {
if (NodeUtil.isLhs(n, n.getParent())) {
// The expression to which the assignment is made is evaluated before
// the RHS is evaluated (normal left to right eval... | 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 ... | src/com/google/javascript/jscomp/DeadAssignmentsElimination.java | Incorrect assignment removal from expression in simple mode. | function closureCompilerTest(someNode) {
var nodeId;
return ((nodeId=someNode.id) && (nodeId=parseInt(nodeId.substr(1))) && nodeId>0);
}
COMPILES TO:
function closureCompilerTest(b){var a;return b.id&&(a=parseInt(a.substr(1)))&&a>0};
"nodeId=someNode.id" is replaced with simply "b.id" which is incorrect ... | 323 | 347 |
Closure-91 | public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (n.getType() == Token.FUNCTION) {
// Don't traverse functions that are constructors or have the @this
// or @override annotation.
JSDocInfo jsDoc = getFunctionJsDocInfo(n);
if (jsDoc != null &&
(jsDoc.isConstructor() ||
... | 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() ||
... | src/com/google/javascript/jscomp/CheckGlobalThis.java | support @lends annotation | Some javascript toolkits (dojo, base, etc.) have a special way of declaring (what java calls) classes, for example in dojo:
dojo.declare("MyClass", [superClass1, superClass2], {
foo: function(){ ... }
bar: function(){ ... }
});
JSDoc (or at least JSDoc toolkit) supports this via annotations:
/**
... | 82 | 146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.